DafeUltimateLibDAFE Ultimate Library: The Universal AI Dashboard & Analysis System
This is the operating system for your next generation of trading tools. Welcome to the future of on-chart intelligence.
█ PHILOSOPHY: BEYOND THE INDICATOR, INTO THE CONSCIOUSNESS
For decades, technical analysis has been a monologue. We load indicators onto our charts, and they give us static, one-dimensional answers: a line, a number, a crossover. They provide data, but they offer no wisdom, no context, no actionable intelligence. They are tools without a mind.
The DAFE Ultimate Library was created to fundamentally shatter this paradigm. It was not designed to be another indicator, but to be the very brain that powers all of your future indicators. This is a professional-grade, open-source library that allows any Pine Script developer to integrate a sophisticated, AI-powered analytical and visualization engine into their own scripts with just a few lines of code.
This library transforms your indicator from a simple data plotter into an intelligent trading assistant. It takes in raw metrics—RSI, MACD, Volume, Volatility—and synthesizes them into a rich, multi-dimensional analysis, complete with a primary bias, confidence score, market state assessment, and a set of dynamic, actionable recommendations. It doesn't just give you the "what"; it gives you the " so what? "
█ WHAT IS THIS LIBRARY? A REVOLUTION IN PINE SCRIPT
This is a foundational shift in what's possible within the TradingView ecosystem.
A Universal AI Brain: At its core is a powerful analysis engine. You feed it any number of metrics from your own custom script—each with its own type (bounded, zero-centric, trend, etc.) and weight—and the AI synthesizes them into a single, cohesive analysis. It's like having a quantitative analyst living inside your indicator.
The ASCII Art Visualization Core: This is the soul of the library. We have pushed the boundaries of what's possible with Pine Script's table and label objects to create a stunning, fully animated, and customizable ASCII art interface. This is not a gimmick; it is a high-information-density display that brings your data to life in a way that is both beautiful and intuitively understandable. Choose from multiple "genders" (Male, Female, Droid) and themes to create an AI assistant that fits your personal aesthetic.
Open & Extensible Framework: This is a library, not a closed black box. It is designed to be the foundation for a new generation of "smart" indicators. I provide a simple, powerful API (Application Programming Interface) that allows any developer to plug their own unique metrics into the DAFE AI brain and instantly gain access to its analytical and visualization power.
Human-Readable Intelligence: The output is not just numbers. The AI communicates in natural language. It provides you with its "Thoughts" ("Bullish momentum across 3 metrics," "Structural weakness developing") and a set of "Recommended Actions" ("ACCUMULATE on pullbacks," "TIGHTEN stops") that adapt in real-time to the changing market conditions.
█ HOW IT WORKS: THE ARCHITECTURE OF AN AI
The library operates on a simple but powerful three-stage pipeline.
Stage 1: Metric Ingestion (The Senses)
As a developer, you first define the "senses" of your AI. Using the library's simple create_metric functions, you tell the AI what to look at. This is a highly flexible system that can handle any type of data your indicator produces. You define the metric's name, its current value, its "mode" of operation, and its relative importance (weight). The available modes allow the AI to correctly interpret any data source:
metric_bounded: For oscillators like RSI or Stochastics that move between set levels (e.g., 0-100).
metric_zero: For indicators like MACD or a Momentum oscillator that fluctuate around a central zero line.
metric_trend: For moving averages or trend lines, analyzing their position relative to price.
metric_volume / metric_volatility: Specialized metrics for analyzing volume and volatility events against high/low thresholds.
Stage 2: The Analysis Engine (The Brain)
On every bar, the library takes the updated metric values and feeds them into its core analytical model. This is where the magic happens.
Normalization: Each metric is processed according to its "mode" and converted into a standardized signal score from -100 (extremely bearish) to +100 (extremely bullish). This allows the AI to compare apples and oranges—an RSI of 80 can now be directly compared to a MACD histogram of 0.5.
Synthesis: The AI calculates a composite score by taking a weighted average of all the individual metric signals. This gives a single, unified view of the market's state based on all available evidence.
State Assessment: It analyzes the distribution of signals (how many are bullish vs. bearish), the number of "extreme" readings (e.g., overbought, high volume), and the overall composite score to determine the current Market State (e.g., "STRONG TREND," "MIXED SIGNALS," "EXTREME CONDITIONS").
Confidence Calculation: The magnitude of the final composite score is translated into a Confidence percentage, representing the strength of the AI's conviction in its current bias.
Natural Language Generation: Based on the final analysis, the engine selects the most appropriate "Thoughts" and "Recommended Actions" from its pre-programmed library of strategic heuristics, providing you with context and a potential game plan.
Stage 3: The Rendering Engine (The Face)
The final analysis is passed to the visualization core, which renders the complete AI Terminal on your chart. This is a masterwork of Pine Script's drawing capabilities.
The Face: The stunning ASCII art face is dynamically generated on every bar. Its Mood (Confident, Focused, Cautious, etc.) is directly determined by the AI's confidence level. Its eyes will even animate with a subtle, customizable Blink cycle, bringing the character to life and creating an unparalleled user experience.
The Dashboard: The surrounding terminal is built, displaying the primary bias, market state, confidence, and the detailed thoughts, active metrics, and recommended actions in a clean, retro-futuristic interface.
Theming: The entire display is colored according to your chosen theme, from the cool greens of "Matrix" to the vibrant pinks of "Neon," allowing for deep personalization.
█ A GUIDE FOR DEVELOPERS: INTEGRATING THE DAFE AI
We have made it incredibly simple to bring your indicators to life with the DAFE AI. This is the true purpose of the library—to empower you.
Import the Library: Add the following line to the top of your script import DskyzInvestments/DafeUltimateLib/1 as dafe
Define Your Metrics: In the barstate.isfirst block of your script, create an array and populate it with the metrics your indicator uses. For example:
var array my_metrics = array.new()
if barstate.isfirst
array.push(my_metrics, dafe.metric_bounded("RSI", 50.0, 70.0, 30.0, 1.5))
array.push(my_metrics, dafe.metric_zero("MACD Hist", 0.0, 0.5, 1.0))
Update Your Metrics: On every bar, update the values of your metrics.
dafe.update_metric(array.get(my_metrics, 0), ta.rsi(close, 14))
dafe.update_metric(array.get(my_metrics, 1), macd_histogram_value)
Configure & Render: Create a configuration object from user inputs and call the main render function.
dafe.DafeConfig my_config = dafe.quick_config("Droid", "Cyber")
dafe.render(my_metrics, my_config)
That's it. With these few steps, you have integrated a complete AI dashboard and analysis engine directly into your own script, saving you hundreds of hours of development time and providing your users with a revolutionary interface.
█ DEVELOPMENT PHILOSOPHY
The DAFE Ultimate Library was born from a desire to push the boundaries of Pine Script and to empower the entire TradingView developer community. We believe that the future of technical analysis is not just in creating more complex algorithms, but in building more intelligent and intuitive ways to interact with the data those algorithms provide. This library is our contribution to that future. It is an open-source tool designed to elevate the work of every developer who uses it, fostering a new era of "smart" indicators on the platform.
This library is designed to help you and your users make the best trades by providing a layer of objective, synthesized intelligence that filters out noise, quantifies confidence, and promotes a disciplined, analytical approach to the market.
█ A NOTE TO USERS & DISCLAIMER
THIS IS A LIBRARY: This script does nothing on its own. It is a powerful engine that must be integrated by other indicator developers. It is a tool for builders.
THE AI IS A GUIDE, NOT A GURU: The analysis provided is based on the mathematical synthesis of the metrics it is fed. It is a powerful decision-support tool, but it is not a crystal ball. All trading involves substantial risk.
GARBAGE IN, GARBAGE OUT: The quality of the AI's analysis is directly dependent on the quality and logic of the metrics it is given by the host indicator.
"The goal of a successful trader is to make the best trades. Money is secondary."
— Alexander Elder
Taking you to school. - Dskyz, Trade with DAFE.
Statistics
Entropy Divergence (No Repaint) [PhenLabs]📊 Entropy Divergence (No Repaint)
Version: PineScript™ v6
📌 Description
The Entropy Divergence Scalper (EDS) is a sophisticated trading indicator that applies information theory to market analysis. By calculating Shannon Entropy on price returns, it identifies periods when market behavior becomes more predictable and orderly—the ideal conditions for divergence-based trading.
Traditional divergence indicators generate signals regardless of market conditions, leading to many false signals during chaotic, high-entropy periods. EDS solves this by acting as an intelligent filter: it only triggers signals when entropy drops below your specified threshold, indicating that the market has entered a more structured, tradeable state.
This indicator is built with a strict non-repainting guarantee. All signals use barstate.isconfirmed and only appear after bar close, giving you reliable signals you can trust for live trading.
🚀 Points of Innovation
Shannon Entropy integration measures market randomness using information theory mathematics
Dual divergence engine detects both RSI and Volume divergences simultaneously
Entropy-filtered signals eliminate noise by only triggering in low-entropy (predictable) market conditions
100% non-repainting architecture ensures all signals are confirmed and historically accurate
Multi-layer confirmation combines entropy state, RSI divergence, and volume divergence for higher probability setups
Dynamic color visualization provides instant visual feedback on current market entropy state
🔧 Core Components
Shannon Entropy Calculator: Bins price returns into histograms and calculates entropy using H(X) = -Σ p(x) × log₂(p(x))
RSI Divergence Detector: Identifies when price makes lower lows while RSI makes higher lows (bullish) or price makes higher highs while RSI makes lower highs (bearish)
Volume Divergence Detector: Spots increasing volume interest at price lows (bullish) or decreasing conviction at price highs (bearish)
Pivot Detection System: Uses configurable lookback periods to identify and track price, RSI, and volume pivots
Signal Classification Engine: Labels signals as RSI, VOL, or RSI+VOL based on which divergences triggered
🔥 Key Features
Entropy Threshold Control: Set your preferred entropy level (default 2.5) to filter out signals during chaotic market periods
Configurable Smoothing: EMA smoothing on entropy values reduces noise while maintaining signal responsiveness
Flexible Pivot Detection: Adjust left/right lookback bars to tune sensitivity for different trading styles
Divergence Search Range: Control how far back the indicator looks for divergence patterns (20-200 bars)
Minimum Pivot Distance: Prevents false signals from pivots that are too close together
Complete Alert System: Four alert conditions for bullish signals, bearish signals, any signal, and low entropy zone entry
🎨 Visualization
Dynamic Entropy Line: Color gradient shifts from green (low entropy/tradeable) to orange (high entropy/chaotic)
Entropy Threshold Line: Dashed reference line shows your configured entropy threshold
Low Entropy Zone Fill: Background highlighting indicates when market is in tradeable low-entropy state
Scaled RSI Plot: RSI overlay scaled to fit the entropy pane for easy correlation analysis
Normalized Volume Bars: Volume displayed as columns normalized against 20-period average
Signal Labels: Clear LONG/SHORT labels with divergence type (RSI, VOL, or RSI+VOL)
Information Table: Real-time display of entropy value, state, RSI, and current signal status
📖 Usage Guidelines
Entropy Lookback Period — Default: 20, Range: 5-100 — Controls how many bars are used for entropy calculation; higher values provide smoother readings but slower response
Histogram Bins — Default: 10, Range: 5-50 — Number of bins for probability distribution; more bins provide finer granularity
Low Entropy Threshold — Default: 2.5, Range: 0.5-4.0 — Signals only trigger when entropy drops below this value; lower settings are more selective
Entropy Smoothing — Default: 3, Range: 1-10 — EMA smoothing applied to raw entropy values for noise reduction
RSI Length — Default: 14, Range: 5-50 — Standard RSI calculation period
Pivot Lookback Left — Default: 5, Range: 2-20 — Bars to the left for pivot detection
Pivot Lookback Right — Default: 2, Range: 1-10 — Bars to the right for pivot confirmation; lower values produce faster signals
Divergence Search Range — Default: 60, Range: 20-200 — Maximum bars to look back for divergence comparison
Min Bars Between Pivots — Default: 5, Range: 3-30 — Minimum distance between pivots for valid divergence detection
✅ Best Use Cases
Scalping during low-volatility consolidation periods when entropy drops and price becomes more predictable
Swing trade entry timing by waiting for divergence signals in low-entropy market conditions
Trend reversal identification when both RSI and Volume divergences align with low entropy readings
Multi-timeframe confirmation by checking entropy state on higher timeframes before taking signals
Filtering existing strategies by adding entropy as a confirmation layer to reduce false signals
⚠️ Limitations
Signals appear with a delay due to pivot confirmation requirements (pivotLookbackRight bars after pivot forms)
May generate fewer signals during strongly trending markets where entropy remains elevated
Entropy threshold requires optimization for different instruments and timeframes
Not designed for high-frequency trading due to bar-close confirmation requirement
Divergences can fail in extremely strong trends where momentum overwhelms the signal
💡 What Makes This Unique
First indicator to combine Shannon Entropy filtering with multi-factor divergence detection
Information theory approach provides mathematical foundation for identifying tradeable market states
Triple confirmation requirement (low entropy + divergence + bar close) significantly reduces false signals
Non-repainting guarantee makes it suitable for strategy backtesting and live trading
Open-source PineScript v6 code allows traders to understand and customize the methodology
🔬 How It Works
Step 1 — Entropy Calculation: The indicator calculates logarithmic returns, bins them into a histogram, and computes Shannon Entropy to measure market randomness
Step 2 — Entropy Filtering: When smoothed entropy drops below the threshold, the market is considered to be in a tradeable low-entropy state
Step 3 — Pivot Detection: The system continuously tracks price, RSI, and volume pivots using configurable lookback parameters
Step 4 — Divergence Analysis: When a new pivot is confirmed, the indicator compares it against previous pivots to detect bullish or bearish divergences
Step 5 — Signal Generation: A final signal only triggers when low entropy conditions coincide with a confirmed divergence pattern on a closed bar
💡 Note:
This indicator is designed for educational purposes and technical analysis. Always use proper risk management and never risk more than you can afford to lose. The non-repainting guarantee means signals will only appear after bar close—watch the indicator in real-time to verify this behavior. For optimal results, consider combining EDS signals with support/resistance levels and overall market context.
Z-Score ProZ-Score Pro - Complete Description
This is an **advanced mean reversion indicator** that measures how many standard deviations the current price is from its average. It's ideal for identifying market extremes and trading opportunities.
What is the Z-Score?
The Z-Score is a statistical measure that answers: **"How far is the price from normal?"**
- **Z = 0**: Price is at its average
- **Z = +2**: Price is 2 standard deviations above (overbought)
- **Z = -2**: Price is 2 standard deviations below (oversold)
- **Z > +3** or **Z < -3**: Very rare extremes (occur ~0.3% of the time)
Main Features
### 1. **Flexible Calculation**
- **SMA or EMA**: Choose between simple or exponential moving average
- **Adjustable period**: Default 20 periods
- **Smoothing**: Option to smooth the Z-Score to reduce noise
### 2. **Multiple Levels**
- **±1.0**: Caution zone
- **±2.0**: Overbought/Oversold (68% statistical confidence)
- **±3.0**: Rare extremes (99.7% statistical confidence)
### 3. **Trading Signals**
The indicator generates automatic signals based on:
**Buy Signals (BUY)**:
- Z-Score is in oversold zone
- Momentum changes from negative to positive (price stops falling)
**Sell Signals (SELL)** :
- Z-Score is in overbought zone
- Momentum changes from positive to negative (price stops rising)
**Aggressiveness Levels**:
- **Conservative**: Only signals at extremes (±3.0)
- **Normal**: Signals at ±2.0 (recommended)
- **Aggressive**: More frequent signals at ±1.5
### 4. **Divergence Detection**
**Bullish Divergence** (aqua marker):
- Price makes a lower low
- Z-Score makes a higher low
- Indicates weakening of downtrend
**Bearish Divergence** (fuchsia marker):
- Price makes a higher high
- Z-Score makes a lower high
- Indicates weakening of uptrend
---
## Visualization
### Dynamic Colors
- **Bright red**: Z-Score > 2 and rising (strong overbought)
- **Orange**: Z-Score > 1 and rising
- **Purple**: Neutral zone rising
- **Transparent green**: Z-Score falling (any level)
### Background Zones
- **Intense red**: Extreme overbought (Z > 3)
- **Soft orange**: Overbought (Z > 2)
- **Intense green**: Extreme oversold (Z < -3)
- **Soft lime**: Oversold (Z < -2)
### Info Table (top right corner)
Shows in real-time:
- **Current Z-Score**: Numeric value with color
- **Status**: Extreme OB/OS, Overbought, Oversold, or Neutral
- **Momentum**: Rising ↗ or Falling ↘
- **Mean**: Current average value
- **Std Dev**: Current standard deviation
---
## Alert System
The indicator includes **8 types of alerts**:
1. **Buy Signal**: When entry conditions are met
2. **Sell Signal**: When exit conditions are met
3. **Overbought**: When crossing above +2.0
4. **Oversold**: When crossing below -2.0
5. **Extreme Overbought**: When reaching +3.0
6. **Extreme Oversold**: When reaching -3.0
7. **Bullish Divergence**: Potential reversal up
8. **Bearish Divergence**: Potential reversal down
---
## How to Use It
### **Mean Reversion Strategy**
1. Wait for Z-Score to reach ±2 or beyond
2. Wait for BUY/SELL signal (momentum reversal)
3. Enter trade in opposite direction of extreme
4. Exit when Z-Score returns to zero
### **Divergence Strategy**
1. Identify divergence markers (DIV)
2. Confirm with momentum change
3. Enter in direction of divergence
4. Use Z-Score levels as targets
### **Multi-Timeframe Analysis**
- **Short-term** (5-15 min): Scalping with aggressive mode
- **Medium-term** (1H-4H): Swing trading with normal mode
- **Long-term** (Daily): Position trading with conservative mode
---
## Best Practices
**Do**:
- Use in ranging/sideways markets
- Combine with support/resistance levels
- Wait for momentum confirmation
- Use conservative mode in trending markets
**Don't**:
- Trade against strong trends
- Ignore divergences
- Use alone without confirmation
- Over-trade in low volatility
---
## Statistical Background
The Z-Score follows a **normal distribution**:
- **68%** of values fall within ±1 standard deviation
- **95%** of values fall within ±2 standard deviations
- **99.7%** of values fall within ±3 standard deviations
When price reaches Z = ±2, there's a **95% probability** it will revert toward the mean, making it a powerful mean reversion tool.
---
##Customization Options
All aspects are customizable:
- Calculation method and periods
- Visual colors and transparency
- Signal sensitivity
- Alert preferences
- Level thresholds
- Background zones on/off
Herramienta Risk:Reward Pro - MECTRADEROverview: This is an advanced Risk/Reward management tool specifically designed for traders who execute based on Ticks (perfect for Futures like NQ/ES, Gold, or Forex). The main focus of this script is visual clarity and precision.
Key Features:
✅ Clean Visuals (No Dimming): Built using linefill technology with a 92% transparency rate. This ensures the price action remains vibrant and clear. Unlike standard boxes, this tool does not darken or "muddy" the candles when the price enters the zone.
✅ Tick-Based Calculation: Define your Stop Loss and up to 5 Take Profit levels using Ticks for maximum precision.
✅ Toggleable TP Levels: You can enable or disable TP1 through TP5 individually to match your scaling-out strategy.
✅ Dynamic Labels: Automatically displays the level name (Entry, SL, TP) along with the exact price value on the right-side scale.
✅ Long/Short Toggle: Switch between buy and sell setups instantly with a single drop-down selection.
How to use:
Add the script to your chart.
Open Settings and choose your Mode (LONG or SHORT).
Use the Precision Crosshair icon next to "Price Entry" to pick your execution level directly from the chart.
Adjust your Stop Loss and Profit Ticks.
The tool will project your risk zones professionally without interfering with your technical analysis.
Risk:Reward Tool Pro - MECTRADER (Minimalist)This is an optimized and refined version of my previous Risk/Reward tool. In this update, I have focused on visual clarity by removing all background color fills (shaded zones) to provide a much more minimalist and professional charting experience.
Key Improvements:
Zero Visual Distractions: All linefills have been removed, allowing traders to focus purely on price action and market structure without cluttered backgrounds.
Clean Aesthetics: Take Profit levels feature dashed lines for easy target identification, while Entry and Stop Loss levels remain solid for clear boundary definition.
Performance Focused: The script has been streamlined for a lightweight footprint, making it ideal for users who run multiple indicators simultaneously.
Core Features:
Tick-Based Calculation: Automatically calculate up to 5 Take Profit levels based on ticks.
Quick SL Setup: Simple input for Stop Loss distance.
Dynamic Labels: Real-time price display for every level on the right side of the chart.
Dual Mode: Full support for both Long and Short positions.
Designed for traders who demand technical precision without sacrificing the visual workspace.
ATR + ADX Expansion This script plots in real time a shorter period ATR compared to a longer period ATR allowing one to see if the market has above or below average volatility. This helps avoid choppy sideways markets.
Secondly, the table shows whether ADX is expanding above its signal line, or contracting below it's signal line further identifying a market in expansion or contraction.
Any set up must be deployed in a healthy market environment, this indicator measures core statistics in real time to allow you see at a glance what state the market is in.
Fixed Risk + Contracts 2.0This is the upgraded version of my Contracts/Risk indicator, released in January 2026. Users will trade responsibly (and never overleverage again!)
1. Pre-Select Your Ticker
MES ES
NQ MNQ
MYM YM
M2K MCL MGC
GC SIL SI
2. Input Current Account Balance and Risk % Each Trade To Grow Your Account
3. Input Stop Amount In Ticks (Use Position Tool for ease)
4. Contract Risk Is Calculated Automatically!
Add to your favourites and comment below if you have any suggestions :)
ETF-CFD Ratio Bridge
This indicator helps traders visualize the relationship between ETFs and their corresponding CFD/Spot instruments. It allows you to trade on one chart while monitoring the equivalent price levels of the other instrument without mental math or switching screens.
Features
1. Ratio Table
A customizable table displayed on the chart (default: Top Right) that shows:
- Pair : The ETF and CFD pair being monitored.
- Ratio : The calculated price ratio (ETF / CFD).
- Prices : Real-time prices for both instruments.
2. Companion Price Label
A dynamic label that moves with the current price candle.
- Displays the equivalent price of the paired instrument.
- Example : If you are viewing SPY , the label shows the equivalent US500 price next to the candle.
3. Left Virtual Scale
A custom vertical axis drawn on the left side of the chart.
- Shows price levels for the companion instrument corresponding to the current visible chart range.
- Allows you to read "CFD prices" directly on an "ETF chart" (and vice versa) via the Y-axis.
4. Historical Levels lines
Visualizes recent market structure converted to the companion price.
- HH(x) : Highest High of the last X bars (default: 20).
- LL(x) : Lowest Low of the last X bars.
- Dashed lines extend to the right with labels showing the converted price at those key levels.
5. Closed Market Handling
Ensures the indicator remains useful even when the ETF market is closed (e.g., after hours) while the Futures/CFD market is open.
- Automatic Detection : The script detects if the ETF market is closed based on the timestamp.
- Fixed Ratio : Automatically switches to a user-defined "Fixed Ratio" when the ETF is closed.
- Continuous Updates : Prevents values from freezing, calculating a synthetic "Shadow Price" for the closed asset so you can continue to see projected levels based on the live CFD market.
Technical Explanation (The Math)
The indicator functions by calculating a dynamic ratio between the two instruments and using it to convert price levels.
Formulas
1. Calculate Ratio :
Ratio = Price(ETF) / Price(CFD)
2. Conversion :
- ETF Chart → CFD Price :
Equivalent CFD Price = Current ETF Price / Ratio
- CFD Chart → ETF Price :
Equivalent ETF Price = Current CFD Price × Ratio
Example (SPY vs US500)
- Scenario : You are trading on the SPY chart.
- Current Prices :
- SPY (ETF) = $500
- US500 (CFD) = $5000
- Step 1 : Calculate Ratio
- 500 / 5000 = 0.10
- Step 2 : Calculate Equivalent Price
- If SPY moves to $505 , what is the US500 equivalent?
- 505 / 0.10 = 5050
- The indicator will display "US500: 5050" on the label and scale.
Supported Pairs
SPY (AMEX) = US500
GLD (AMEX) = XAUUSD
SLV (AMEX) = XAGUSD
IWM (AMEX) = US2000
QQQ (NASDAQ) = NAS100
IBIT (NASDAQ) = BTCUSD
Settings
- Symbols : Customize the ticker symbols for each pair if your broker uses different names.
- Fixed Ratio (Closed) : Manually adjust the fallback ratio used when the ETF market is closed (default values provided).
- Visuals :
- Toggle Table, Labels, Scale, and Historical Lines on/off.
- Customize colors, text sizes, and positions.
- Right Offset (Bars from Current) : Adjusts how far back (from the current live bar) the Left Virtual Scale is drawn. Increasing this moves the scale further to the left.
- Historical Levels :
- Lookback Length : Number of bars to check for High/Low calculations (Default: 20).
Wick Ranges (GG)Simple data box that tracks candle wick largest, smallest, and average sizes by price within specified time ranges. Displays labels for upper and lower wicks of current candle.
Helpful if your entry model is entering on the close/open of momentum candles.
-GG
DafeVisualsLibDafeVisualsLib: The Architect - The Intelligent Visualization Engine
This is not a library of drawing functions. This is an AI-powered artist and data scientist that lives in your code. It automates the complex, time-consuming process of data analysis and visualization, allowing you to focus on what truly matters: your trading ideas.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND PLOTTING, INTO PERCEPTION
For too long, the world of technical indicator development has been bifurcated. On one side, you have the quantitative analyst, obsessed with mathematical purity but often displaying their work in a crude, unintuitive manner. On the other, you have the visual designer, creating beautiful indicators that often lack analytical depth. The result for the end-user is a compromise: either a tool that is powerful but ugly and hard to interpret, or one that is beautiful but analytically shallow.
The DafeVisualsLib was created to shatter this compromise. Its core philosophy is that great analysis and great visualization are not separate disciplines; they are two sides of the same coin . An indicator should not just present data; it should communicate intelligence. It should automatically understand the nature of the data it is given and render it in the most effective, intuitive, and aesthetically pleasing way possible.
This library is an "Architect." You provide it with the raw materials—a simple data series like an RSI or a moving average—and it handles the entire complex process of analysis, configuration, and rendering. It is the ultimate accelerator for developers, saving hundreds of hours of boilerplate code, and the ultimate upgrade for traders, providing a level of clarity and visual intelligence previously unseen on this platform.
█ CHAPTER 2: THE CORE INNOVATION - THE "ANALYZE, THEN RENDER" PARADIGM
The DafeVisualsLib operates on a revolutionary two-stage pipeline that sets it apart from any other tool.
STAGE 1: The analyze() Function (The Data Scientist)
This is the brain. Before a single line is drawn, this function performs a sophisticated statistical analysis on your raw data series to understand its fundamental character. It asks the critical questions that a human analyst would:
What type of data is this? It automatically detects if your data is a bounded "oscillator" like an RSI, a zero-centric "momentum" indicator like MACD, a "price"-based line like a moving average, or a "volume"-based metric.
What is the current market regime? It analyzes the data's volatility (using the coefficient of variation) to classify the current environment as a low-volatility "squeeze," a moderate-volatility "trend," or a high-volatility "volatile" state.
Where is the data in its cycle? It normalizes the data to a 0-100 scale and determines if it is currently at a statistical "extreme."
The output of this stage is a MetricAnalysis object—a complete analytical report on the DNA of your data.
STAGE 2: The auto_config() Function (The Artist & Physicist)
This is where the magic happens. This function takes the analytical report from analyze() and uses it to make a series of intelligent, context-aware decisions about how the data should be visualized.
Intelligent Color Logic: It doesn't just use one color. For an oscillator, it will create a beautiful heatmap gradient. For a momentum indicator, it will use a binary bull/bear color scheme.
Neon Physics: It separates the color into a solid c_core and a transparent c_glow. The opacity of the glow is not static; it is dynamically controlled by the detected market regime. In a "volatile" regime, the glow becomes bright and intense. In a "squeeze," it becomes dim and subtle.
Adaptive Style & Width: It automatically adjusts the plot style and line width. A "momentum" indicator will be rendered as a histogram by default. A "price" line will be thick and bold in a volatile market and thin and clean in a calm market.
Smart Zones: If it detects that the data is an "oscillator," it will automatically recommend showing overbought/oversold zones and provide the standard 70/30 levels.
The output of this stage is a PlotConfig object—a complete, ready-to-use set of plotting instructions, intelligently tailored to your specific data and the current market conditions.
█ CHAPTER 3: THE DEVELOPER'S TOOLKIT - A MASTERCLASS IN EFFICIENCY
This library is a gift to Pine Script developers. It is a suite of powerful, high-level functions designed to simplify your workflow and elevate your final product.
The Theme Engine
Forget hard-coding colors. The get_theme() function provides access to a library of professionally designed, high-contrast color themes ("Neon," "Cyber," "Matrix," "Gold," etc.). Each Theme object contains a complete palette for primary, secondary, accent, bull, bear, and neutral colors, ensuring perfect visual consistency across your entire indicator.
The UI & HUD Helpers
Building user interfaces with tables can be tedious. This library provides a suite of helper functions to make it effortless.
smart_text(): Automatically selects black or white text for optimal contrast against any background color.
draw_bar(): Creates a clean, beautiful ASCII progress bar from a simple percentage value.
draw_stars(): Creates a five-star rating visualization.
gradient_color(): A powerful function for creating smooth color transitions.
get_signal_style() & get_zone_style(): High-level functions that return complete styling configurations for signals and support/resistance zones based on your chosen theme.
The Simplicity of Integration: A 4-Step Workflow
The true beauty of the DafeVisualsLib is its simplicity. You can create a stunning, intelligent, and fully functional indicator in just four steps:
Import the library: import YourUsername/DafeVisualsLib/1 as viz
Get your theme: viz.Theme theme = viz.get_theme("Neon")
Calculate your metric: float rsi = ta.rsi(close, 14)
Let the Architect do the work: viz.PlotConfig cfg = viz.auto_config(rsi, "RSI", theme)
Plot the result: plot(cfg.value, cfg.title, cfg.c_core, cfg.width)
In these few lines, the library has automatically analyzed your RSI, determined the market regime, selected the appropriate plot style, calculated a dynamic color gradient with a physics-based glow, and adapted the line width to the current volatility. This is the power of the Architect.
█ CHAPTER 4: DEVELOPMENT PHILOSOPHY
The DafeVisualsLib was born from a desire to democratize elite-level indicator design. For too long, the ability to create beautiful, context-aware, and intuitively designed indicators has been the domain of a select few developers with deep knowledge of both programming and graphic design. This library changes that. It is an open-source tool that encapsulates thousands of hours of research and development into a simple, powerful API.
My philosophy is that a developer's most valuable asset is their idea. They should be free to focus on inventing new, powerful analytical concepts, without getting bogged down in the tedious, repetitive work of building robust visualization and configuration systems from scratch. This library is my contribution to the Pine Script community—a tool for builders, designed to accelerate innovation and elevate the quality of indicators for everyone.
This library embraces that philosophy. It handles immense complexity on the backend to deliver absolute simplicity and elegance on the frontend, both for the developer who uses it and the trader who benefits from it.
█ A NOTE TO USERS & DISCLAIMER
THIS IS A LIBRARY FOR DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be imported and used by other indicator developers in their own scripts. It is a tool for building, not a ready-made indicator.
THE ANALYSIS IS A GUIDE: The analyze() function's classification of data and regimes is based on a robust set of heuristics, but it is a statistical interpretation. It provides a powerful baseline for visualization but is not a substitute for a trader's own judgment.
"Simplicity is the ultimate sophistication."
— Leonardo da Vinci
Taking you to school. - Dskyz, Create with DAFE
TSM: Time-Series Momentum & Volatility Targeting [Moskowitz]TSM: Institutional Time-Series Momentum & Volatility Targeting (Moskowitz)
SUMMARY
TSM is a trend and risk-sizing indicator designed to convert price movement into a risk-adjusted regime signal and a single Recommended Exposure output. It addresses a common trend problem: direction can be correct while sizing is wrong during volatility expansions.
Recommended Exposure is a signed value where positive indicates bullish bias and negative indicates bearish bias. The magnitude reflects confidence after the volatility and quality filters are applied.
The engine combines volatility-scaled time-series momentum across multiple horizons with optional volatility targeting and an optional efficiency filter to reduce noise sensitivity and improve sizing discipline.
WHAT THIS INDICATOR GIVES YOU
A risk-adjusted momentum signal that is scaled by realized volatility rather than raw returns, so high-volatility noise is less likely to look like strong trend.
An optional volatility targeting layer that mechanically scales Recommended Exposure down when realized volatility rises and up when it falls, capped by Max Leverage.
An ensemble approach using fast, medium, and slow horizons with configurable weights, reducing dependence on a single lookback and lowering curve-fitting risk.
An optional R-squared efficiency filter that reduces exposure in choppy, low-quality trends, with a floor to avoid over-suppressing exposure.
Optional workflow features including a dashboard, trend cloud bands, threshold-based signals with cooldown, and alerts.
SCIENTIFIC FOUNDATION (PLAIN ENGLISH)
Time-Series Momentum (Moskowitz, Ooi, Pedersen 2012) describes the empirical tendency for an asset’s own past returns to predict its future returns in expectation, distinct from cross-sectional momentum which compares assets to each other.
Volatility clustering means markets alternate between calm and violent regimes; many traditional trend tools misread volatility shocks as sustainable trend. This indicator normalizes momentum by realized volatility to express trend significance relative to the regime.
Volatility targeting (Harvey et al. 2018) scales exposure inversely to realized volatility to stabilize risk. When volatility rises, recommended exposure is reduced mechanically; when volatility falls, exposure can increase, subject to a max leverage cap.
DATA AND SOURCES
This indicator uses only the chart symbol’s OHLC data. No external feeds, no COT libraries, and no third-party data sources are required.
It supports multi-timeframe calculation. You can compute the signal on the current chart timeframe, or use a fixed timeframe such as Daily to keep volatility math consistent when viewing intraday charts.
HOW THE ENGINE WORKS (HIGH LEVEL)
Step 1 estimates realized volatility from log returns over a chosen lookback. Step 2 computes a volatility-scaled momentum statistic for three horizons (fast, medium, slow) to measure how meaningful the move is relative to volatility. Step 3 clamps extreme values so outliers do not dominate. Step 4 combines the horizons into a weighted ensemble. Step 5 optionally applies an efficiency filter to reduce exposure in choppy trends. Step 6 optionally applies volatility targeting to scale exposure inversely with realized annualized volatility, capped by Max Leverage. The final output is Recommended Exposure as the combined result of direction, risk scaling, and quality filtering.
OUTPUTS AND HOW USERS SHOULD APPLY THEM
Recommended Exposure is the primary output. Positive values indicate bullish regime bias, negative values indicate bearish regime bias, and larger magnitude indicates higher risk-adjusted conviction after filters.
Typical use is as a position-sizing overlay: keep your own entry method and use Recommended Exposure to decide how aggressive or defensive sizing should be in the current regime.
Signals are optional and trigger when Recommended Exposure crosses user-defined thresholds. A cooldown reduces repeated triggers during consolidations, and direction can be restricted to long only, short only, or both.
The dashboard is optional and displays realized volatility versus target, ensemble momentum, the efficiency metric, the volatility scalar, the quality multiplier, and final Recommended Exposure, including the fast/medium/slow breakdown.
Trend cloud bands are optional and provide range context; they are not the signal and are intended as visual regime support.
SETTINGS GUIDE (WHAT MATTERS MOST)
Fixed Timeframe mode is recommended for consistent volatility math across chart timeframes; Current Chart mode is more sensitive to the displayed timeframe.
Momentum horizons control responsiveness versus stability. Shorter lookbacks react faster but whipsaw more; longer lookbacks are smoother but slower. Weights allow emphasizing fast responsiveness or slow regime confirmation.
Volatility targeting turns the tool into a sizing engine by scaling exposure inversely to realized volatility. Target annualized volatility sets the risk budget, and the annualization basis (365 vs 252) aligns conventions for crypto versus traditional markets. Max Leverage caps the scalar in very low-volatility regimes.
The efficiency filter reduces exposure in choppy conditions; the floor controls how harshly exposure is reduced. Threshold and cooldown control how selective discrete signals are.
LIMITATIONS (IMPORTANT FOR USERS)
This is a trend-following framework, so it will lag turning points by design. Sideways markets can still cause whipsaws; cooldown and the efficiency filter may reduce but cannot eliminate this. Volatility targeting can reduce drawdowns during volatility expansions but may reduce participation during sharp V-shaped reversals after volatility increases. The efficiency metric is a practical proxy for trend straightness and can misclassify certain price paths.
REFERENCES
Moskowitz, T. J., Ooi, Y. H., and Pedersen, L. H. (2012). Time series momentum. Journal of Financial Economics, 104(2), 228-250.
Harvey, C. R., Rattray, S., Sinclair, A., and Van Hemert, O. (2018). The impact of volatility targeting. Journal of Portfolio Management, 45(1), 14-33.
Hurst, B., Ooi, Y. H., and Pedersen, L. H. (2017). A century of evidence on trend-following investing. Journal of Portfolio Management, 44(1), 15-29.
DISCLAIMER
Educational and informational purposes only. Not financial advice. Trading involves risk. Past performance is not indicative of future results.
MJ amd tableAsia, Londong and New york table showing each session what goes to happen depending on the movement of AMD
1M / 3M / 6M / 12M Performance Box─────────────────────────────────────────────────────────────
1M / 3M / 6M / 12M Performance Box
─────────────────────────────────────────────────────────────
A compact on-chart dashboard that shows multi-horizon price performance
(1M / 3M / 6M / 12M) as percentage change, using DAILY data for consistency
across all chart timeframes (intraday, daily, weekly).
What it does
• Calculates % performance over 1, 3, 6, and 12 month horizons.
• Displays results in a clean table overlay on the chart.
• Automatically color-codes performance:
- Green = positive
- Red = negative
- Gray = neutral / not available
Month definition (user selectable)
• Calendar days mode:
1M = 30 days, 3M = 90 days, 6M = 180 days
• Trading days mode:
1M = 21 TD, 3M = 63 TD, 6M = 126 TD
• 12M is calculated as ~365 days in both modes.
Customization
• Table position (top/bottom + left/right)
• Decimal precision
• Fully customizable colors (header, labels, positive/negative/neutral cells)
• Adjustable background opacity
• Optional header with symbol + timeframe
Use cases
• Quick trend/context check before entries
• Relative strength snapshot across time horizons
• Cleaner decision-making without adding clutter
Notes
• Uses daily close/time via request.security() for stable results.
• Displays "n/a" when a reference value is not available.
─────────────────────────────────────────────────────────────
SPX & VIX Overnight Gap and Gap % w/VIX Open
Displays SPX and VIX Overnight gaps in points and percentage with VIX open value. Display boxes change color depending on gap up (green) or gap down (red) Optional vertical line which changes color depending on the gap direction placed at the first bar.
Wick Statistics (Intra-Day)Data box that shows smallest, largest, and average wick point size during specified time ranges.
Pattern Atlas Smart Panel Alerts Toni Ventura MaltaThe Pattern Atlas in 1 Indicator
Not fool proof but helps understanding what the discord traders are talking about ;)
QuantumPips Sessions QuantumPips Sessions highlights the three main trading sessions. Asia, London, and New York, directly on your chart using session boxes, live session high/low tracking, and optional vertical dotted separators at each session open.
What it does
Draws a box around each session range (from session start to session end)
Updates the box dynamically to reflect the current session High + Low
Adds a session label (ASIA / LONDON / NEW YORK) above the session high
Optionally shades the chart background during active sessions
Optionally plots vertical dotted separators at the start of each session
Sessions (default UK time)
Asia: 00:00 – 09:00
London: 08:00 – 17:00
New York: 13:00 – 22:00
You can change session times and timezone in the settings to match your broker/chart.
Customization options
Toggle sessions on/off (Asia, London, NY)
Change box fill + border colors for each session
Adjust label text color + padding
Enable/disable background shading
Enable/disable vertical separators + set color/width
ES Morning Range Entry8am to 815am ZONE, marking out previous session highs and lows as targets. Simple and easy dont over complicate things
DafePatternLibDafePatternLib: The Neural Pattern Recognition & Reinforcement Learning Engine
This is not a pattern library. This is an artificial trading brain. It doesn't just find patterns; it learns, adapts, and evolves based on their performance in the live market.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND STATIC RULES, INTO DYNAMIC LEARNING
For decades, chart pattern analysis has been trapped in a static, rigid paradigm. An indicator is coded to find a "Bullish Engulfing" or a "Head and Shoulders," and it will signal that pattern with the same blind confidence every single time, regardless of whether that pattern has been consistently failing for the past month. It has no memory, no intelligence, no ability to adapt. It is a dumb machine executing a fixed command.
The DafePatternLib was created to shatter this paradigm. It is built on a powerful, revolutionary philosophy borrowed from the world of artificial intelligence: Reinforcement Learning . This library is not just a collection of pattern detection functions; it is a complete, self-optimizing neural framework. It doesn't just find patterns; it tracks their outcomes. It remembers what works and what doesn't. Over time, it learns to amplify the signals of high-probability patterns and silence the noise from those that are failing in the current market regime.
This is not a black box. It is an open-source, observable learning system. It is a "Neural Edition" because, like a biological brain, it strengthens and weakens its own "synaptic" connections based on positive and negative feedback, evolving into a tool that is uniquely adapted to the specific personality of the asset you are trading.
█ CHAPTER 2: THE CORE INNOVATIONS - WHAT MAKES THIS A "NEURAL" LIBRARY?
This library introduces several concepts previously unseen in the TradingView ecosystem, creating a truly next-generation analytical tool.
Reinforcement Learning Engine: The brain of the system. Every time a high-confidence pattern is detected, it is logged into an "Active Memory." The library then tracks the outcome of that pattern against its projected stop and target. If the pattern is successful, the "synaptic weight" for that entire category of patterns is strengthened. If it fails, the weight is weakened. This is a continuous feedback loop of performance-driven adaptation.
Synaptic Plasticity (Learning Rate): You have direct control over the brain's "plasticity"—its ability to learn. A high plasticity allows it to adapt very quickly to changing market conditions, while a lower plasticity creates a more stable, long-term learning model.
Dynamic Volatility Scaling (DVS): Markets are not static; they breathe. DVS is a proprietary function that calculates a real-time volatility scalar by comparing the current ATR to its historical average. This scalar is then used to automatically adjust the lookback periods and sensitivity of all relevant pattern detection engines. In high-volatility environments, the engines look for larger, more significant patterns. In low-volatility, they tighten their focus to find smaller, more subtle setups.
Neural Confidence Score: The output of this library is not a simple "true/false" signal. Every detected pattern comes with two confidence scores:
Raw Confidence: The original, static confidence level based on the pattern's textbook definition.
Net Confidence: The AI-adjusted score. This is the Raw Confidence × Learned Bias. A pattern that has been performing well will see its confidence amplified (e.g., 70% raw → 95% net). A pattern that has been failing will see its confidence diminished (e.g., 70% raw → 45% net).
Intelligent Filtering: The learning system is not just for scoring. If the learned bias for a particular pattern category (e.g., "Candle") drops below a certain threshold (e.g., 0.8), the library will automatically begin to filter out those signals, treating them as unreliable noise until their performance improves.
█ CHAPTER 3: THE ANATOMY OF THE AI - HOW IT THINKS
The library's intelligence is built on a clear, observable architecture.
The NeuralWeights (The Brain)
This is the central data structure that holds the system's "memory." It is a simple object that stores a single floating-point number—a weight or "bias"—for each of the five major categories of pattern analysis. It is initialized with neutral weights of 1.0 for all categories.
w_candle: For candlestick patterns.
w_harmonic: For harmonic patterns.
w_structure: For market structure patterns (e.g., BOS/CHoCH).
w_geometry: For classic geometric patterns (e.g., flags, wedges).
w_vsa: For Volume Spread Analysis patterns.
The update_brain() Function (The Learning Process)
This is the core of the reinforcement learning loop. When a pattern from the ActiveMemory is resolved (as a win or a loss), this function is called. If the pattern was a "win," it applies a small, positive adjustment (the plasticity value) to the corresponding weight in the brain. If it was a "loss," it applies a negative adjustment. The weights are constrained between 0.5 (maximum distrust) and 2.0 (maximum trust), preventing runaway feedback loops.
The manage_memory() Function (The Short-Term Memory)
This function is the AI's hippocampus. It maintains an array of ActiveMemory objects, tracking up to 50 recent, high-confidence signals. On every bar, it checks each active pattern to see if its target or stop has been hit. If a pattern resolves, it triggers the update_brain() function with the outcome and removes the pattern from memory. If a pattern does not resolve within a set number of bars (e.g., 50), it is considered "expired" and is treated as a minor loss, teaching the AI to distrust patterns that lead to nowhere.
The scan_neural_universe() Function (The Master Controller)
This is the main exported function that you will call from your indicator. It is the AI's "consciousness." On every bar, it performs a sequence of high-level actions:
It calculates the current Dynamic Volatility Scalar (DVS).
It runs all of its built-in pattern detection engines (VSA, Geometry, Candles, etc.), feeding them the DVS to ensure they are adapted to the current market volatility.
It identifies the single "best" active pattern for the current bar based on its raw confidence score.
It passes this "best" pattern to the manage_memory() function to be tracked and to trigger learning from any previously resolved patterns.
It retrieves the current learned bias for the "best" pattern's category from the brain.
It calculates the final net_confidence by multiplying the raw confidence by the learned bias.
It performs a final check, intelligently filtering out the signal if its learned bias is too low.
It returns the final, neurally-enhanced PatternResult object to your indicator.
█ CHAPTER 4: A GUIDE FOR DEVELOPERS - INTEGRATING THE BRAIN
I have designed the DafePatternLib to be both incredibly powerful and remarkably simple to integrate into your own scripts.
Import the Library: Add the following line to the top of your script (replace YourUsername with your TradingView username):
import DskyzInvestments/DafePatternLib/1 as pattern
Call the Scanner: On every bar, simply call the main scanning function. The library handles everything else internally—the DVS calculation, the multi-pattern scanning, the memory management, and the reinforcement learning.
pattern.PatternResult signal = pattern.scan_neural_universe()
Use the Result: The signal object now contains all the intelligence you need. Check if a pattern is active, and if so, use its properties to draw your signals and alerts. You can choose to display the raw_confidence vs. the net_confidence to give your users a direct view of the AI's learning process.
if signal.is_active
label.new(bar_index, signal.entry, "AI Conf: " + str.tostring(signal.net_confidence, "#") + "%")
With just these few lines, you have integrated a self-learning, self-optimizing, multi-pattern recognition engine into your indicator.
// ═══════════════════════════════════════════════════════════
// INSTRUCTIONS FOR DEVELOPERS:
// ───────────────────────────────────────────────────────────
1. Import the library at the top of your indicator script:
import YourUsername/DafePatternLib/1 as pattern
2. Copy the entire "INPUTS TEMPLATE" section below and paste it into your indicator's code.
This will create the complete user settings panel for controlling the AI.
3. Copy the "USAGE EXAMPLE" section and adapt it to your script's logic.
This shows how to initialize the brain, call the scanner, and use the results.
// ═══════════════════════════════════════════════════════════
// INPUT GROUPS
// ═══════════════════════════════════════════════════════════
string G_AI_ENGINE = "══════════ 🧠 NEURAL ENGINE ══════════"
string G_AI_PATTERNS = "══════════ 🔬 PATTERN SELECTION ══════════"
string G_AI_VISUALS = "══════════ 🎨 VISUALS & SIGNALS ══════════"
string G_AI_DASH = "══════════ 📋 BRAIN STATE DASHBOARD ══════════"
string G_AI_ALERTS = "══════════ 🔔 ALERTS ══════════"
// ═══════════════════════════════════════════════════════════
// NEURAL ENGINE CONTROLS
// ═══════════════════════════════════════════════════════════
bool i_enable_ai = input.bool(true, "✨ Enable Neural Pattern Engine", group = G_AI_ENGINE,
tooltip="Master switch to enable or disable the entire pattern recognition and learning system.")
float i_plasticity = input.float(0.03, "Synaptic Plasticity (Learning Rate)", minval=0.01, maxval=0.1, step=0.01, group = G_AI_ENGINE,
tooltip="Controls how quickly the AI adapts to pattern performance. " +
"• Low (0.01-0.02): Slow, stable learning. Good for long-term adaptation. " +
"• Medium (0.03-0.05): Balanced adaptation (Recommended). " +
"• High (0.06-0.10): Fast, aggressive learning. Adapts quickly to new market regimes but can be more volatile.")
float i_filter_threshold = input.float(0.8, "Neural Filter Threshold", minval=0.5, maxval=1.0, step=0.05, group = G_AI_ENGINE,
tooltip="The AI will automatically hide (filter) signals from any pattern category whose learned 'Bias' falls below this value. Set to 0.5 to disable filtering.")
// ═══════════════════════════════════════════════════════════
// PATTERN SELECTION
// ═══════════════════════════════════════════════════════════
bool i_scan_candles = input.bool(true, "🕯️ Candlestick Patterns", group = G_AI_PATTERNS, inline="row1")
bool i_scan_vsa = input.bool(true, "📦 Volume Spread Analysis", group = G_AI_PATTERNS, inline="row1")
bool i_scan_geometry = input.bool(true, "📐 Geometric Patterns", group = G_AI_PATTERNS, inline="row2")
bool i_scan_structure = input.bool(true, "📈 Market Structure (SMC)", group = G_AI_PATTERNS, inline="row2")
bool i_scan_harmonic = input.bool(false, "🦋 Harmonic Setups (Experimental)", group = G_AI_PATTERNS, inline="row3",
tooltip="Harmonic detection is simplified and experimental. Enable for additional confluence but use with caution.")
// ═══════════════════════════════════════════════════════════
// VISUALS & SIGNALS
// ═══════════════════════════════════════════════════════════
bool i_show_signals = input.bool(true, "Show Pattern Signals on Chart", group = G_AI_VISUALS)
color i_bull_color = input.color(#00FF88, "Bullish Signal Color", group = G_AI_VISUALS, inline="colors")
color i_bear_color = input.color(#FF0055, "Bearish Signal Color", group = G_AI_VISUALS, inline="colors")
string i_signal_size = input.string("Small", "Signal Size", options= , group = G_AI_VISUALS)
//══════════════════════════════════════════════════════
// BRAIN STATE DASHBOARD
//══════════════════════════════════════════════════════
bool i_show_dashboard = input.bool(true, "Show Brain State Dashboard", group = G_AI_DASH)
string i_dash_position = input.string("Bottom Right", "Position", options= , group = G_AI_DASH)
string i_dash_size = input.string("Small", "Size", options= , group = G_AI_DASH)
// ══════════════════════════════════════════════════════════
// ALERTS
// ═══════════════════════════════════════════════════════════
bool i_enable_alerts = input.bool(true, "Enable All Pattern Alerts", group = G_AI_ALERTS)
int i_alert_min_confidence = input.int(75, "Min Neural Confidence to Alert (%)", minval=50, maxval=100, group = G_AI_ALERTS)
█ DEVELOPMENT PHILOSOPHY
The DafePatternLib was born from a vision to bring the principles of modern AI to the world of technical analysis on TradingView. We believe that an indicator should not be a static, lifeless tool. It should be a dynamic, intelligent partner that learns and adapts alongside the trader. This library is an open-source framework designed to empower developers to build the next generation of smart indicators, moving beyond fixed rules and into the realm of adaptive, performance-driven intelligence.
This library is designed to be a tool for that discipline. By providing an objective, data-driven, and self-correcting analysis of patterns, it helps to remove the emotional guesswork and second-guessing that plagues so many traders, allowing you to act with the cold, calculated confidence of a machine.
█ A NOTE TO USERS & DISCLAIMER
THIS IS A LIBRARY FOR DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be imported and used by other indicator developers in their own scripts.
THE AI LEARNS, IT DOES NOT PREDICT: The reinforcement learning is based on the recent historical performance of patterns. It is a powerful statistical edge, but it is not a crystal ball. Past performance does not guarantee future results.
ALL TRADING INVOLVES RISK: The patterns and confidence scores are for informational and educational purposes only. Always use proper risk management.
**Please be aware that this is a library script and has no visual output on its own. The charts, signals, and dashboards shown in the images were created with a separate demonstration indicator that utilizes this library's powerful pattern recognition and learning engine.
"The key to trading success is emotional discipline. If intelligence were the key, there would be a lot more people making money trading."
— Victor Sperandeo, Market Wizard
Taking you to school. - Dskyz, Create with DAFE
Green/Red Candle Conditional Probability V2Conditional Next-Candle Probability Analyzer
This indicator calculates the historical probability of the next candle being green based on current market conditions. Unlike simple candle counters, it tracks conditional probabilities.
How It Works:
Monitors 20+ market conditions across trend, momentum, volatility, volume, and candle patterns
For each condition, tracks: "When this was true, what % of next candles were green?"
Combines active conditions into a weighted probability prediction
Weights by sample size (more historical data = more influence)
Conditions Tracked:
Trend alignment (EMA 7 / SMA 20 / SMA 200)
RSI levels and momentum
MACD position, histogram, and crosses
Consecutive candle streaks (3-4 in a row)
Bollinger Band touches and squeeze/expansion
Volume spikes and anomalies
Large candles and rejection wicks
Table Display:
P(Grn): Probability next candle is green when condition is active
Edge: Deviation from 50% (how predictive the condition is)
N: Sample size (historical occurrences)
► marks currently active conditions
Signals:
Plots arrows when multiple conditions align with sufficient confidence (configurable threshold).
Use Cases:
Identify which setups have actual predictive value on your asset/timeframe
Find confluence zones where multiple high-edge conditions align
Backtest mean-reversion vs momentum characteristics
Note: Edges are typically small (2-5%). Best used for confluence confirmation, not standalone signals.
ATLAS_COREShared utility library for the ATLAS Trading Intelligence Suite. Provides brand colors, math utilities, candle analysis, grading system, visual helpers, and more.






















