Asia / London / Overlap / NY Sessions - Live + Futuresession markers to determine which session you're currently playing at
指標和策略
Historical Annual Avg Growth Lines + 1-Year ProjectionThis script creates an overlay indicator on your TradingView chart that visualizes the historical average annual growth rate of the selected instrument (e.g., TSLA) in a specific way. Here's a step-by-step summary of what it represents and how it works:
Overall Purpose
It calculates the average annual percentage gain (arithmetic mean) across the instrument's entire trading history, using non-overlapping periods of 252 trading days each (approximating one year, excluding weekends/holidays).
It then draws horizontal green lines on the chart for each complete "year" segment, showing a projected "fair value" price level for that year based on the overall average growth rate.
This helps you compare actual historical price action against what the price "would have been" if it had grown steadily at the stock's long-term average annual rate. Lines above actual prices suggest periods where growth exceeded the average (potentially overvalued in hindsight), while lines below suggest underperformance (potentially undervalued).
The calculation excludes the most recent incomplete year (any bars beyond the last full 252-day segment), ensuring only fully realized historical periods are used.
Key Calculations
Identifying Complete Years: It divides the chart's data from the first trading day (bar_index 0) into segments of exactly 252 bars each. For example:
Year 1: Bars 0 to 251
Year 2: Bars 252 to 503
And so on, up to the last full segment before the current bar.
If the total bars aren't a perfect multiple of 252, the partial current year is ignored.
Average Annual % Gain: For each complete year segment:
It computes the % gain as (end_price - start_price) / start_price.
Sums these % gains across all years and divides by the number of years to get the overall average (e.g., if TSLA averaged 42% per year historically, that's the value used).
Projected Price Lines: For each year segment:
Takes the starting price of that year.
Applies the overall average % gain to project a "target" end-of-year price: start_price * (1 + average_annual_gain).
Draws a horizontal line at that projected price level, spanning only the bars of that specific year (e.g., a flat green line covering 252 bars, positioned above or below the actual price action for visual comparison).
Visual Representation
Horizontal Lines: Each green line is flat and covers one historical year block on the chart. Earlier years (left side) will have lower projected prices (reflecting lower starting prices), while later years (right side) will have higher ones as the base price compounds over time—but each is independent and based on that year's start.
No Smoothing or Rolling: Unlike a moving average, these are static historical segments (non-overlapping), recalculated only on the last bar for efficiency.
Example on TSLA: Assuming TSLA's long-term average annual gain is ~42% (based on its history since 2010 IPO), the line for Year 1 would be at * 1.42, spanning the first 252 bars. Year 2 would start from the actual price at bar 252 and project * 1.42, and so on. If lines are consistently above actual prices in recent years, it might indicate recent growth slowing relative to historical averages.
Forward Projection (1 Year Out)
The script also extends a dashed orange horizontal line to the right of the current bar, projecting the price one year into the future based on the same historical average annual growth rate.
It starts from the end price of the last complete historical year as the base.
Applies the average % gain once more to estimate the "target" price after another 252 trading days (e.g., base_price * (1 + average_annual_gain)).
The line is dashed and orange for distinction, extending approximately 252 bars to the right (scroll or zoom right to view the full projection). This provides a visual guide for where the price "might" trend if growth continues at the historical average, helping with long-term investment planning like setting targets or assessing potential upside.
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.
CRZTestBuildV2At market open, the indicator plots daily zones derived from the previous session's range and volatility, using statistically common extensions and reactions from similar prior days. These zones act as areas of interest where price commonly stalls, reverses, or accelerates, which makes them useful or HOD/LOD reference and structure trade entries.
Log-Returns Anomaliad Z-score + VolatilidadLog-Returns: Anomalías (Z-score + Volatilidad)
Log-Returns: Anomalies (Z-score Volatility) This is the mathematically correct way to measure the price change between two periods
BOS/CHoCH Impulsive Move Detector #12.2Includes all updates. This indicator includes all BOS & CHoCH impulses and identifies impulses of greater than 5% and differentiates between longs and shorts.
Mine Shaft + Drift + Ore Pocket Detector (Gap+Touch)Mine Shaft + Drift + Ore Pocket Detector (Gap+Touch) — Full Description (v1.6.1, Pine v6)
*Experimental - *Test Phase*
1) What this indicator is intended to do
This indicator attempts to algorithmically discover “mine shaft” price structure on a chart by:
Collecting structural anchor points (gaps and optionally pivots),
Generating candidate trend “rails” (centerline + parallel upper/lower borders) from pairs of anchors,
Fitting an optimal channel width around each candidate centerline,
Scoring candidates based on how well price action conforms to the channel (touches + containment),
Selecting and rendering:
the main shaft channel (primary),
additional drifts (secondary shafts per direction),
And then detecting Ore Pockets: time locations where multiple selected lines intersect (time confluence / intersection clustering).
The conceptual model is:
A shaft = a best-fit channel that price respects over time (the “main tunnel”).
Drifts = alternate channels close in quality to the main shaft (secondary tunnels).
Ore pockets = future/past time coordinates where multiple channels’ centerlines intersect densely (confluence in time, not necessarily in price).
2) What it is doing right now (current behavior)
In its current form, the script does a bounded, performance-limited scan:
It stores a limited number of anchor points in arrays.
It only considers a bounded number of recent anchors per direction.
It constructs candidate lines from anchor pairs and evaluates channel fitness using sampled bars.
On the last bar, it selects top candidates per direction and draws:
a “main” channel per mode (single best overall, or separate up/down),
plus optional drift channels,
plus ore pocket markers.
It is producing meaningful channels and drifts, but it is currently more likely to lock onto a strong “local” shaft than the one macro shaft spanning the entire market structure.
3) Core mechanics (how the script finds shafts)
3.1 Anchor generation (what points it uses)
Anchors are the “support points” used to build candidate shaft centerlines.
Two anchor families are supported:
A) Gap anchors (from your selected gap mode)
These attempt to capture “displacement events” and their boundaries/mids.
B) Pivot anchors (optional structural anchors)
These use pivots to inject macro structure points that are not strictly gap-based.
All anchors are stored as:
anchorX: bar_index of anchor
anchorY: price of anchor
anchorD: direction flag (+1 for up, -1 for down)
Anchors are capped by maxAnchors with FIFO trimming.
3.2 Candidate generation (how it produces centerlines)
For each direction (+1 and -1):
Collect “recent” anchors of that direction within lookbackBars (bounded to maxDirAnchors).
For each pair of anchors (x1,y1) and (x2,y2) that satisfy:
spacing within ,
slope sign consistent with direction,
Construct the line equation:
slope m and intercept b
Fit a channel width w around that line (via width mode).
Score it (touches + inside count minus width penalty).
Keep the top K rails (K = driftCount+1 typically).
3.3 Scoring model (what “best” means right now)
For a candidate centerline:
At sampled bars (stride sampling), compute:
channel top = y(x) + w
channel bot = y(x) - w
Evaluate:
Inside: candle range fits within the channel ± tolerance
Touches: high near top border, low near bottom border (within tolerance)
Score formula:
score = insideCount * insideWeight
+ touchCount * touchWeight
- (w / ATR) * widthPenalty
So:
Higher inside and touch counts increase score
Wider channels are penalized (in ATR units) to avoid “cheating” via enormous width
3.4 Width fitting (how the channel thickness is chosen)
Width is either:
Fit (scan widths): scans widths between a min width and a max deviation cap and selects the best scoring width.
Fixed ATR Envelope: uses a fixed width derived from ATR (currently hard-coded to a 2.0 ATR envelope in your present draft).
Fixed Max Deviation: width is max observed deviation from line in sampled window.
This matters because “macro shaft” detection is strongly influenced by whether the width-fitting is allowed to expand enough to contain large historical moves, without being penalized into losing to a smaller local shaft.
3.5 Rendering (what gets drawn)
For any selected rail, it draws:
Upper border line (top rail)
Lower border line (bottom rail)
Optional centerline (main only)
Optional fill between borders (main only)
Label at current bar with touches and inside count
Drifts render similarly but without main-only features (depending on flags).
3.6 Ore Pocket detection (time confluence)
Ore pockets are not “price zones” directly.
They are computed as follows:
Collect selected centerlines (m,b) for:
the main selected shaft(s),
and all drift centerlines (both directions if present)
For each pair of selected lines, compute intersection x-coordinate:
x* = (b2 - b1) / (m1 - m2)
Only keep intersections within:
Cluster intersections by time proximity (clusterBars)
Mark the strongest clusters (highest counts) as “Ore Pocket” vertical dotted lines with labels.
Interpretation:
A dense cluster indicates many selected rails converge around a similar time coordinate.
It is a “time confluence” hypothesis point.
4) Full settings reference (what each setting is for)
01) Gap Anchors
Gap Mode
FVG (3-candle)
Uses a classic 3-candle fair value gap pattern:
Up gap if low > high
Down gap if high < low
Anchors are derived from the gap boundaries.
Candle Gap (open-close)
Gap based on open vs close of the same bar with a tick threshold.
Candle Gap (open-prev close)
Gap based on open vs close with a tick threshold.
Gap Threshold (ticks)
Only used for the candle gap modes.
Controls the minimum gap size required to register an anchor.
Anchor Price
Boundary: anchors at one gap boundary (more “structural edge”)
Mid: anchors at midpoint of the gap (more “center of displacement”)
Include Pivot Anchors (structure)
When enabled, adds pivots as additional anchors to stabilize macro detection.
Pivot Length
Pivot sensitivity (how many bars left/right define a pivot).
Larger values = fewer, more structural pivots.
02) Channel Fit + Touch Scoring
Lookback Bars
The historical window used to:
filter which anchors are considered “recent enough”
evaluate channel fitness (sampled evaluation)
Larger lookback tends to favor macro shafts, but also increases computational risk (mitigated by evalBars and stride).
ATR Length
ATR period used for tolerance and width penalty scaling.
Tolerance (ATR mult)
Defines how close price must be to a rail to count as “touch” and how strict the “inside channel” containment is.
Higher tolerance = easier to score high on touch/inside.
Min Border Touches (keep rail)
Minimum number of border touches required before a candidate is even eligible.
Score: Inside Weight
Weight of inside count in score.
Score: Border Touch Weight
Weight of border touches in score.
This is a strong driver of “shaft-like” behavior.
Score: Width Penalty (in ATRs)
Penalizes wide channels relative to ATR.
Higher penalty biases toward narrow/local shafts.
03) Performance Controls
Max Stored Anchors (global)
Maximum anchor points kept in memory arrays.
Too low can cause loss of macro structure; too high increases candidate noise.
Max Anchors / Direction (scan)
Hard cap on how many anchors are used in candidate generation per direction.
Critical: this strongly influences whether macro shaft can be found, because if you only keep the most recent anchors, you lose the early-structure anchor points.
Eval Bars (max)
Maximum historical bars actually evaluated for scoring.
Even if lookbackBars is large, evaluation is capped here.
Eval Stride (sample every N bars)
Sampling step for evaluation.
Larger stride = faster but less accurate scoring.
04) Candidate Generation
Min Anchor Spacing (bars)
Minimum distance between the two anchors used to define a candidate line.
Prevents micro-noise lines from being evaluated.
Max Anchor Spacing (bars)
Maximum distance between the two anchors used to define a candidate line.
If this is too low, you cannot generate truly macro candidate lines.
05) Shaft + Drift Display
Main Shaft Mode
Best Overall (Single Shaft): chooses one best rail among Up/Down and draws it as main.
Up Only: show only the best upward rail.
Down Only: show only the best downward rail.
Up + Down: show both main up rail and main down rail simultaneously.
Show Ascending Shaft
Toggles rendering for the “up” main shaft (when mode allows it).
Show Descending Shaft
Toggles rendering for the “down” main shaft (when mode allows it).
Drifts per Direction
Number of additional top-ranked rails to draw per direction (after the best one).
Extend Lines
Right: extend lines to the right only.
Both: extend both left and right.
Fill Main Shaft Channel
Fill between upper and lower borders for main shaft.
Main Shaft Fill Transparency
Transparency level for main fill.
Show Main Shaft Centerline
Draw the dashed centerline for the main shaft.
06) Ore Pocket (Intersection-Time Confluence)
Show Ore Pockets (Time Confluence)
Enables ore pocket discovery and rendering.
Intersection Window Forward (bars)
How far into the future intersections are considered.
Intersection Window Backward (bars)
How far into the past intersections are considered.
Cluster Radius (bars)
How close in time intersections must be to merge into a cluster.
Min Intersections per Cluster
Minimum cluster count required before a pocket is shown.
Max Pocket Markers
Limit how many pocket clusters are drawn.
07) Visual Controls
Show Gap Anchors
Displays the gap anchor dots for debugging.
Show Pivot Anchors
Displays pivot anchor dots for debugging.
5) How to use it (practical workflow)
Step A — Confirm anchor behavior
Turn on Show Gap Anchors.
Choose your Gap Mode.
Verify you are seeing anchors where you expect (displacement boundaries).
If anchors are sparse:
Reduce gap threshold (ticks) for candle-gap modes
Enable pivots to inject structure
Increase lookbackBars and maxAnchors so early anchors are not dropped
Step B — Get stable main shaft candidate discovery
Enable Include Pivot Anchors with a medium pivotLen.
Use Fit (scan widths) initially.
Increase Max Anchors / Direction (scan) so you’re not only using recent anchors.
Increase Max Anchor Spacing so macro pairs are eligible.
If you keep getting only local shafts:
That is usually because the candidate pool does not include enough old anchors, or the maxSpacing prevents long-span lines.
Step C — Tune scoring so the “whole-structure” shaft wins
If the script picks a small local channel instead of the macro channel:
Increase insideWeight relative to touchWeight (macro channels tend to contain longer structure even with fewer perfect “touches”)
Reduce widthPenalty, because macro channels may need to be wider to accommodate historical volatility
Increase lookbackBars and evalBars to make “whole-structure fit” matter
Step D — Drifts as secondary shafts
Once main shaft is good:
Increase Drifts per Direction
Validate that drifts represent meaningful alternate sub-shafts rather than noisy duplicates.
If drifts look too similar:
This is expected if many candidates differ only slightly; future refinements should diversify drift selection (see “what still needs done”).
Step E — Ore pockets interpretation
Ore pockets indicate time confluence of multiple rails.
Use them as:
“Time windows to watch”
Not as deterministic price levels
Tune:
clusterBars (cluster tightness)
minClusterSize (signal strength)
6) What still needs done (explicit backlog)
The macro “main mining shaft channel” spanning the entire market structure, and
Smaller shafts/drifts nested inside the macro structure.
To accomplish that, the current algorithm needs additional architecture. Concretely:
A) True multi-scale / hierarchical discovery (primary missing feature)
Right now: one pass, one lookback, one score objective.
Still Needed:
Macro pass: discover a primary shaft using a very long evaluation window and anchor set.
Micro pass(es): discover drifts/secondary shafts using:
residuals (distance from macro centerline),
or segmented time windows (regime partitions),
or anchor subsets constrained to local regions.
This is the single biggest reason we are not consistently getting the full-structure shaft.
B) Anchor retention strategy for macro detection
Right now:
anchors are FIFO capped and direction scanning uses “recent anchors only.”
To reliably find 10-year shafts we need:
an option to store/retain representative anchors across the entire history, not only the most recent ones.
Examples of necessary improvements:
“Stratified anchor sampling” across time (keep some old anchors even when maxAnchors is hit)
“Macro anchor bank” (separate storage for pivots or major gaps)
C) Candidate generation constraints must support macro lines
If we want a shaft spanning the whole structure:
maxSpacing must allow it
the candidate pool must contain anchors far apart in time
So the algorithm needs:
better selection of anchor pairs for long-span candidates (e.g., include earliest/oldest anchors + newest anchors deliberately, not accidentally)
D) Drift diversification
Right now drifts are “next best by score,” which often yields near-duplicates.
We want:
“diverse” secondary shafts:
enforce minimum angular difference,
enforce minimum offset difference,
or penalize candidates too similar to the already-selected shaft.
E) Width fitting logic for macro channels
Macro channels often require:
either a higher width cap,
or a different penalty profile.
Current width penalty is simple and can bias against macro channels.
Needed:
width penalty that scales by timescale or by total evaluated bars,
or separate macro/micro scoring.
F) Ore pocket semantics enhancement (optional but aligned)
Currently pockets are time intersections only.
If you want “pocket zones,” improvements could include:
projecting intersection price and drawing a zone box,
clustering in (time, price) space instead of only time,
adding “importance” weighting based on which lines intersect (macro line intersections weighted higher).
7) Known limitations (current version)
Heavy compute only runs on last bar (good for performance), but means:
changes in anchors/parameters can reselect rails abruptly
Candidate set is bounded; macro shaft can be missed if not in pool
Drift selection can be redundant
Ore pockets are time clusters, not price clusters
btall//@version=5
strategy("AR | AlphaEdge Pro (No-Repaint) v1.0",
overlay=true,
initial_capital=100000,
commission_type=strategy.commission.percent,
commission_value=0.04,
slippage=1,
pyramiding=0,
calc_on_order_fills=true,
calc_on_every_tick=false,
process_orders_on_close=true)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Inputs
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
grp1 = "Trend + Signals"
useHTF = input.bool(true, "Use Higher TF Trend Filter", group=grp1)
htf = input.timeframe("240", "Higher Timeframe", group=grp1)
htfEmaLen = input.int(200, "HTF EMA Length", minval=1, group=grp1)
emaFastLen = input.int(21, "Fast EMA", minval=1, group=grp1)
emaSlowLen = input.int(55, "Slow EMA", minval=1, group=grp1)
stAtrLen = input.int(10, "Supertrend ATR Length", minval=1, group=grp1)
stFactor = input.float(3.0, "Supertrend Factor", minval=0.1, step=0.1, group=grp1)
rsiLen = input.int(14, "RSI Length", minval=1, group=grp1)
rsiBull = input.int(52, "RSI Bull Threshold", minval=1, maxval=99, group=grp1)
rsiBear = input.int(48, "RSI Bear Threshold", minval=1, maxval=99, group=grp1)
useVolFilter = input.bool(true, "Use Volume Filter", group=grp1)
volLen = input.int(20, "Volume SMA Length", minval=1, group=grp1)
volMult = input.float(1.2, "Volume Multiplier", minval=0.1, step=0.1, group=grp1)
grp2 = "Risk Management (ATR)"
atrLen = input.int(14, "ATR Length", minval=1, group=grp2)
slAtrMult = input.float(1.6, "Stop = ATR x", minval=0.1, step=0.1, group=grp2)
rr = input.float(2.0, "Risk:Reward (TP)", minval=0.1, step=0.1, group=grp2)
useRiskPct = input.bool(true, "Dynamic Position Size by Risk %", group=grp2)
riskPct = input.float(1.0, "Risk % of Equity per Trade", minval=0.05, step=0.05, group=grp2)
maxPosPct = input.float(20.0, "Max Position % of Equity Cap", minval=1.0, step=1.0, group=grp2)
grp3 = "Breakeven + Session"
useBE = input.bool(true, "Move Stop to Breakeven", group=grp3)
beTriggerATR = input.float(1.0, "Trigger After +ATR x", minval=0.1, step=0.1, group=grp3)
beOffsetATR = input.float(0.05, "BE Offset (ATR x)", minval=0.0, step=0.01, group=grp3)
useSession = input.bool(false, "Trade Only in Session", group=grp3)
sess = input.session("1000-1500", "Session (exchange time)", group=grp3)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Helper / Filters
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
inSession = not useSession or not na(time(timeframe.period, sess))
emaFast = ta.ema(close, emaFastLen)
emaSlow = ta.ema(close, emaSlowLen)
rsi = ta.rsi(close, rsiLen)
atr = ta.atr(atrLen)
volOk = not useVolFilter or (volume > ta.sma(volume, volLen) * volMult)
// Supertrend
= ta.supertrend(stFactor, stAtrLen) // stDir: 1 bullish, -1 bearish (TradingView behavior)
stBull = stDir == 1
stBear = stDir == -1
// HTF trend (lookahead_off to reduce repaint risk on historical vs realtime behavior)
htfEma = request.security(syminfo.tickerid, htf, ta.ema(close, htfEmaLen), barmerge.gaps_off, barmerge.lookahead_off)
htfBull = close >= htfEma
htfBear = close <= htfEma
trendOkLong = not useHTF or htfBull
trendOkShort = not useHTF or htfBear
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Entry Conditions (confirmed bar to avoid “intrabar” surprises)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
longSignal = barstate.isconfirmed and inSession and trendOkLong and stBull and close > emaFast and emaFast > emaSlow and rsi >= rsiBull and volOk
shortSignal = barstate.isconfirmed and inSession and trendOkShort and stBear and close < emaFast and emaFast < emaSlow and rsi <= rsiBear and volOk
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Position sizing by ATR stop distance (approx; works best on stocks/spot)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
f_posQty(_stopDist) =>
// Risk capital = equity * riskPct%
riskCapital = strategy.equity * (riskPct / 100.0)
// Qty to risk roughly riskCapital if stop hits
rawQty = _stopDist > 0 ? (riskCapital / _stopDist) : 0.0
// Cap position size by maxPosPct% of equity
maxPositionValue = strategy.equity * (maxPosPct / 100.0)
maxQty = close > 0 ? (maxPositionValue / close) : rawQty
qty = math.max(0.0, math.min(rawQty, maxQty))
qty
stopDist = atr * slAtrMult
qty = useRiskPct ? f_posQty(stopDist) : na
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Entries
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
if (longSignal and strategy.position_size <= 0)
strategy.entry("L", strategy.long, qty=useRiskPct ? qty : na)
if (shortSignal and strategy.position_size >= 0)
strategy.entry("S", strategy.short, qty=useRiskPct ? qty : na)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Exits (ATR SL/TP + optional Breakeven)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
entry = strategy.position_avg_price
longSL = entry - stopDist
longTP = entry + stopDist * rr
shortSL = entry + stopDist
shortTP = entry - stopDist * rr
// Breakeven logic
beTrig = atr * beTriggerATR
beOff = atr * beOffsetATR
if isLong and useBE
// if price moved in our favor enough -> raise stop to entry (+offset)
if (close - entry) >= beTrig
longSL := math.max(longSL, entry + beOff)
if isShort and useBE
if (entry - close) >= beTrig
shortSL := math.min(shortSL, entry - beOff)
// Submit exits every bar so they update dynamically
strategy.exit("XL", from_entry="L", stop=longSL, limit=longTP, when=isLong)
strategy.exit("XS", from_entry="S", stop=shortSL, limit=shortTP, when=isShort)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Visuals + Alerts
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
plot(emaFast, "EMA Fast", linewidth=2)
plot(emaSlow, "EMA Slow", linewidth=2)
plot(stLine, "Supertrend", linewidth=2)
plot(useHTF ? htfEma : na, "HTF EMA", linewidth=2)
plotshape(longSignal, title="Long Signal", style=shape.triangleup, location=location.belowbar, size=size.tiny, text="L")
plotshape(shortSignal, title="Short Signal", style=shape.triangledown, location=location.abovebar, size=size.tiny, text="S")
alertcondition(longSignal, title="AlphaEdge Long", message="AlphaEdge LONG on {{ticker}} @ {{close}}")
alertcondition(shortSignal, title="AlphaEdge Short", message="AlphaEdge SHORT on {{ticker}} @ {{close}}")
Bollinger Bands with 3SD Volume SegmentationPurpose
This script provides a structured way to analyze how real traded volume distributes across the different volatility zones defined by Bollinger Bands with three standard deviations, it reveals where activity concentrates, how pressure shifts between buyers and sellers, and how market participation behaves as price moves through expanding or contracting volatility regimes. The tool turns the bands into a mechanical segmentation system that exposes the microstructure hidden inside each volatility layer.
How it works
The script calculates Bollinger Bands at one, two, and three standard deviations, then assigns every bar’s volume to the correct volatility zone based on where price closed, it reconstructs buy and sell volume from candle behavior, computes delta as the difference between them, and aggregates these values over the chosen lookback window. Each zone displays total volume, delta, and a dominance percentage that expresses how strongly buyers or sellers controlled that region, all updated dynamically on the most recent bar. For example, if the Mid–U1 zone shows 28,450 contracts with a –2,728 delta and –9.59% dominance, that indicates mild seller control in a normally balanced rotation area, while the L1–Mid zone showing 10,606 contracts, +1,816 delta, and 17.12% dominance signals buyers absorbing pressure and defending the pullback.
Rationale
Volatility zones behave like natural boundaries where liquidity concentrates, where traders commit, hesitate, or get trapped, and where expansions or reversals often originate, so segmenting volume and delta by these zones provides a clearer picture of intent and pressure than raw volume alone. By quantifying how much buying or selling occurred in each volatility layer, the script helps identify continuation, absorption, exhaustion, and imbalance, giving traders a mechanical, objective map of market behavior rather than relying on subjective interpretation.
BOS, CHoCH and CISD [theEccentricTrader]█ OVERVIEW
This open-source indicator plots Break of Structure (BOS), Change of Character (CHoCH) and Change in State of Delivery (CISD) events directly on the chart and provides optional alerts for each condition.
All conditions are built around my primitive swing logic and are confirmed at candle close to avoid repainting.
The script is designed as a research tool, not a trading strategy. It does not generate entries, exits, targets or risk management rules. Its purpose is to make objectively defined market structure events visible, reproducible and testable across markets and timeframes.
█ CONCEPTS
Green and Red Candles
A green candle is defined as a candle that closes at or above its open.
A red candle is defined as a candle that closes below its open.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing or the low of the preceding red candle, depending on which is lower.
Basic Uptrends and Downtrends
Basic uptrends, henceforth referred to as uptrends, are formed when the most recent trough is higher than the preceding trough.
Basic downtrends, henceforth referred to as downtrends, are formed when the most recent peak is lower than the preceding peak.
Break of Structure (BOS)
A BOS occurs when price continues in the direction of the prevailing trend by breaking beyond the most recent peak or trough price. BOS implies trend continuation through structural expansion.
BOS Up occurs during an uptrend when price closes above the most recent peak.
BOS Down occurs during a downtrend when price closes below the most recent trough.
Change of Character (CHoCH)
A CHoCH occurs during an uptrend or downtrend when price breaks the most recent peak or trough price in the opposite direction to the prevailing trend, without fully reversing the higher-level trend structure. CHoCH implies early structural weakness or internal rotation rather than confirmed trend reversal.
CHoCH Up occurs during a downtrend when price closes above the most recent peak but remains below the preceding peak.
CHoCH Down occurs during an uptrend when price closes below the most recent trough but remains above the preceding trough.
Change in State of Delivery (CISD)
A CISD occurs when price breaks the most recent peak or trough price. CISD isolates pure structural displacement, independent of trend classification.
CISD Up occurs when price closes above the most recent peak without regard for trend state.
CISD Down occurs when price closes below the most recent trough without regard for trend state.
█ VISUAL OUTPUTS
Labels
Labels are plotted at the candle where each condition is confirmed.
Users can change the label colours and sizes via indicator Settings/Inputs/LABELS.
Event Lines
Horizontal dashed lines mark the peak or trough that was broken.
Trend Lines
Trend lines are drawn to contextualise trend direction for appropriate structural events.
█ ALERTS
Optional alerts are provided for all conditions. By default, all alerts are set to false.
Users can apply alerts via Indicator Settings/Inputs/ALERTS.
SMC One Candle + AMD Bias (CT Focus)This indicator is a specialized Smart Money Concepts (SMC) tool designed for QQQ on the 5-minute chart. It fuses Tony Trades' "One Candle Rule" execution with the AMD (Accumulation, Manipulation, Distribution) cycle logic found in your previous CRT Pro V2 script.
The primary goal of this indicator is to identify high-probability entries during the Purge Window (9:00 AM – 11:30 AM CT) by detecting when price manipulates morning liquidity before expanding in the direction of the daily bias.
## Core Components
### 1. Master Candle Range (Accumulation)
Timeframe: 05:00 AM – 09:00 AM CT.
Function: It automatically plots the Master High (CRH) and Master Low (CRL). This represents the "Accumulation" phase where orders are built up before the New York open.
### 2. The One Candle Zone (Execution)
Timeframe: 08:35 AM CT (The 5-minute candle immediately following the high-volatility open).
Function: It creates a blue "Value Zone" based on Tony Trades’ logic. This zone acts as the ultimate filter—price must reclaim or break this zone to confirm that the "Manipulation" phase is over and the "Distribution" has begun.
### 3. Multi-Timeframe Daily Bias
Calculation: It tracks the midpoint (Equilibrium) of the previous day's range.
Premium/Discount:
Bullish (Discount): Price is trading above the daily midpoint.
Bearish (Premium): Price is trading below the daily midpoint.
Logic: Signals are filtered by this bias to ensure you are always trading with the higher-timeframe flow.
## Signal Logic Descriptions
### SMC Long (Bullish Distribution)
A Long signal is generated when:
Bias: The Daily Bias is Bullish.
Manipulation: Price has ideally swept the Master Low (CRL) during the open.
The Trigger: A 5-minute candle closes above the 08:35 AM "One Candle" High.
Confirmation: This suggests shorts are trapped and Smart Money is distributing price toward the Previous Day High (PDH).
### SMC Short (Bearish Distribution)
A Short signal is generated when:
Bias: The Daily Bias is Bearish.
Manipulation: Price has ideally swept the Master High (CRH).
The Trigger: A 5-minute candle closes below the 08:35 AM "One Candle" Low.
Confirmation: This confirms a rejection of the opening range, signaling a move toward the Previous Day Low (PDL) or the current Low of Day.
## Visual Guide
Blue Box: The One Candle Zone (Tony Trades' "Line in the Sand").
Gray Stepline: The Master Candle Range (0500–0900 CT).
Yellow Background: The Purge Window (0900–1130 CT), where your logic dictates the highest probability of a successful trade.
Labels: Real-time Daily Bias updates in the top right corner.
FVG w/ Correlated ConfirmationThis Pine Script indicator detects Fair Value Gaps (FVGs) on your chart—price gaps between candles where no trading occurred, often signaling potential support or resistance zones. It highlights bullish FVGs (gap ups) and bearish FVGs (gap downs) as colored boxes directly on the chart. The indicator also optionally confirms these FVGs by checking if a correlated asset (e.g., NASDAQ:NDX) shows a similar FVG, increasing confidence. Midpoint lines inside the boxes can be displayed to mark the center of the gap.
Boxes are anchored to the exact candles where the FVG forms and extend rightwards by a user-defined number of bars, remaining fixed and not sliding as new bars form. Correlated FVGs add an extra layer of confirmation from related markets, improving reliability and reducing false signals.
MA Labels (Fully Custom, Padded)On screen reminder of whatever you want. I use it remember what MA line colors are.
HVN Boundary Assist FRVP + ATR Tempo Auto TF Defaults (LOCKED)This indicator is a structure-assist tool, not a signal generator. It is designed to standardize High-Volume Node (HVN) boundary placement and evaluation when using TradingView’s Fixed Range Volume Profile (FRVP) on weekly and monthly timeframes.
The script does not attempt to discover HVNs automatically. The trader selects the HVN visually using FRVP and inputs the HVN center (effective VPOC). From there, the script applies consistent, rules-based logic to define boundaries, track interaction, and prevent lower-timeframe levels from conflicting with higher-timeframe structure.
What the indicator does
1. Standardizes HVN boundary placement
Using the active timeframe’s ATR, the indicator identifies the first candle that regains tempo on each side of the HVN center.
A valid boundary requires:
A bar range ≥ a fixed fraction of ATR
A close that breaks prior rotational overlap
The close of that candle becomes the candidate HVN high or low. Wicks are ignored for structure.
2. Automatically adapts to timeframe
The indicator enforces locked system defaults:
Weekly: 0.33 ATR expansion, 10-bar overlap lookback
Monthly: 0.25 ATR expansion, 8-bar overlap lookback
These values adjust automatically based on chart timeframe, eliminating discretionary tuning.
3. Tracks retests without redefining structure
HVN interaction is tracked via wick touches within a tight ATR-based tolerance.
Retests are informational only and never move boundaries. This captures recognition and rejection behavior without violating close-based structure rules.
4. Ranks HVN strength (0–3)
Each HVN is scored using:
Tightness relative to ATR
Relative volume confirmation
Presence of at least one retest
This produces a simple, comparable strength ranking without overfitting.
5. Enforces clean monthly → weekly nesting
An optional monthly gate restricts weekly logic to operate only inside a defined monthly HVN.
If conflicts arise, monthly structure always overrides weekly, preventing level overlap and structural ambiguity.
What the indicator does NOT do
It does not read FRVP data (TradingView limitation)
It does not auto-detect HVNs
It does not generate trade signals
It exists to remove subjectivity and inconsistency from HVN boundary placement and evaluation.
Intended use
Apply FRVP and visually identify the HVN
Enter the HVN center price into the indicator
Let the script define precise boundaries and interaction metrics
Use monthly HVNs as structural rails and weekly HVNs for execution
Design philosophy
Structure is defined by closes and volatility, not wicks
Retests measure recognition, not acceptance
Higher timeframe structure always dominates
This tool enforces those rules mechanically so the trader doesn’t have to.
Group 2: Weekly Regime ClassifierThis indicator classifies the weekly market regime inside monthly value so you know whether to rotate, wait, prepare for expansion, or stand aside before looking for daily trades.
Purpose: Decide whether the market is rotating, compressing, attempting to escape value, or should be avoided entirely.
What this script does
This script analyzes weekly price behavior in the context of your manually defined monthly value area. Its job is to classify the current weekly regime so you know which type of trade logic is even allowed, before you look at daily setups.
It answers one question:
“What kind of environment am I dealing with right now?”
It does not generate trades. It does not choose entries or exits. It tells you whether conditions favor:
value rotation,
expansion attempts,
waiting, or
standing aside due to instability.
How it works (in simple terms)
The script always evaluates weekly candles, even if you apply it to a daily chart.
It uses four ideas:
1. Monthly value containment
All weekly analysis is framed by your monthly VAH and VAL.
If weekly closes are outside monthly value, that matters.
If weekly closes are inside monthly value, that matters differently.
The monthly levels are manual inputs and never auto-calculated.
2. Weekly alternation (instability check)
The script checks the last 6 weekly candles:
If most candles flip direction back and forth, the environment is unstable.
This is labeled “Neutral – heavy alternation”.
In this state, trades should be skipped unless conditions are perfect.
This acts as a sector-level permission filter.
3. Weekly regime classification
Based on quantified rules, the script assigns one regime:
ROTATING (Roadmap A default)
Price is staying inside monthly value and weekly ranges are normal.
This favors mean-reversion and value-to-value trades.
COMPRESSING (Wait)
Weekly ranges and volume are shrinking while price remains inside value.
This signals energy building, but no trade yet.
ESCAPING (Roadmap B on deck)
Weekly closes cluster near one edge of monthly value and show progress toward breaking out.
This sets up possible expansion trades, pending daily confirmation.
WAIT / NEUTRAL
Conditions do not clearly support rotation or expansion.
No bias is assumed.
4. Edge proximity and progress
The script also reports whether price is:
near monthly VAH,
near monthly VAL,
or not near an edge.
For escaping regimes, it checks that price is actually moving closer to the edge, not drifting sideways.
What you see on the chart
Optional background shading by regime (informational only)
Optional monthly and weekly level lines (display only)
A dashboard showing:
current weekly regime,
alternation status,
edge proximity,
weekly RangeRatio,
weekly VolumeRatio,
flip count,
freshness of weekly levels
Nothing on the chart triggers trades or alerts.
How you’re meant to use it
Run this after Group 1
Group 1 answers: Can I trade at all?
Group 2 answers: What type of trading makes sense?
Use the regime to choose a roadmap
ROTATING → value rotation logic (Roadmap A)
ESCAPING → watch for expansion logic (Roadmap B)
COMPRESSING → wait
NEUTRAL → skip unless exceptional
Only then drop to the daily chart
Daily execution rules apply only if the weekly regime allows them.
What this script deliberately does NOT do
No entries
No exits
No targets
No stop logic
No automatic level calculation
No intraday analysis
It does not tell you what to trade.
It tells you what kind of environment you’re in.
Auto-DCF and Margin of Safety SetupDescription
Overview This indicator provides a dual-layered approach to stock valuation by combining a Discounted Cash Flow (DCF) model with Technical Momentum filters. It is designed for investors who seek to align fundamental "Fair Value" with high-probability technical entry points.
How It Works The script automates the valuation process by fetching real-time financial data directly from TradingView’s database.
Fundamental Valuation (DCF):
FCF Projections: It retrieves Free Cash Flow (TTM) and Total Shares Outstanding to calculate FCF per share.
Growth & Discounting: It projects FCF forward for 10 years based on your "Expected Annual Growth Rate" and discounts those values back to the present using the "Discount Rate" (WACC).
Terminal Value: A terminal value is calculated using a exit multiple (P/FCF) at Year 10 to account for the company's value beyond the projection period.
Intrinsic Value: The sum of all discounted cash flows and the terminal value represents the Intrinsic (Fair) Value, plotted as gray circles.
Margin of Safety (MoS):
A "Buy Limit" line (green) is plotted at a user-defined percentage below the Intrinsic Value. This represents the "Margin of Safety" popularized by Benjamin Graham to account for errors in estimation.
Technical Filters (The "Buy Setup"):
A visual Buy Zone appears only when three conditions align:
Value: Price is trading below the Margin of Safety.
Momentum: The RSI is in "Oversold" territory (default < 35).
Price Action: The stock is in a "Deep Pullback" (defined as a 15% drop from its 50-bar high).
How to Use
Settings: You must adjust the Growth Rate and Discount Rate based on the specific company’s historical performance and risk profile.
Visuals: When a setup occurs, the script draws a green box, a technical Stop Loss (based on a buffer below the low), and a Tech Target (a 50% retracement of the recent drop).
Limitations: This script requires request.financial data. It is intended for Stocks only. If no financial data is available for a ticker (e.g., Crypto or Forex), an error label will appear.
Disclaimer This script is for educational purposes only and does not constitute financial advice. DCF models are highly sensitive to input variables; small changes in growth or discount rates can significantly alter the Fair Value.
Moonboys BTC Liquidation Heatmap═════════════════════════════════════════════════════════════
MoonBoys BTC LIQUIDATION HEATMAP
═════════════════════════════════════════════════════════════
Visualize high-probability liquidation zones across Bitcoin futures markets using multi-exchange data and algorithmic pivot detection.
═══ OVERVIEW ═══
This indicator tracks where leveraged positions cluster and highlights areas where cascading liquidations are likely to occur. By combining Open Interest data from major exchanges with volume-weighted pivot analysis, it shows you where the market's leverage is stacked before price gets there.
Perfect for:
• Anticipating volatility zones
• Identifying potential reversal areas
• Avoiding stop-hunt regions
• Confirming breakout/breakdown levels
═══ KEY FEATURES ═══
🎨 HEAT-MAPPED LIQUIDATION ZONES
└─ Green zones = Long liquidations (below price)
└─ Purple zones = Short liquidations (above price)
└─ Color intensity = Volume significance
⚡ SMART SIGNIFICANCE DETECTION
└─ Top 30% of levels automatically highlighted
└─ Lightning bolt icon (⚡) marks critical zones
└─ Enhanced with borders, brighter colors, and bold labels
└─ Weak levels stay subtle to reduce noise
📊 MULTI-EXCHANGE DATA
└─ Binance Futures Open Interest
└─ Bybit Futures Open Interest
└─ Coinbase Spot Volume
└─ Toggle exchanges individually
🕐 MULTI-TIMEFRAME COMPATIBLE
└─ Works on all timeframes: 1m to Monthly
└─ Auto-adjusts filters and aggregation per timeframe
└─ Consistent performance across different chart scales
🎯 CLEAN VISUAL DESIGN
└─ Labels positioned right of chart (off candles)
└─ Connector lines show which label belongs to which zone
└─ Hit levels fade automatically
└─ Only active zones are labeled
═══ HOW TO READ IT ═══
┌─────────────────────────────────────────────────────────┐
│ ZONE TYPE │ MEANING │
├─────────────────────────────────────────────────────────┤
│ 🟢 Green (below) │ Long liquidation cluster │
│ │ → Potential bounce/support zone │
├─────────────────────────────────────────────────────────┤
│ 🟣 Purple (above)│ Short liquidation cluster │
│ │ → Potential rejection/resistance │
├─────────────────────────────────────────────────────────┤
│ ⚡ With icon │ Top 30% most significant levels │
│ │ → Higher probability of reaction │
└─────────────────────────────────────────────────────────┘
═══ TRADING APPLICATIONS ═══
📈 TREND CONTINUATION
→ Price rejects from liquidation zone = trend strength
→ Watch for bounces at green zones in uptrends
→ Watch for rejections at purple zones in downtrends
🔄 REVERSAL SETUPS
→ Price diving into dense liquidation clusters
→ Heavy volume + liquidation zone = potential turning point
→ Combine with momentum divergence for confirmation
⚠️ RISK MANAGEMENT
→ Avoid entries near untouched significant levels
→ High probability of stop hunts and slippage
→ Wait for price to sweep and confirm before entry
🧩 CONFLUENCE TRADING
→ Layer with support/resistance
→ Combine with volume profile nodes
→ Use alongside order flow indicators
→ Validate with moving averages or trend tools
═══ SETTINGS GUIDE ═══
📡 DATA FEEDS
├─ Binance Futures OI: Toggle Binance data
├─ Bybit Futures OI: Toggle Bybit data
└─ Coinbase Spot Vol: Toggle Coinbase data
🔍 LIQUIDATION DETECTION
├─ Lookback Bars (100-2000): Historical scan range
├─ Pivot Width (1-20): Detection sensitivity
│ └─ Higher = fewer, stronger levels
├─ Target Leverage Tier: Distance from pivot
│ ├─ 25x-50x: 2-4% zones
│ ├─ 50x-100x: 0.8-2% zones (default)
│ └─ 100x+: 0.3-0.8% zones
├─ Min Activity Filter: Remove weak signals
└─ Extend Levels (0-200): Project zones forward
🎨 VISUAL OPTIONS
├─ Long/Short Colors: Customize zone colors
├─ Heat Contrast (0.1-3.0): Intensity scaling
├─ Significance Threshold (0.3-0.95): Top % to highlight
├─ Touched Transparency: Fade amount for hit levels
└─ Label Offset: Distance from chart edge
═══ HOW IT WORKS ═══
1. PIVOT IDENTIFICATION
Scans historical data for swing highs/lows using pivot detection
2. VOLUME AGGREGATION
Combines Open Interest + Volume at each pivot point
Creates weighted metric for liquidation probability
3. ZONE PROJECTION
Calculates liquidation bands based on selected leverage tier
Projects zones where stop losses are likely stacked
4. SIGNIFICANCE RANKING
Normalizes all levels against historical range
Top percentile gets enhanced visual treatment
5. REAL-TIME TRACKING
Monitors price interaction with each zone
Active zones extend forward | Hit zones fade and lock
Memory management removes outdated levels
═══ BEST PRACTICES ═══
✅ DO:
• Use on high-liquidity BTC pairs (BTCUSDT, BTCUSD)
• Combine with volume and order flow analysis
• Look for confluences with key technical levels
• Use higher timeframes for more reliable zones
• Adjust leverage tier based on market volatility
❌ DON'T:
• Trade liquidation zones blindly without confirmation
• Ignore broader market context and trend direction
• Overtrade every single level that appears
• Use as sole entry/exit criteria
• Forget proper position sizing and risk management
═══ TECHNICAL NOTES ═══
• Built with Pine Script v6
• Max 500 boxes, 100 labels for optimal performance
• Auto-scales for different timeframe data availability
• Uses request.security() for multi-exchange aggregation
• Dynamic memory management prevents chart lag
═══ DISCLAIMER ═══
This indicator visualizes potential liquidation zones based on historical volume and open interest data. It does NOT:
• Predict future price movements with certainty
• Guarantee reversals or continuations
• Provide buy/sell signals
• Replace proper risk management
Liquidation zones show where leverage is concentrated — not where price will definitely react. Always use this tool as part of a comprehensive trading strategy alongside technical analysis, risk management, and market context.
📚 EDUCATIONAL USE ONLY | NOT FINANCIAL ADVICE
═══ RESOURCES ═══
Pine Script Documentation
→ www.tradingview.com
Understanding Liquidations
→ academy.binance.com
Open Interest Data
→ www.coinglass.com
Leverage Trading Education
→ www.investopedia.com
═══════════════════════════════════════════════════════════
Built for the Bitcoin trading community 🚀
Because knowing where the leverage sits is half the battle 💎
═══════════════════════════════════════════════════════════
Adaptive Elliott Wave: Forecast + Dashboard (V.2)Title: Adaptive Elliott Wave: Forecast + Dashboard
Description:
Overview
The Adaptive Elliott Wave: Forecast + Dashboard is a technical analysis tool designed to visualize potential Elliott Wave structures using a dynamic, multi-factor approach. Unlike static wave scripts, this indicator adapts its projections based on real-time trend context (Weighted Moving Averages) and momentum shifts (RSI). It is built to help traders identify the most likely path—Impulse or Correction—based on current market conditions.
How It Works
The script uses a combination of pivot-point detection and trend filtering to project future wave paths.
Pivot Logic: The indicator identifies significant Highs and Lows using a sensitivity setting. These pivots form the "anchors" for the Elliott Wave count.
Adaptive Engine: The "Auto-Detect" mode analyzes the relationship between the 50/200 WMA (Trend) and RSI (Momentum).
In a Bull Trend: If RSI is oversold, the script anticipates a bullish "Impulse" wave. If RSI is overbought, it prepares for a "Correction."
In a Bear Trend: The logic reverses to project rallies or downward impulses.
Projections: It calculates Fibonacci-based targets for waves 1-5 (Impulse) or A-B-C/W-X-Y (Correction) and renders them as "ghost lines" that move with the price.
Macro Outlook: For long-term context, the script includes a Macro Projection feature that uses higher-period pivots to show the possible 1-year direction.
Key Features
Target Table: A real-time dashboard showing exact Fibonacci target prices and the percentage distance from the current price.
Corrective Channels: Automatically draws channels for wave corrections to help identify potential breakout or breakdown zones.
Bullish/Bearish Extensions: Shows immediate volatility-based extensions beyond the last confirmed pivot.
RSI Signals: Visual markers on the chart indicate overbought/oversold conditions that feed into the adaptive logic.
How to Use
Identify the Phase: Use the "AI STATUS" in the dashboard to see if the script is currently projecting an Impulse (Trend move) or a Correction (Counter-trend).
Confirm with WMA: Use the 50 (Blue) and 200 (Orange) WMAs to confirm the macro trend before following a projection.
Monitor Fib Targets: Watch for price reactions at the projected labels. If price breaks a target significantly, the wave count may need to be re-evaluated (re-pivot).
Customize Sensitivity: For scalping, lower the "Short-Term Sensitivity." For swing trading, increase it.
Disclaimer
This script is for educational purposes only. Elliott Wave Theory is subjective, and projections are mathematical estimates based on historical volatility. Past performance does not guarantee future results. Always use proper risk management.
Settings Guide
Forecast Mode: Choose between "Auto-Detect" (Dynamic) or manually force an Impulse/Correction count.
Macro Sensitivity: Controls how far back the script looks to generate the purple 1-year projection.
Link Correction to Extension: A unique feature that starts the forecast from a potential extension target rather than the current live price.
Elliott Wave: Pro Forecast + Dashboard (with RSI Divergence)Elliott Wave: Pro Forecast + Dashboard (with RSI Divergence)
This indicator provides a dynamic, real-time projection of Elliott Wave structures, helping traders identify potential trend exhaustion and reversal targets. By combining historical pivot analysis with Fibonacci extensions, it forecasts both short-term "extensions" and long-term "macro" moves.
🚀 Key Features
Automated Elliott Wave Projections: Automatically plots potential 5-wave impulse moves (bullish) and 3-wave corrective moves (ABC - bearish) based on current market volatility.
RSI Divergence Integration (⚡): The script scans for discrepancies between price and momentum. If a reversal is projected while a Bullish or Bearish divergence exists, a lightning bolt icon appears, signaling a high-probability setup.
Dual-Horizon Forecasting:
Short-Term Extension: Projects the immediate continuation of the current trend.
1-Year Macro Projection: A "Big Picture" mode that uses high-sensitivity pivots to forecast long-term structural shifts.
Dynamic Data Dashboard: An on-chart table calculates exact Fibonacci price targets and the percentage distance from the current price, allowing for precise risk/reward planning.
Invalidation Logic: Clearly marks the "Invalidation Line." If price breaches this level, the current wave count is considered void.
🛠️ How to Read the Chart
Historical Waves (Green/Teal): Shows the confirmed pivots that the script is using as a baseline.
Extensions (Orange): The immediate predicted path if the current momentum continues.
Reversals (Blue): The projected Elliott Wave path if the current pivot holds.
Look for the ⚡ symbol near the Invalidation line; this indicates RSI Divergence, suggesting the reversal has strong momentum backing it.
Macro Projection (Purple): Designed for swing traders and investors to see where the asset could be in a year based on larger cycle pivots.
⚙️ Settings & Customization
Sensitivity: Adjust the "Short-Term" and "Macro" sensitivity to filter out market noise or capture smaller intraday cycles.
Scenario Linking: You can choose to have the Reversal projection start after the Extension target is hit, or have them run independently.
Visual Toggles: Enable/Disable the target table, Fibonacci grid levels, and chart labels to keep your workspace clean.
Disclaimer: This indicator is a mathematical projection based on historical volatility and Elliott Wave rules. It is a tool for technical analysis and does not guarantee future results. Always use proper stop-loss management.






















