NQ Statistical MapperNQ Statistical Mapper
CRITICAL DISCLAIMER - READ FIRST
WARNING: THIS INDICATOR IS EXCLUSIVELY FOR NQ (NASDAQ-100 E-MINI FUTURES) ONLY
All statistics displayed in this indicator are HARD-CODED values derived from a comprehensive analysis of 12 years (2013-2025) of 1-minute NQ futures data. These statistics are calculated offline using Python and embedded directly into the indicator code.
These probabilities DO NOT apply to any instrument other than NQ
What This Indicator Does
The NQ Statistical Mapper is a data-driven trading tool that displays historical probability statistics for intraday NQ price behavior based on overnight session structure and opening positioning. Rather than generating signals, it provides context by showing:
Three trading sessions with visual boxes: Asia (8PM-2AM), London (2AM-8AM), and New York (8AM-4PM) Eastern Time
Key price levels with historical hit rate percentages showing the probability these levels are touched during the NY cash session (8AM-4PM)
Context-aware statistics that change based on current market conditions
Session range analysis showing whether Asia and London ranges are unusually large or small compared to recent history
Core Methodology and Statistical Foundation
Pattern Detection System
The indicator automatically detects one of four overnight session patterns based on how the London session (2AM-8AM) interacts with the Asia session (8PM-2AM):
London Engulfs Asia: London high is greater than Asia high AND London low is less than Asia low
Asia Engulfs London: Asia high is greater than or equal to London high AND Asia low is less than or equal to London low
London Partial Up: London high is greater than Asia high BUT London low is greater than or equal to Asia low (took out Asia high only)
London Partial Down: London low is less than Asia low BUT London high is less than or equal to Asia high (took out Asia low only)
Each pattern has distinct statistical characteristics that influence NY session behavior.
Conditional Probability Framework
The indicator uses a conditional probability approach where statistics adapt based on:
Primary Condition: Where does NY open (8:00 AM) relative to the London session midpoint?
"NY opens above London midpoint"
"NY opens below London midpoint"
This single condition dramatically changes the probabilities. For example:
When NY opens above London midpoint: 76.68% chance NY hits the London high before the London low during 8AM-4PM
When NY opens below London midpoint: 73.32% chance NY hits the London low before the London high during 8AM-4PM
Secondary Condition: The overnight pattern further refines these probabilities. Each combination of "NY position vs London midpoint" plus "overnight pattern" has unique hit rate statistics calculated from the 12-year dataset.
"Hit First" Statistics Explained
The table displays "Hit High First" and "Hit Low First" percentages. These answer the question: "During the NY cash session (8AM-4PM), if price eventually touches both the London high AND London low, which one does it touch FIRST?"
Example interpretation:
Hit High First: 76.68% means that in 76.68% of historical days with this setup, price touched the London high before touching the London low
Hit Low First: 22.48% means London low was touched first
The remaining approximately 1% represents days where neither level was hit during the NY session
This is fundamentally different from asking "will price go up or down" - it is about the sequence of range expansion during the NY session.
Displayed Levels and Their Meanings
Session Highs/Lows (Solid Lines)
These appear when each session completes and extend through the NY session:
Asia High/Low (Orange): The highest and lowest prices during 8PM-2AM EST
London High/Low (Blue): The highest and lowest prices during 2AM-8AM EST
Each level shows its hit rate percentage - the probability that NY session price (8AM-4PM) will touch that level, based on the current pattern and NY opening position.
Hourly Midpoint Levels (Dashed Gray Lines)
Three specific hourly levels with remarkably high hit rates:
7-8 AM Midpoint: Average of high and low during the 7-8 AM hour. Hit rates consistently above 93-94%, essentially sitting at the 8 AM open price (mean distance: -0.001%)
Midnight Open: The opening price at midnight EST. Hit rates vary from 62-87% depending on pattern and setup
2-3 AM Midpoint: Average of high and low during the 2-3 AM hour. Hit rates range from 67-92%
These levels are derived from mean-reversion behavior - price tends to revisit certain overnight reference points during the NY session.
Session Midpoints (Dotted Lines)
Optional display of Asia and London session midpoints. These lines terminate when their respective sessions end, providing additional reference levels for session positioning.
Statistics Table Breakdown
The table displays five sections of information:
1. SETUP Section
Shows whether "NY opens above/below London midpoint"
Displays the detected overnight pattern (1 of 4 types)
Sample size: Number of historical days matching this exact setup
Hit High First / Hit Low First: Directional bias percentages
2. HIT RATES (8AM-4PM) Section
Shows probability that each level gets touched at any point during the NY cash session:
7-8 AM Midpoint: Almost always touched (93-97% depending on pattern)
Midnight Open: Varies significantly (62-87%) based on whether the overnight pattern is aligned or contrary to NY's opening position
2-3 AM Midpoint: Strong hit rates (67-92%)
These are independent probabilities - they do not predict which is hit first, just whether each level gets visited.
3. ASIA RANGE Section
Real-time comparison of today's Asia session range versus recent history:
Sessions Captured: Shows how many sessions are in the rolling calculation (e.g., "18 / 50" = 18 sessions captured out of 50 requested). This alerts users if their chart history is insufficient
Current Range: Today's Asia high minus Asia low in points
Mean Range: Average range over the captured sessions
Percentile Rank: Where today's range falls in the distribution
80th percentile (red background): Unusually large range - top 20% of days
60-80th percentile (light gray): Above average
20-60th percentile (white): Normal range
Less than 20th percentile (light blue): Unusually small range - bottom 20% of days
4. LONDON RANGE Section
Identical structure to Asia Range section, analyzing the London session's range characteristics.
Why Percentile Rank Instead of Standard Deviation?
Intraday ranges exhibit right-skewed distributions with fat tails (volatility spikes create extreme outliers). Percentile rank is distribution-free and robust to these characteristics, providing more reliable identification of unusual ranges than z-scores or standard deviations.
How To Use This Indicator
For Context and Confluence
This is not a standalone trading system. The indicator provides statistical context to support other analysis:
Understanding Session Bias: If the table shows 76% probability of hitting the session high first, you know there is a statistical lean toward upside range expansion
Target Setting: If trading a breakout above the overnight high, knowing that Asia high gets hit 75% of the time helps assess target viability
Entry Timing: The 7-8 AM midpoint's 94% hit rate makes it an excellent re-entry or scaling level
Range Expansion Assessment: Percentile rankings help identify whether overnight sessions showed abnormal volatility, which may influence NY session behavior
Pattern-Specific Insights
London Partial Up plus NY Opens Below London Midpoint:
Midnight open hit rate jumps to 87.82% (strong mean reversion)
Suggests counter-trend reversal back toward overnight lows is likely
London Partial Down plus NY Opens Above London Midpoint:
Midnight open hit rate is 86.30%
Mirror pattern - reversion toward overnight highs
Asia Engulfs London Pattern:
Very high hit rates (85-98%) across all levels
Suggests consolidation/mean reversion during NY session rather than directional expansion
Typical Workflow
8:00 AM: Review the statistics table - which pattern occurred? Where did NY open relative to London midpoint?
Check Hit Rates: Note which levels have the highest probabilities of being touched
Assess Range Percentiles: Are Asia/London ranges unusually large or small? High percentiles may indicate already-extended ranges
Combine With Your Strategy: Use the statistics as confluence with your technical analysis, support/resistance, or order flow
Customization Options
Trading Sessions Settings
Session Visualization:
Toggle each session on/off independently
Customize colors for each session (New York, London, Asia)
Adjust background transparency using "Range Area Transparency" slider (0-100, default 90)
Show/hide session outlines with "Range Outline" checkbox
Each session has three customizable parameters on the same line:
Checkbox to enable/disable the session
Text field to rename the session label if desired
Color picker to select the session's display color
Hit Rate Levels Settings
Master Controls:
"Show Hit Rate Levels" - Master toggle to show or hide all level lines and labels
Individual Level Toggles:
"7-8 AM Midpoint" - Toggle the 7-8 AM hour midpoint level
"Midnight Open" - Toggle the midnight opening price level
"2-3 AM Midpoint" - Toggle the 2-3 AM hour midpoint level
Hourly Level Styling (applies to 7-8 AM Mid, Midnight, and 2-3 AM Mid):
"Hourly Level Color" - Color picker for all three hourly levels
"Hourly Level Line Width" - Thickness of hourly level lines (1-5, default 1)
"Hourly Level Line Style" - Choose between Solid, Dashed, or Dotted lines (default Dashed)
Session High/Low Styling (applies to Asia High/Low and London High/Low):
"Session High/Low Line Width" - Thickness of session extreme lines (1-5, default 1)
"Session High/Low Line Style" - Choose between Solid, Dashed, or Dotted lines (default Solid)
Additional Options:
"Show Session Midpoints" - Toggle display of Asia and London midpoint reference lines (dotted lines that end when each session completes)
"Label Text Size" - Size of percentage labels on all levels (tiny, small, normal, large, default small)
Table Settings
Statistics Table Controls:
"Show Statistics Table" - Master toggle to display or hide the entire statistics table
"Stats Table Position" - Choose from 9 positions on the chart:
Top: Top Left, Top Center, Top Right
Middle: Middle Left, Middle Center, Middle Right
Bottom: Bottom Left, Bottom Center, Bottom Right
"Stats Table Size" - Text size within the table (Auto, Tiny, Small, Normal, Large, Huge, default Small)
"Sessions for Stats Calculation" - Number of historical sessions to use for percentile calculations (5-100, default 50)
Lower values (20-30): More responsive to recent market conditions
Higher values (50-100): More stable baseline, requires more chart history
The table displays "Sessions Captured" to show how many sessions were actually available
Important Limitations and Considerations
1. This Is Historical Data, Not Prediction
The statistics show what happened in the past given similar setups. Markets evolve, regimes change, and past probability does not guarantee future outcomes. A 75% hit rate means that in 25% of historical cases, the level was NOT hit.
2. Chart History Requirements
TradingView imposes data limits:
5-minute chart: Approximately 10 days of history (enough for minimal statistics)
1-minute chart: Approximately 2-3 days of history (insufficient for percentile calculations)
Use 5-minute or higher timeframes to ensure adequate session capture
The table displays "Sessions Captured" (e.g., 18/50) to alert you when your chart history is limited.
3. Session Timing Is Fixed (EST)
All sessions use America/New_York timezone:
Asia: 8PM-2AM
London: 2AM-8AM
NY: 8AM-4PM
These times do not adjust for daylight saving changes in other regions. The definitions match CME NQ futures trading hours.
4. The Statistics Are From 2013-2025 Data
The 12-year analysis period includes:
Multiple market regimes (bull/bear/sideways)
Various volatility environments
QE, taper tantrums, COVID, 2022 bear market, 2023-2024 rally
However, it is still a limited sample. Future market structure changes (algorithmic trading evolution, regulatory changes, etc.) may alter these probabilities over time.
5. No Real-Time Calculation
This indicator does not recalculate statistics based on your chart's data. It displays pre-calculated probabilities. The only real-time calculations are:
Which pattern occurred today
Where NY opened relative to London midpoint
Current session ranges and their percentile ranks (based on your chart's recent history)
Statistical Methodology Details
Data Source
Instrument: NQ (Nasdaq-100 E-mini Futures) continuous contract
Timeframe: 1-minute bars
Period: January 2013 - January 2025 (12 years)
Sample Size: 3,132 trading days analyzed
Analysis Approach
Each trading day was classified by overnight pattern (4 types). NY opening position vs London midpoint was determined. For each combination (4 patterns times 2 positions equals 8 scenarios), the following was measured:
How often each level (session highs/lows, hourly midpoints) was touched during 8AM-4PM
Which session extreme (high or low) was hit first
Mean distance from 8 AM open to each level
Session ranges were measured for percentile analysis. All percentages were rounded to two decimal places for display.
Why These Specific Levels?
The levels were not chosen arbitrarily:
Session highs/lows: Natural support/resistance from overnight price discovery
7-8 AM midpoint: The final hour before NY open often establishes the opening range balance point
Midnight open: Represents the "true" start of the trading day (6PM-5PM structure)
2-3 AM midpoint: Captures early London price action balance
Testing showed these levels had the highest and most consistent hit rates across different patterns and setups.
Technical Implementation Notes
Language: Pine Script v5
Drawing Objects: Uses boxes for session visualization, lines for levels, labels for percentages, table for statistics
Performance: Optimized for real-time use with max limits set (500 boxes, 500 lines, 500 labels)
Calculations Per Bar:
Session detection (3 sessions)
Hourly detection (3 hourly periods)
Pattern classification
Conditional probability lookup
Percentile rank calculation (for session ranges)
All heavy statistical analysis was performed offline. The indicator only performs simple lookups and real-time range tracking.
Educational Value
Beyond trading application, this indicator demonstrates:
Conditional Probability: How market context (opening position, overnight structure) dramatically changes probabilities
Mean Reversion Dynamics: Why certain levels (7-8 AM midpoint, midnight) have such high revisit rates
Pattern Recognition: How overnight session relationships create different NY session behaviors
Distribution Analysis: Using percentile ranks instead of parametric statistics for skewed data
Understanding these concepts helps traders develop more sophisticated market models beyond simple "support and resistance."
Final Notes
This indicator is a tool for informed decision-making, not a crystal ball. It answers questions like:
"What typically happens in this setup?"
"How often does price revisit these levels?"
"Is this overnight range unusual?"
It does NOT answer:
"Should I buy or sell right now?"
"Where will price be at 4 PM?"
"What will happen tomorrow?"
Combine these statistics with proper risk management, sound trading strategy, and awareness that any individual day can deviate significantly from historical norms. The power of this indicator lies in providing objective, data-driven context to complement your analysis - not in replacing your judgment.
Statistics
Central Bank Liquidity Gap IndicatorThis indicator measures the gap between global liquidity growth and stock market growth to identify potential buying opportunities.
Liquidity drives markets. When central banks print money, that liquidity eventually flows into stocks and other assets. If we spot when liquidity growth is outpacing market growth, we can spot moments when the market is "due" to catch up.
I like this quote:
Earnings don't move the overall market; it's the Federal Reserve Board... focus on the central banks and focus on the movement of liquidity."
- Stanley Druckenmiller
How Central Bank Liquidity Gap Indicator Works
The indicator calculates a simple divergence:
Divergence = Liquidity Growth % − S&P 500 Growth %
Green bars = Liquidity is growing faster than the market (bullish)
Red bars = Market is growing faster than liquidity (less bullish)
Multi-Country M2 Money Supply
Unlike basic M2 indicators, this one lets you combine money supply data from multiple economies, including US, UK, Canada, China, Eurozone, Switzerland and Japan.
Each country's M2 is automatically weighted by its actual size (converted to USD). Larger economies have more influence on the global liquidity picture.
I've added a discount for China. China's M2 weight is reduced by 50% to account for capital controls that limit how much Chinese liquidity flows into global markets and into the US market.
Fed Net Liquidity
You can also blend in Fed Net Liquidity for a more precise US liquidity measure:
Net Liquidity = Fed Balance Sheet − Treasury General Account − Reverse Repo
This captures the actual liquidity the Fed has injected into financial markets, not just the broad money supply.
How To Read It
The Buy Zone (5%+ Divergence)
When the divergence exceeds +5%, the indicator enters the "Buy Zone" (highlighted with green background). This means liquidity is significantly outpacing market growth — historically a good buy signal.
The Support Table
The info table shows:
Component weights: How much each country's M2 contributes
Corr w/ SPX: Current correlation between liquidity and SPX (are they moving together?)
Leads SPX by X: Does past liquidity predict future SPX moves? (higher = more predictive)
Divergence %: Current divergence value
Signal
Correlation Stats
Corr w/ SPX: Measures if liquidity and SPX are moving in sync right now
Leads SPX: Measures if liquidity changes predict future SPX moves. A positive value here suggests liquidity is a leading indicator.
Potential Use Cases
Long-term investing: Wait for 5%+ divergence (buy zone) to accumulate index funds, ETFs, or stocks
Leveraged ETFs: Use buy zone signals to time entries into UPRO, TQQQ, SSO (higher risk, higher reward)
Crypto: Bitcoin and crypto markets also correlate with global liquidity — use this for BTC accumulation timing
Risk management: Avoid adding positions when divergence is deeply negative
Important Notes
This is a long-term indicator and not for daytrading. It works best used on Daily/Weekly timeframes
It identifies accumulation zones and not precise bottoms
Truly yours, Henrique Centieiro
Inspired by the relationship between M2 money supply and market performance, enhanced with multi-country liquidity tracking and Fed balance sheet analysis.
Let me know if you have questions/suggestions.
Day/Month Returns Analysis [theUltimator5]This indicator calculates the average returns for day of the week, months of the year, and each Friday of the month, then gives a visualization of the average returns in green/red bars as well as the average percentage move.
You can select from (3) options.
1) Day of the week. This shows the average returns for each day of the week calculated back as far as your chart history goes. For crypto, it calculates all 7 days of the week. If not crypto, it does Monday through Friday
2) Month of the year. This shows the average returns for each month. Self explanatory
3) Friday of the month. This is a niche setting that lets you see the average returns of each Friday of the month, to track if there is any OPEX related consistency.
You can also set the start date for the indicator to start calculating from in the options. If there is a certain date that a symbol starts acting differently and you want to only calculate from that point forwards, you can.
The visuals appear as a table which can be repositioned to whichever section of your screen you would like.
This indicator works best on the daily timeframe since lower timeframes may not have enough bars back in history to calculate enough to make an average.
WickPressureKernelWick Pressure Kernel (WPK) : The Physics-ML Fusion Engine
This is not a candlestick pattern library. This is a physics and machine learning engine that decodes the institutional battle hidden inside every wick. It is the definitive toolkit for analyzing microstructure and quantifying order flow pressure.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND THE WICK, INTO THE PHYSICS
A candlestick wick is not just a line on a chart. It is a fossil record of a battle. It is the remnant of a fierce conflict between aggressive market orders and passive limit orders. A long upper wick is not just "bearish"; it is the evidence of a failed auction, a footprint left by a wall of institutional supply that absorbed and rejected aggressive buying. Traditional candle analysis gives these events simple, unchanging names. It is a dead language.
The Wick Pressure Kernel (WPK) was created to translate this dead language into the living, dynamic language of physics and machine learning. It deconstructs the candle into its core components and subjects them to a rigorous, multi-layered analysis. It calculates the Kinetic Force of the candle, estimates the institutional Delta hidden within it, tracks the Siege Decay of the levels it tests, and uses a Bayesian Reinforcement Learning system to predict the probable outcome.
This library does not just identify patterns; it quantifies the underlying forces that create them. It is designed for the trader who is no longer content with subjective interpretation and demands a quantitative, data-driven edge in reading the story of every single bar.
█ CHAPTER 2: THE PHYSICS-ML FUSION - THE SIX LAYERS OF ANALYSIS
The WPK's unparalleled intelligence comes from its six-stage analytical pipeline. Each layer builds upon the last, transforming a simple candle into a rich, multi-dimensional data object.
LAYER 1 - DELTA PHYSICS: At its core, the WPK uses a proprietary model to estimate the institutional order flow (Delta) within a single candle. It analyzes the relationship between the wicks, the body, and the total range to approximate the net buying or selling pressure that occurred during the bar's formation.
LAYER 2 - SIEGE ANALYSIS: This is a revolutionary concept for measuring structural integrity. Every time a price level is tested by a wick, its "Siege Decay" score is updated. A fresh, untested level has a score of 1.0. A level that has been tested multiple times without breaking has a decayed score (e.g., 0.5), indicating it is weakening and likely to fail.
LAYER 3 - MAGNETISM ENGINE: Not all wicks are created equal. This engine calculates the probability that a wick will be "filled" (mean reversion). It understands that long wicks in a weak, choppy trend are likely to be filled, while wicks in a strong, trending market are more likely to represent valid rejection.
LAYER 4 - REGIME ML: The WPK is context-aware. It uses a suite of advanced statistical tools— Shannon Entropy (disorder), Detrended Fluctuation Analysis (trend vs. mean-reversion), and the Hurst Exponent (persistence)—to classify the market's current "personality" into one of six regimes (e.g., "Bull Trend," "Bear Range," "Choppy").
LAYER 5 - THOMPSON SAMPLING (REINFORCEMENT LEARNING): This is the AI brain. The library uses a Bayesian Multi-Armed Bandit algorithm called Thompson Sampling. It maintains a set of "Learning Agents," each specializing in a different type of wick pattern (e.g., Rejection, Absorption). Based on the real-time performance of these patterns, the AI continuously updates the win probability for each agent, learning which strategies are most effective in the current market.
LAYER 6 - CONTEXTUAL ROUTING: The final layer of intelligence. The WPK analyzes the wick, determines its pattern type, and then routes it to the specialist Learning Agent for a probability assessment, all while considering the current market regime.
█ CHAPTER 3: A DEEP DIVE INTO THE WPK's CORE ENGINES
THE analyze_wick() FUNCTION (THE MASTER ANALYZER)
This is the primary function of the library. You feed it a bar, and it returns a complete WickAnalysis object, a rich data structure containing over 15 distinct metrics that tell the full story of that candle:
Anomaly Score: A Z-Score that tells you how statistically rare the wick's size is compared to recent history. A score > 2.0 is a significant outlier.
Kinetic Force: A physics-based metric that combines the bar's range and its relative volume to quantify the "impact energy" of the candle.
Estimated Delta & Delta Ratio: The raw institutional flow estimate and its ratio compared to the recent average.
Siege Decay & Test Count: The current structural integrity of the level the wick tested, and how many times it has been hit.
Magnet Score: The calculated probability (0-100%) that this specific wick will be filled.
Pattern & Context: The classified pattern name (e.g., "Dragonfly/Hammer," "Liquidity Trap") and its tactical context (e.g., "reversal," "trend_continuation").
Win Probability: The final, ML-predicted success rate for this pattern, as determined by the Thompson Sampling engine.
THE scan_clusters() FUNCTION (LIQUIDITY ZONE DETECTION)
Wicks rarely happen in isolation. This powerful function scans the recent price history and identifies areas where multiple high-pressure wicks have occurred at similar price levels. It groups these events into dynamic "Pressure Clusters," which function as high-probability supply and demand zones. Each cluster is tracked with its own set of metrics, including its total strength, age, and siege decay.
THE detect_regime() FUNCTION (THE CONTEXT ENGINE)
This function is the AI's "eyes." It uses advanced statistical methods to understand the market's personality. Is it trending cleanly? Is it mean-reverting? Is it completely random and chaotic? The output of this function is fed into the rest of the WPK, allowing the analysis to adapt intelligently to the current environment.
█ CHAPTER 4: A GUIDE FOR DEVELOPERS - INTEGRATING THE KERNEL
The Wick Pressure Kernel is designed as a powerful, low-level engine for developers to build sophisticated trading tools.
Import the Library:
import YourUsername/WickPressureKernel/1 as wpk
Initialize the AI: The learning agents must be stored in a var variable to retain their memory.
var array agents = wpk.create_learning_agents()
Analyze the Market: On every bar, run the core analysis functions.
wpk.RegimeState regime = wpk.detect_regime(100)
wpk.WickAnalysis wick_data = wpk.analyze_wick(0, regime, agents)
float final_probability = wpk.get_probability(wick_data, regime)
Apply Your Logic: Use the rich data from the wick_data object and the final_probability to build your custom signal logic and filters.
bool my_buy_signal = wick_data.pattern == "Dragonfly/Hammer" and final_probability > 65
Provide Feedback (The Learning Step): After a trade based on a pattern is complete, you must tell the AI the outcome. This is how it learns.
int agent_id = wpk.get_agent_by_pattern(wick_data)
agents := wpk.update_learning_agent(agents, agent_id, 1.0) // +1.0 for a win, -1.0 for a loss
By following this loop, you are not just running an indicator; you are actively training a specialized AI to master the specific asset you are trading.
█ DEVELOPMENT PHILOSOPHY
The Wick Pressure Kernel was born from the conviction that the future of technical analysis lies in the fusion of quantitative physics and machine learning. It is an attempt to move beyond subjective pattern naming and into the realm of objective, measurable forces. This library is for the serious developer and the quantitative trader who is not satisfied with simple signals, but who seeks to understand the deep, complex, and often violent auction process that creates every candle on the chart.
The WPK is designed to be a tool for that patience, providing the deep contextual understanding needed to wait for moments of true, statistically-backed institutional pressure.
█ 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 to build their own tools.
THE AI IS A PROBABILISTIC GUIDE: The reinforcement learning system provides a powerful statistical edge, but it does not predict the future with certainty. All trading involves substantial risk.
LEARNING REQUIRES DATA: The Thompson Sampling engine becomes more intelligent over time as it processes more outcomes. Its initial predictions will be less reliable than its predictions after hundreds of trades.
**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 stock market is a device for transferring money from the impatient to the patient."
— Warren Buffett
Taking you to school. - Dskyz, Create with DAFE
Ticker Dashboard [rogman]TICKER DASHBOARD INDICATOR
Overview
A comprehensive real-time market dashboard that displays critical trading information in a compact, color-coded table overlay. Designed for quick at-a-glance analysis of price action, trend direction, market conditions, and relative performance. Automatically detects asset type (stocks, futures, CFDs, forex, crypto) and adjusts session display accordingly.
Table Layout
ROW 1: PRICE & MARKET STATUS
Trend Dot: 🟢 when 8 EMA > 21 EMA (bullish), 🔴 when below (bearish)
Ticker: Current symbol, colored green/red based on change from previous close
Price: Real-time price, updates during extended hours
Chg $: Dollar change from previous day's close (updates in afterhours)
VWAP: ▲V (green) if price above VWAP, ▼V (red) if below
S:/Q:: SPY and QQQ real-time status — 🟢 up from previous close, 🔴 down from previous close
ROW 2: MOVING AVERAGES & RELATIVE STRENGTH
RS 8 EMA 21 EMA 50 SMA
RS (Relative Strength vs SPY):
⊕ (green): Outperforming SPY by >0.5%
⊖ (red): Underperforming SPY by >0.5%
⊜ (gray): Neutral (within ±0.5%)
8/21/50 MAs: Values color-coded green if price above, red if below
ROW 3: SESSION, RANGE & VOLUME
Session - Low - Range Bar - High - Vol:██████
Session Indicator (Auto-detects Asset Type)
Stocks:
IconStatusHours (ET)🔔Market Open9:30am - 4:00pm⏰Pre-Market4:00am - 9:29am🌙After-Hours4:01pm - 8:00pm⛔️Closed8:00pm - 4:00am, Weekends
Futures & CFDs:
IconStatusHours (ET)🔔OpenSunday 6pm - Friday 5pm (with daily 5-6pm break)⛔️ClosedFriday 5pm - Sunday 6pm, Daily 5-6pm maintenance
Forex & DXY:
IconStatusHours (ET)🔔OpenSunday 5pm - Friday 5pm (24/5, no daily break)⛔️ClosedFriday 5pm - Sunday 5pm
Crypto:
IconStatus🔔Always Open (24/7)
Range Bar
Visual representation showing current price position within daily high/low range using a ║ marker.
Volume Blocks
6 blocks compared to 30-day average volume:
Volume % Color Block Fill
<75% avg🔴 RedFills 1 block per 10% below 75% (e.g., 24% = 6 red blocks)
75-125% avg⬜ GrayFills 1-6 blocks as volume increases through normal range
>125% avg🟢 GreenFills 1 block per 10% above 125%
ROW 4: VOLUME DETAILS (Optional)
Vol: XXM 30D Avg: XXM Ratio: X%
Vol: Current daily volume (in millions)
30D Avg: 30-day average volume (in millions)
Ratio: Current volume as percentage of average
Toggle on/off in settings via "Show Volume Row"
Settings
Customize table background and border colors
Position table in multiple locations on chart
Customize text color and size
Asset Type Detection
The indicator automatically detects the asset type and adjusts behavior
Example Displays
Stock During Market Hours
┌────┬──────┬────────┬─────────┬────┬─────────────┐
│ 🟢 │ TSLA │ 421.81 │ +$12.50 │ ▲V │ S:🟢 Q:🟢 │
├────┼──────┼────────┼─────────┼────┼─────────────┤
│ ⊕ │ 8: 418.50│ 21: 415.20 │ 50: 410.35 │
├────┼──────┼────────┼─────────┼────┼─────────────┤
│ 🔔 │ 409 │ ─────║──│ 425 │Vol: │ ███░░░ │
└────┴──────┴────────┴─────────┴────┴─────────────┘
Stock During Pre-Market
┌────┬──────┬────────┬─────────┬────┬─────────────┐
│ 🔴 │ AAPL │ 178.25 │ -$2.30 │ ▼V │ S:🔴 Q:🔴 │
├────┼──────┼────────┼─────────┼────┼─────────────┤
│ ⊖ │ 8: 179.80│ 21: 181.50 │ 50: 183.20 │
├────┼──────┼────────┼─────────┼────┼─────────────┤
│ ⏰ │ 177 │ ──║──── │ 180 │Vol: │ █░░░░░ │
└────┴──────┴────────┴─────────┴────┴─────────────┘
Crypto (Always Open)
┌────┬──────┬──────────┬─────────┬────┬─────────────┐
│ 🟢 │ BTC │ 67,450 │ +$1,250 │ ▲V │ S:🟢 Q:🟢 │
├────┼──────┼──────────┼─────────┼────┼─────────────┤
│ ⊕ │ 8: 66,800│ 21: 65,500 │ 50: 63,200 │
├────┼──────┼──────────┼─────────┼────┼─────────────┤
│ 🔔 │ 65,000 │ ──────║── │ 68,000 │Vol: │ ████░░ │
└────┴──────┴──────────┴─────────┴────┴─────────────┘
Futures (Closed)
┌────┬──────┬─────────┬─────────┬────┬─────────────┐
│ 🔴 │ ES1! │ 5,425 │ -$15.00 │ ▼V │ S:🔴 Q:🔴 │
├────┼──────┼─────────┼─────────┼────┼─────────────┤
│ ⊜ │ 8: 5,430 │ 21: 5,445 │ 50: 5,480 │
├────┼──────┼─────────┼─────────┼────┼─────────────┤
│ ⛔️ │ 5,400 │ ───║──── │ 5,450 │Vol: │ ██░░░░ │
└────┴──────┴─────────┴─────────┴────┴─────────────┘
Technical Notes
Session detection uses timenow for real-time accuracy (not bar time)
All session times are based on America/New_York timezone
Volume calculations use daily timeframe regardless of chart timeframe
Moving averages calculated on current chart timeframe
Price color reflects change from previous close (not day open)
Asia Range + OB Zones + AlertsTrail run of script built with chatgpt and clude to mark hhs lows and OB's
Hawks NY Midnight OpenPlots the New York Midnight Open price with configurable horizontal and vertical reference lines, session-based timing, and adjustable extensions.
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.
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
Volatility & Probability by Hour/DayVolatility & Probability by Hour/Day
Analyzes historical candle data to find statistically significant time-based patterns. Tracks green candle probability, volatility, and average returns broken down by hour (UTC), day of week, and their combinations.
What It Shows:
Hourly Table: P(Green), edge, volatility, and average return for each hour (00:00-23:00 UTC)
Day of Week Table: Same metrics aggregated by day (Sun-Sat)
Top Combinations: The 5 best bullish and 5 best bearish day+hour slots ranked by edge
Key Metrics:
P(Grn): Historical probability the candle closes green
Edge: Deviation from 50% (how tradeable the bias is)
Vol%: Average candle range as percentage of price
N: Sample size
Use Cases:
Identify optimal entry windows with statistical edge
Avoid low-edge, high-volatility periods (noise)
Find specific day+hour combinations with compounding edges
Time trades around recurring market patterns
Notes:
All times in UTC
Current period highlighted with ►
Best results on liquid assets with sufficient history
Edges are historical and not guaranteed to persist
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
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.
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.
─────────────────────────────────────────────────────────────
ATLAS_COREShared utility library for the ATLAS Trading Intelligence Suite. Provides brand colors, math utilities, candle analysis, grading system, visual helpers, and more.
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.
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).
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 :)
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.
Daily DashboardThe Daily Dashboard indicator provides a quick, at-a-glance view of essential daily market statistics directly on your TradingView chart.
Features:
- Daily High & Low: Track the highest and lowest prices of the current trading day.
- Total Daily Volume: Monitor the total trading volume accumulated during the day.
- Previous Day Breakouts: See if today’s price has broken the previous day’s high or low.
- Automatic Updates: All values refresh automatically at the start of a new trading day.
- Pinned Table Layout: Fixed in the top-right corner of the chart for easy reference, independent of price movements.
- Clean Design: White text on a semi-transparent blue background for maximum readability.
Use Cases:
- Day traders needing a quick overview of daily market activity.
- Swing traders monitoring key levels and breakout potential.
- Traders wanting a professional, lightweight dashboard without cluttering the chart.
How It Works:
- Tracks daily high, low, and volume in real time.
- Compares today’s price to the previous day’s high and low to identify breakouts.
- Displays all data neatly in a fixed table pinned to the chart.
Customization:
- Table position is fixed in the top-right corner.
- Background transparency and colors can be adjusted in the script if desired.
Pro Tip:
Combine this dashboard with trend or momentum indicators to create a complete trading setup.
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
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
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.
Wick Statistics (Intra-Day)Data box that shows smallest, largest, and average wick point size during specified time ranges.






















