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
DafeRLMLLibDafeRLMLLib: The Reinforcement Learning & Machine Learning Engine
This is not an indicator. This is an artificial intelligence. A state-based, self-learning engine designed to bring the power of professional quantitative finance to the Pine Script ecosystem. Welcome to the next frontier of trading analysis.
█ CHAPTER 1: THE PHILOSOPHY - FROM STATIC RULES TO DYNAMIC LEARNING
Technical analysis has, for a century, been a discipline of static, human-defined rules. "If RSI is below 30, then buy." "If the 50 EMA crosses the 200 EMA, then sell." These are fixed heuristics. They are brittle. They fail to adapt to the market's ever-changing personality—its shifts between trend and range, high and low volatility, risk-on and risk-off sentiment. An indicator built on static rules is an automaton, destined to fail when the environment it was designed for inevitably changes.
The DafeRLMLLib was created to shatter this paradigm. It is not a tool with fixed rules; it is a framework for discovering optimal rules. It is a true Reinforcement Learning (RL) and Machine Learning (ML) engine, built from the ground up in Pine Script. Its purpose is not to follow a pre-programmed strategy, but to learn a strategy through trial, error, and feedback.
This library provides a complete, professional-grade toolkit for developers to build indicators that think, adapt, and evolve. It observes the market state, selects an action, receives a reward signal based on the outcome, and updates its internal "brain" to improve its future decisions. This is not just a step forward; it is a quantum leap into the future of on-chart intelligence.
█ CHAPTER 2: THE CORE INNOVATIONS - WHAT MAKES THIS A TRUE ML ENGINE?
This library is not a collection of simple moving averages labeled as "AI." It is a suite of genuine, academically recognized machine learning algorithms, adapted for the unique constraints and opportunities of the Pine Script environment.
Multi-Algorithm Architecture: You are not locked into one learning model. The library provides a choice of powerful RL algorithms:
Q-Learning with TD(λ) Eligibility Traces: A classic, robust algorithm for learning state-action values. We've enhanced it with eligibility traces (Lambda), allowing the agent to more efficiently assign credit or blame to a sequence of past actions, dramatically speeding up the learning process.
REINFORCE Policy Gradient with Baseline: A more advanced method that directly learns a "policy"—a probability distribution over actions—instead of just values. The baseline helps to stabilize learning by reducing variance.
Actor-Critic Architecture: The state-of-the-art. This hybrid model combines the best of both worlds. The "Actor" (the policy) decides what to do, and the "Critic" (the value function) evaluates how good that action was. The Critic's feedback is then used to directly improve the Actor's decisions.
Prioritized Experience Replay: Like a human, the AI learns more from surprising or significant events. Instead of learning from experiences in a simple chronological order, the library stores them in a ReplayBuffer. It then replays these memories to the learning algorithms, prioritizing experiences that resulted in a large prediction error. This makes learning incredibly efficient.
Meta-Learning & Self-Tuning: An AI that cannot learn how to learn is still a dumb machine. The MetaState module is a meta-learning layer that monitors the agent's own performance over time. If it detects that performance is degrading, it will automatically increase the learning rate ("Synaptic Plasticity"). If performance is improving, it will decrease the learning rate to stabilize the learned strategy. It tunes its own hyperparameters.
Catastrophic Forgetting Prevention: A common failure mode for simple neural networks is "catastrophic forgetting," where learning a new task completely erases knowledge of a previous one. This library includes mechanisms like soft_reset and L2 regularization to prevent the agent's learned weights from exploding or being wiped out by a single bad run of trades, ensuring more stable, long-term learning.
The Universal Socket Interface: How does the AI "see" the market? Through DataSockets. This brilliant, extensible interface allows a developer to connect any data series—an RSI, a volume metric, a volatility reading, a custom calculation—to the AI's "brain." Each socket normalizes its input, tracks its own statistics, and feeds into the state-building process. This makes the library universally adaptable to any trading idea.
█ CHAPTER 3: A DUAL-PURPOSE FRAMEWORK - MODES OF OPERATION
This library is a foundational component of the DAFE AI ecosystem, designed for ultimate flexibility. It can be used in two primary modes: as a powerful standalone intelligence, or as the core cognitive engine within a larger, bridged super-system. Understanding these modes is key to unlocking its full potential.
MODE 1: STANDALONE ENGINE OPERATION (Independent Power
The DafeRLMLLib can be used entirely on its own to create a complete, self-learning trading indicator. This approach is perfect for building focused, single-purpose tools that are designed to master a specific task. In this mode, the developer is responsible for creating the full feedback loop within their own indicator script.
The Workflow:
Your indicator initializes the ML agent.
On each bar, it feeds the agent market data via the socket interface.
It asks the agent for an action (e.g., Buy, Sell, Hold).
Your script then executes its own internal trade logic based on the agent's decision.
Your script is responsible for tracking the Profit & Loss (PnL) of the resulting simulated trade.
When the trade is closed, your script feeds the final PnL directly back into the agent's learn() function as the "reward" signal.
The Result: A pure, state-based learning system. The agent directly learns the consequences of its own actions. This is excellent for discovering novel, micro-level trading patterns and for building indicators that are designed to operate with complete autonomy.
MODE 2: BRIDGED SUPER-SYSTEM OPERATION (Synergistic Intelligence)
This is the pinnacle of the DAFE ecosystem. In this advanced mode, the DafeRLMLLib acts as the core "cognitive engine" or the "tactical brain" within a larger, multi-library system. It can be fused with a strategic portfolio management engine (like the DafeSPALib) via a master communication protocol (the DafeMLSPABridge).
The Workflow:
The ML engine (this library) generates a set of creative, state-based proposals or predictions.
The Bridge Library translates these proposals into a portfolio of micro-strategies.
The SPA (Strategy Portfolio Allocation) engine, acting as a high-level manager, analyzes the real-time performance of these micro-strategies and selects the one it trusts the most. This becomes the final decision. The PnL from the SPA's final, performance-vetted decision is then routed back through the Bridge as a highly-qualified reward signal for the ML engine.
The Result: A hybrid intelligence that is more robust and adaptive than either system alone. The ML engine provides tactical creativity, while the SPA engine provides ruthless, strategic, performance-based oversight. The ML proposes, the SPA disposes, and the ML learns from the SPA's wisdom. This creates a system of checks, balances, and continuous, synergistic learning, perfect for building an ultimate, all-in-one "drawing indicator" or trading system.
As a developer, the choice is yours. Use this library independently to build powerful, specialized learning tools, or use it as the foundational brain for a truly comprehensive trading AI.
█ CHAPTER 4: A GUIDE FOR DEVELOPERS - INTEGRATING THE BRAIN
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. This section provides the full, unabridged input template and usage guide.
PART I: THE INPUTS TEMPLATE
To give your users full control over the AI, copy this entire block of inputs into your indicator script. It is professionally organized with groups and detailed tooltips.
// ╔═════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE (COPY INTO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_RL_AGENT = "═══════════ 🧠 AGENT CONFIGURATION ════════════"
string G_RL_LEARN = "═══════════ 📚 LEARNING PARAMETERS ═══════════"
string G_RL_REWARD = "═══════════ 💰 REWARD SYSTEM ═══════════════"
string G_RL_REPLAY = "═══════════ 📼 EXPERIENCE REPLAY ════════════"
string G_RL_META = "═══════════ 🔮 META-LEARNING ═══════════════"
string G_RL_DASH = "═══════════ 📋 DIAGNOSTICS DASHBOARD ═════════"
// AGENT CONFIGURATION
string i_rl_algorithm = input.string("Actor-Critic", "🤖 Algorithm",
options= , group=G_RL_AGENT,
tooltip="Selects the core learning algorithm. " +
"• Q-Learning: Classic, robust, and fast for discrete states. Learns the 'value' of actions. " +
"• Policy Gradient: Learns a direct probability distribution over actions. " +
"• Actor-Critic: The state-of-the-art. The 'Actor' decides, the 'Critic' evaluates. " +
"• Ensemble: Runs both Q-Learning and Policy Gradient and chooses the action with the highest confidence. " +
"RECOMMENDATION: Start with 'Q-Learning' for stability or 'Actor-Critic' for performance.")
int i_rl_num_features = input.int(8, "Number of Features (Sockets)", minval=2, maxval=12, group=G_RL_AGENT,
tooltip="Defines the size of the AI's 'vision'. This MUST match the number of sockets you connect.")
int i_rl_num_actions = input.int(3, "Number of Actions", minval=2, maxval=5, group=G_RL_AGENT,
tooltip="Defines what the AI can do. 3 is standard (0=Neutral, 1=Buy, 2=Sell).")
// LEARNING PARAMETERS
float i_rl_learning_rate = input.float(0.05, "🎓 Learning Rate (Alpha)", minval=0.001, maxval=0.2, step=0.005, group=G_RL_LEARN,
tooltip="How strongly the AI updates its knowledge. Low (0.01-0.03) is stable. High (0.1+) is aggressive.")
float i_rl_discount = input.float(0.95, "🔮 Discount Factor (Gamma)", minval=0.8, maxval=0.99, step=0.01, group=G_RL_LEARN,
tooltip="Determines the agent's 'foresight'. High (0.95+) for trend following. Low (0.85) for scalping.")
float i_rl_epsilon = input.float(0.15, "🧭 Exploration Rate (Epsilon)", minval=0.01, maxval=0.5, step=0.01, group=G_RL_LEARN,
tooltip="For Q-Learning. The probability of taking a random action to explore. Decays automatically over time.")
float i_rl_lambda = input.float(0.7, "⚡ Eligibility Trace (Lambda)", minval=0.0, maxval=0.95, step=0.05, group=G_RL_LEARN,
tooltip="For Q-Learning. A powerful accelerator that allows a reward to be 'traced' back through a sequence of actions.")
// REWARD SYSTEM
string i_rl_reward_mode = input.string("Normalized", "💰 Reward Shaping Mode",
options= , group=G_RL_REWARD,
tooltip="Modifies the raw PnL reward signal to guide learning. " +
"• Normalized: Creates a stable reward signal (Recommended). " +
"• Asymmetric: Punishes losses more than it rewards gains. Teaches risk aversion. " +
"• Risk-Adjusted: Divides PnL by risk (e.g., ATR). Teaches better risk/reward.")
// EXPERIENCE REPLAY
bool i_rl_use_replay = input.bool(true, "📼 Enable Experience Replay", group=G_RL_REPLAY,
tooltip="Allows the agent to store and re-learn from past experiences. Dramatically improves learning stability. HIGHLY RECOMMENDED.")
int i_rl_replay_capacity = input.int(500, "Replay Buffer Size", minval=100, maxval=2000, group=G_RL_REPLAY)
int i_rl_replay_batch = input.int(4, "Replay Batch Size", minval=1, maxval=10, group=G_RL_REPLAY)
// META-LEARNING
bool i_rl_use_meta = input.bool(true, "🔮 Enable Meta-Learning", group=G_RL_META,
tooltip="Allows the agent to self-tune its own learning rate based on performance trends.")
// DIAGNOSTICS DASHBOARD
bool i_rl_show_dash = input.bool(true, "📋 Show Diagnostics Dashboard", group=G_RL_DASH)
PART II: THE IMPLEMENTATION LOGIC
This is the boilerplate code you will adapt to your indicator. It shows the complete Observe-Act-Learn loop.
// ╔═══════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═══════════════════════════════════════════════════════╝
// 1. INITIALIZE THE AGENT (happens only on the first bar)
int algo_id = i_rl_algorithm == "Q-Learning" ? 0 : i_rl_algorithm == "Policy Gradient" ? 1 : i_rl_algorithm == "Actor-Critic" ? 2 : 3
int reward_id = i_rl_reward_mode == "Raw PnL" ? 0 : i_rl_reward_mode == "Normalized" ? 1 : i_rl_reward_mode == "Asymmetric" ? 2 : 3
var rl.RLAgent agent = rl.init(algo_id, i_rl_num_features, i_rl_num_actions, i_rl_learning_rate, 54, i_rl_replay_capacity, i_rl_epsilon, i_rl_discount, i_rl_lambda, reward_id)
// 2. CONNECT THE "SENSES" (happens only on the first bar)
if barstate.isfirst
// Connect your indicator's data series to the AI's sockets. The number MUST match 'i_rl_num_features'.
agent := rl.connect_socket(agent, "rsi", ta.rsi(close, 14), "oscillator", 1.0)
agent := rl.connect_socket(agent, "atr_norm", ta.atr(14)/close*100, "custom", 0.8)
// ... connect all other features ...
// 3. THE MAIN LOOP (Observe -> Act -> Learn) - runs on every bar
var bool in_trade = false
var int trade_direction = 0
var float entry_price = 0.0
var int last_state_hash = 0
var int last_action_taken = 0
// --- OBSERVE: Build the current market state ---
rl.RLState current_state = rl.build_state(agent)
// --- ACT: Ask the AI for a decision ---
= rl.select_action(agent, current_state)
agent := updated_agent // CRITICAL: Always update the agent state
// --- EXECUTE: Your custom trade logic goes here ---
if not in_trade and ai_action.action != 0 // Assuming 0 is "Hold"
in_trade := true
trade_direction := ai_action.action == 1 ? 1 : -1 // Assuming 1=Buy, 2=Sell
entry_price := close
last_state_hash := current_state.hash // Store the state at the moment of entry
last_action_taken := ai_action.action
// --- LEARN: Check for trade closure and provide feedback ---
bool trade_is_closed = false
float reward = 0.0
if in_trade
// Your custom exit condition here (e.g., stop loss, take profit, opposite signal)
bool exit_condition = bar_index > ta.valuewhen(in_trade, bar_index, 0) + 20
if exit_condition
trade_is_closed := true
pnl = trade_direction == 1 ? (close - entry_price) / entry_price : (entry_price - close) / entry_price
reward := pnl * 100
in_trade := false
// If a trade was closed on THIS bar, feed the experience to the AI
if trade_is_closed
agent := rl.learn(agent, last_state_hash, last_action_taken, reward, current_state, true)
// 4. DISPLAY DIAGNOSTICS
if i_rl_show_dash and barstate.islast
string diag_text = rl.diagnostics(agent)
label.new(bar_index, high, diag_text, style=label.style_label_down, color=color.new(#0A0A14, 10), textcolor=#00FF41, size=size.small, textalign=text.align_left)
█ DEVELOPMENT PHILOSOPHY
The DafeRLMLLib 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 systems that can learn, adapt, and optimize themselves. This library is an open-source framework designed to be a launchpad for a new generation of truly intelligent indicators on TradingView.
This library is designed to help you and your users discover what "the best trades" are, not by following a fixed set of rules, but by learning from the market's own feedback, one trade at a time.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR ADVANCED DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be integrated into other indicators.
REINFORCEMENT LEARNING IS COMPLEX: RL is not a magic bullet. It requires careful feature engineering (choosing the right sockets), a well-defined reward signal, and a sufficient amount of training data (trades) to converge on a profitable strategy.
ALL TRADING INVOLVES RISK: The AI's decisions are based on statistical probabilities learned from past data. It does not predict the future with certainty.
"The goal of a successful trader is to make the best trades. Money is secondary."
— Alexander Elder
Taking you to school. - Dskyz, Create with RL.
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.
Initial Balance Trader NXiIB (Initial Balance) can be trade at IBL or IBH. My setup based on 30min IB zone. This strategy can be trade in GOLD, SP500 or Currencies etc. Can be combine with VP (Volume profile)
Visit us for more:
www.traderxi.com
Market Regime AnalyzerStatistical regime detection with forward-looking transition probabilities. Combines drift testing, variance ratios, and volume delta to classify markets into 5 regimes and quantify transition probabilities.
What Regime Are We In, and What's Likely Next?
That's the question this indicator answers with statistical rigor and forward-looking probabilities.
The Problem:
Most traders classify regimes arbitrarily: "Bull if price > 200 MA" or "Bear if RSI < 30." These rules ignore statistical significance, volume confirmation, and mean reversion patterns. The result? Late entries, false signals, and confusion when markets transition.
The Solution:
Market Regime Analyzer combines drift detection, variance ratio testing, and volume delta analysis to classify markets into 5 distinct regimes. Then it calculates the probability of transitioning to each regime based on historical patterns.
The Benefit:
Know not just where you are, but where you're likely going - with probabilities, not guesses.
The Five Market Regimes
🟢 Strong Bull (Regime 1)
- Statistically significant upward drift (t-stat > 1.96)
- Strong buying pressure (volume delta > 0.3)
- No mean reversion detected
- **Trade:** Trend-following strategies, ride the momentum
🟢 Weak Bull (Regime 2)
- Upward drift present
- BUT weak volume OR mean reversion detected
- **Trade:** Reduce position size, tighten stops, prepare for consolidation
⚪ Consolidation (Regime 3)
- No statistically significant drift
- Mixed volume signals
- Mean reversion likely present
- **Trade:** Range-trading, avoid trend-following systems
🔴 Weak Bear (Regime 4)
- Downward drift present
- BUT weak volume pressure
- **Trade:** Cautious shorts, reduce exposure, prepare for bounce
🔴 Strong Bear (Regime 5)
- Statistically significant downward drift (t-stat < -1.96)
- Strong selling pressure (volume delta < -0.3)
- No mean reversion detected
- **Trade:** Trend-following shorts, protective puts
The Statistical Framework
1. Drift Detection with T-Statistics
Instead of guessing if there's a trend, we test it statistically.
How it works:
- Calculates mean return over lookback period
- Standardizes by volatility
- Compares to significance threshold (default 1.96 = 95% confidence)
What it tells you:
- T-stat > 1.96: Statistically significant uptrend
- T-stat < -1.96: Statistically significant downtrend
- In between: No significant trend (consolidation)
Why it matters:
Only trades trends that are statistically validated, not just visually apparent.
2. Mean Reversion Testing (Variance Ratio)
Based on Lo & MacKinlay (1988) research, this detects when markets are range-bound.
How it works:
- Compares variance at different time scales
- Variance Ratio < 0.8 indicates mean reversion
What it tells you:
- Mean reversion = NO: Trends can continue
- Mean reversion = YES: Expect price to return to mean, not breakout
Why it matters:
Prevents chasing breakouts in range-bound markets.
3. Volume Delta Analysis
Total volume tells you HOW MUCH traded. Volume delta tells you WHO won.
How it works:
- Buying pressure - Selling pressure = Volume Delta
- Normalized to show relative strength
What it tells you:
- Strong positive delta (>0.3): Buyers in control
- Strong negative delta (<-0.3): Sellers in control
- Weak delta: No clear winner
Why it matters:
Price can move up on weak buying or down on weak selling. Volume delta reveals the truth.
4. Transition Probability Matrix
Historical regime changes predict future regime changes.
How it works:
- Tracks every regime transition over last 100 bars (configurable)
- Builds probability distribution for next regime
- Updates continuously
Example:
Current: Strong Bull
Historical transitions from Strong Bull:
- Stayed Strong Bull: 45%
- Became Weak Bull: 30%
- Became Consolidation: 20%
- Became Weak Bear: 4%
- Became Strong Bear: 1%
What it tells you:
Strong Bull has 75% chance of staying bullish (45% + 30%), only 5% chance of bearish turn.
Why it matters:
Adapts to your specific market's behavior patterns.
How to Use This Indicator
Strategy Adaptation
In Strong Bull/Bear Regimes:
- Use trend-following strategies
- Wider stops, let winners run
- Add to positions on pullbacks
- High confidence in directional trades
In Weak Bull/Bear Regimes:
- Reduce position sizes by 50%
- Tighter stops
- Take profits earlier
- Prepare for regime change
In Consolidation:
- Switch to range-trading strategies
- Avoid trend-following systems
- Sell resistance, buy support
- Wait for regime change before trend trades
Risk Management
Position Sizing:
- Strong regime + high continuation probability (>60%) = Normal size
- Weak regime OR high transition probability = Half size
- Consolidation = Quarter size or skip
Stop Loss Placement:
- Strong regime: Use wider stops (2x ATR)
- Weak regime: Tighter stops (1x ATR)
- Consolidation: Very tight stops (0.5x ATR)
Entry Timing
Best entries:
- Regime just changed to Strong Bull/Bear
- High probability (>50%) of staying in current regime
- No divergence signals present
- Drift and volume delta aligned
Avoid entries:
- High probability of regime change
- Divergence signals appearing
- Mean reversion detected in trending regime
- Weak volume despite price movement
Reading the Dashboard
Current Regime
Color-coded for instant recognition:
- Dark Green = Strong Bull
- Light Green = Weak Bull
- Gray = Consolidation
- Light Red = Weak Bear
- Dark Red = Strong Bear
Annualized Drift
Expected annual return based on recent trend.
- Positive = Upward bias
- Negative = Downward bias
- Near zero = No directional edge
T-Statistic
Measures statistical significance of drift.
- > 1.96 = 95% confident in uptrend
- < -1.96 = 95% confident in downtrend
- Between = Not statistically significant
Mean Reversion
- Yes = Expect price to return to mean (range-bound)
- No = Trends can continue (trending market)
Volume Pressure
Normalized volume delta strength.
- > 0.3 = Strong buying
- < -0.3 = Strong selling
- Near 0 = Balanced
Transition Probabilities
Shows most likely next regime.
- Highest probability = Most likely outcome
- Evenly distributed = High uncertainty
- Concentrated = High confidence in direction
Practical Examples
Example 1: Strong Bull with High Continuation
Dashboard shows:
Current Regime: Strong Bull
Drift: +22% annualized
T-Stat: 3.2
Mean Reversion: No
Volume Pressure: +0.45
Probabilities:
→ Strong Bull: 50%
→ Weak Bull: 25%
→ Consolidation: 20%
→ Bears: 5%
Interpretation:
- Strong uptrend (t-stat 3.2 >> 1.96)
- No mean reversion = trends can continue
- Strong buying pressure (0.45 > 0.3)
- 75% chance stays bullish (50% + 25%)
Action:
- Full position size on long setups
- Use trend-following entries
- Wider stops (2x ATR)
- High conviction trades
Example 2: Weak Bull Before Consolidation
Dashboard shows:
Current Regime: Weak Bull
Drift: +8% annualized
T-Stat: 1.2
Mean Reversion: Yes
Volume Pressure: +0.15
Probabilities:
→ Strong Bull: 10%
→ Weak Bull: 30%
→ Consolidation: 50%
→ Weak Bear: 10%
Interpretation:
- Weak drift (t-stat 1.2 < 1.96)
- Mean reversion detected = range-bound likely
- Weak volume (0.15 < 0.3)
- 50% chance of consolidation
Action:
- Reduce long positions
- Tighten stops
- Prepare for range-bound trading
- Avoid new trend trades
Example 3: Regime Transition Alert
Previous: Weak Bull
Current: Consolidation
Volume divergence signal appeared:
Price made new high, volume delta weakened
Interpretation:
- Trend exhausted
- Buyers losing control
- Regime confirmed the transition
Action:
- Exit trend-following longs
- Switch to range-trading approach
- Wait for new regime before new directional trades
Settings Guide
### Regime Detection Period (50)
Number of bars for statistical calculations.
- **30-40:** More responsive, catches changes faster, more regime switches
- **50 (default):** Balanced for daily/4H charts
- **75-100:** More stable, fewer false regime changes, slower to adapt
Transition History Depth (100)
How much history to use for probabilities.
- **50-75:** Adapts quickly to recent behavior
- **100 (default):** Balanced robustness
- **150-200:** More stable probabilities, slower to adapt
Volume Delta Period (14)
Period for volume calculations.
- **7-10:** More sensitive to volume shifts
- **14 (default):** Standard period
- **20-30:** Smoother, less noise
Significance Threshold (1.96)
T-statistic required for trend classification.
- **1.64:** 90% confidence, more trend regimes detected
- **1.96 (default):** 95% confidence, balanced
- **2.58:** 99% confidence, very conservative, mostly consolidation
Best Practices
Do:
- Wait for regime confirmation (at least 3-5 bars in new regime)
- Use probabilities to size positions appropriately
- Combine with support/resistance for entries
- Respect mean reversion signals
- Adapt strategy to current regime
Don't:
- Trade every regime change immediately
- Ignore high transition probabilities
- Use trend strategies in consolidation
- Override statistical signals with gut feel
- Trade against Strong regimes without clear setup
Timeframe Recommendations
Daily Charts:
- Default settings work well
- Most reliable regime detection
- Best for swing trading
4H Charts:
- Use default or slightly higher lookback (60-75)
- Good for active swing trading
- More regime changes than daily
1H Charts:
- Reduce lookback to 30-40
- More noise, use with caution
- Better for intraday position trading
15M and below:
- Not recommended
- Too much noise for statistical validity
- Regimes change too frequently
Combining with Other Indicators
Works Well With:
Moving Averages
- Use regime for directional bias
- MAs for specific entry/exit points
Support/Resistance
- Regime shows context
- S/R shows specific levels
- High probability at confluence
Volume Profile
- Regime shows regime
- Profile shows where volume is
- Target high-volume nodes
RSI/MACD
- Regime provides context
- Momentum shows entry timing
- Combine for higher probability
Example Combined Setup
Regime: Strong Bull
Price: Above 200 MA
Level: Pullback to support
RSI: Oversold (30)
Volume Delta: Still positive
Setup: Long entry
Reason: Trend intact, healthy pullback, buyers still present
Divergence Signals
The indicator shows volume divergence warnings:
Bearish Divergence (Red Triangle Down)
- Price makes new high
- Volume delta makes lower high
- Warning: Buyers weakening, potential reversal
Bullish Divergence (Green Triangle Up)
- Price makes new low
- Volume delta makes higher low
- Warning: Sellers weakening, potential reversal
How to use:
- Divergence in Strong regime = early warning of regime change
- Confirms when regime actually transitions
- Don't trade divergence alone, wait for regime confirmation
Limitations
This Indicator Cannot:
**Predict black swan events** - Unexpected news overrides all technical regimes
**Work in all markets** - Needs liquid markets with reliable volume data
**Guarantee profits** - Probabilities are not certainties
**Replace fundamental analysis** - Technical regimes can diverge from fundamentals
Works Best:
- Liquid markets (major indices, forex, crypto, large-cap stocks)
- Daily and 4H timeframes
- Combined with other analysis
- With proper risk management
- In normal market conditions
Common Questions
"Why did the regime stay consolidation despite strong price move?"
The indicator detected mean reversion (variance ratio < 0.8), indicating the move will likely reverse. Or the move wasn't statistically significant (t-stat < 1.96). Trust the statistics over visual appearance.
"Probabilities show 30% for each regime. What does that mean?"
High uncertainty. The market is at an inflection point. Reduce position sizes and wait for clearer regime formation.
"Can I use this for day trading?"
Not recommended on timeframes below 1H. Statistical tests need sufficient data. Better suited for swing trading.
"Why does this show Strong Bull when my momentum indicators show weakness?"
Momentum can weaken while the trend remains statistically significant. The indicator focuses on drift and volume, not momentum. Consider it a different perspective.
Technical Notes
Volume Delta Approximation
Uses OHLCV data to approximate order flow:
- Buy volume ≈ Volume on up-closes
- Sell volume ≈ Volume on down-closes
- Delta = Buy - Sell
**Note:** Real order flow (from futures or Level 2) is more precise. This approximation works well on liquid markets.
Statistical Tests
Drift T-Test:
- Null hypothesis: No drift (mean return = 0)
- Reject if |t-stat| > threshold
- Based on standard hypothesis testing
Variance Ratio:
- Compares 2-period variance to 1-period variance
- Ratio = 1 for random walk
- Ratio < 1 for mean reversion
- Threshold of 0.8 based on empirical testing
Transition Probability Implementation
Due to Pine Script v5 limitations (no native 2D arrays), the 5×5 transition matrix is stored as a flat 1D array of 25 elements:
- Position maps to index: `row × 5 + col`
- Example: Transition from Regime 2 to Regime 4 is at index `1 × 5 + 3 = 8`
- Laplace smoothing (0.1) prevents zero probabilities
- Row sums normalized to calculate probabilities
This approach is computationally efficient and maintains statistical accuracy.
No Repainting
All calculations confirmed on bar close. Regime changes appear when the bar closes, not during formation. Historical analysis is accurate.
Alert Conditions
Regime Change
- Triggers when regime transitions to any new state
- Message shows new regime number (1-5)
Bearish Divergence
- Triggers when price makes new high but volume delta doesn't confirm
Bullish Divergence
- Triggers when price makes new low but volume delta doesn't confirm
Disclaimer
FOR EDUCATIONAL PURPOSES ONLY
This indicator uses statistical methods to analyze market regimes. It does not predict the future or guarantee trading success.
Markets are probabilistic, not deterministic. A 70% probability of staying bullish means 30% chance of regime change. Always use proper risk management.
Past regime transitions do not guarantee future transitions. Market structure can change. Statistical relationships can break down.
Never risk more than you can afford to lose. Use stop losses on every trade. Test thoroughly before live trading. Consult a qualified financial advisor.
© 2026 | Open Source
Statistical rigor meets practical application
SPX SPY 5Min Lock🔹 DESCRIPTION (Public Library)
This indicator overlays SPX price levels directly onto the SPY chart by converting SPX levels into SPY prices using a session-locked SPY/SPX ratio.
Instead of mentally translating SPX levels, you see them mapped precisely on SPY, where you actually trade.
How it works
• Calculates the SPY-to-SPX price ratio
• Locks the ratio at the first 5-minute RTH candle close (9:35am ET)
• Uses that fixed ratio for the entire session
• Converts SPX levels into accurate SPY-equivalent prices
• Draws clean labels (and optional short stubs) directly on SPY
Why the 5-minute lock
SPY and SPX can drift slightly during the day. Locking the ratio at 9:35am creates stable, non-moving levels that stay consistent throughout RTH, making them far more usable for intraday trading.
Best use cases
• SPY / SPX options traders
• Index-based level traders
• GEX, gamma, and macro level mapping
• Traders who think in SPX but execute in SPY
Customization
• Adjustable SPX level spacing (5 / 10 / 25)
• Number of levels above and below price
• Label size and offset
• Live or Locked ratio mode
• Optional short line stubs
• Info table with ratio and lock status
Daily ATR & Market Cap DisplayDaily ATR & Market Cap Display:
Displays daily ATR percentage with color-coded volatility alerts (🟢 0-4%, 🟡 4-8%, 🔴 8%+) and market cap with size indicators (🔴 <1B, 🟡 1-5B, 🟢 5B+).
Features:
- Daily ATR remains constant across all timeframes
- Customizable position (9 locations + vertical offset)
- Adjustable text size and colors
- Clean, fixed on-screen display
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
TSX Sector ETF Overlay// --- Plot Data with Standard Colors ---
plot(xiu, title="TSX 60", color=color.white, linewidth=2)
plot(xfn, title="Financials", color=color.blue, linewidth=2)
plot(xeg, title="Energy", color=color.orange, linewidth=2)
plot(xma, title="Materials", color=color.yellow, linewidth=2)
plot(xgd, title="Gold Miners", color=color.yellow, linewidth=1)
plot(xit, title="Tech", color=color.purple, linewidth=2)
plot(xre, title="REITs", color=color.red, linewidth=2)
plot(xut, title="Utilities", color=color.green, linewidth=2)
plot(xst, title="Staples", color=color.teal, linewidth=2)
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.
Position Size Dashboard (Gold / Forex / Indices)A clean, MT5-accurate position sizing tool that instantly calculates lot size based on risk and stop-loss range. Designed for discretionary and prop-firm traders who want fast, no-nonsense sizing without manual math. Supports Gold (XAUUSD), Forex pairs, and Indices, with clear on-chart dashboard output.
How to Use (Step-by-Step)
Add the indicator to your chart
Open Settings → Inputs
Enter your Risk ($) (e.g., 100)
Enter SL Range
Forex → pips
Gold / Indices → price points
Enable or disable Gold / Forex / Indices rows as needed
Choose dashboard position, colors, and text size
Click OK → Lot size is calculated instantly and shown on chart
MACD (Standard) + ATR BoxJust a MACD with a ATR values box so no need for wasting a standalone indicator just for the ATR value. You can also calculate the ATR stop loss calculation.
RSquared (log prices)Rolling Trend R² measures the strength of trends using a rolling R² calculation on log prices. Values near 1 indicate a strong, persistent trend, while low values signal choppy or mean-reverting conditions. Includes regime highlighting, reference levels, and an info panel for quick market state identification.
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.
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)
ATLAS_COREShared utility library for the ATLAS Trading Intelligence Suite. Provides brand colors, math utilities, candle analysis, grading system, visual helpers, and more.
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.
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.






















