Indicator

Indicator

AG Pro Daily Open Acceptance Map [AGPro Series]AG PRO DAILY OPEN ACCEPTANCE MAP
OVERVIEW
AG Pro Daily Open Acceptance Map is an intraday overlay built to track how price behaves around the current daily open and to present that behavior in a clean, rules-based structure. Instead of treating the daily open as a passive reference line, this script evaluates whether price is being accepted above it, accepted below it, or repeatedly failing around it.
The core design goal is clarity. Many traders use the daily open as a contextual anchor, but in practice it is often shown as only a simple line with no structured interpretation. This script is designed to go one step further by turning that level into a mapped decision framework. The result is a chart that helps users read whether the market is holding one side of the daily open with acceptance, drifting into indecision, or failing to maintain directional control.
This tool is intentionally narrow in scope. It is not built as a full market structure engine, a session model, a prior high/low dashboard, a VWAP tool, or a moving average framework. Its role is much more specific: to organize the behavior of price around the daily open and to express that behavior through a compact state model, visual reference lines, and confirmed state transitions.
Because the daily open resets every trading day, the script also produces a recurring intraday reference that can be reused across many symbols and market conditions. This makes it useful for users who prefer repeatable visual anchors instead of highly discretionary chart interpretation.
WHAT IT DOES
This script identifies the current daily open and treats it as the primary intraday reference level. From there, it evaluates whether price is holding above the level, holding below the level, or still testing the area without confirmation. It also tracks the first reclaim event when enabled, allowing users to see whether the market has recovered one side of the level after losing it earlier in the day.
The overlay is structured so the current daily open remains the main visual anchor, while the previous daily open can be shown as a lighter secondary context level. Acceptance areas and state mapping are kept as supporting elements rather than replacing the open itself. This keeps the chart readable while still preserving a visual record of how the market behaved around the level throughout the session.
In practical terms, the script helps answer a simple but important question: is price truly holding one side of the daily open, or is it only rotating around it without meaningful acceptance?
HOW THIS DIFFERS FROM OTHER AG PRO TOOLS
This script is intentionally separated from the logic families used in other AG Pro tools.
It does not rely on VWAP behavior.
It does not build decisions from EMA or moving average relationships.
It does not classify price by prior day or prior week high/low structures.
It does not depend on sweep, stop hunt, liquidity trap, or session-kill-zone logic.
It does not function as a structure label, breakout, or order-flow style engine.
The purpose here is much more focused. AG Pro Daily Open Acceptance Map is a daily-open behavior tool. Its main question is not whether a breakout happened, whether liquidity was taken, or whether a trend indicator flipped. Its main question is whether the market is accepting or rejecting one side of the current daily open.
That narrow positioning is deliberate. It helps keep the chart logic cleaner, the visual language simpler, and the use case easier to understand.
UNIQUE EDGE
The unique edge of this script is not the presence of a daily open line by itself. Many tools can plot a daily open. The distinctive part of this indicator is the state framework built around that line.
Instead of only drawing the level, the script evaluates market behavior around it and converts that into a practical overlay language. The chart can therefore communicate whether the market is in bullish acceptance, bearish acceptance, or unresolved testing, rather than forcing the user to interpret every interaction manually.
The script also separates the current daily open from the previous daily open in a clear visual hierarchy. The current open is treated as the primary live anchor, while the previous open is optional secondary context. This helps users compare the active intraday reference against the prior session without turning the chart into a multi-level dashboard.
Another advantage is that the visual model remains compact. The script is designed to offer information density without becoming visually noisy, which is especially important on publish screenshots and on charts where traders prefer a clean price-first layout.
METHODOLOGY
The script starts by identifying the current daily open and, when enabled, the previous daily open. The current daily open becomes the main reference for all live state calculations.
From there, the script measures whether price is sustaining closes above the level, sustaining closes below the level, or remaining in a testing state around the level. The filter mode can be adjusted to make the interpretation more responsive or more selective. In more permissive settings, state shifts can appear earlier. In stricter settings, price generally needs cleaner confirmation before a state is recognized.
When reclaim logic is enabled, the script also monitors whether one side of the daily open is recovered after being lost earlier in the day. This is not treated as a separate prediction model. It is simply an additional contextual event that can help users understand whether the market is recovering control around the open after temporary failure.
The acceptance area, open zone, and state ribbon are visual support layers. They are not intended to replace price or overwhelm the chart. Their purpose is to make the interpretation easier to read while keeping the current daily open as the main anchor.
SIGNALS AND ALERTS
The script supports confirmed-bar style logic so that state changes can be tracked in a more stable way. Depending on the enabled settings, users can monitor:
Bullish acceptance conditions
Bearish acceptance conditions
Testing or unresolved behavior around the daily open
First reclaim context when enabled
General state transitions when the market changes side or loses control
These alerts and visual states are intended for chart organization and condition awareness. They should not be interpreted as guaranteed trade outcomes, guaranteed continuation signals, or automated execution instructions.
KEY INPUTS
FILTER MODE
Users can switch between stricter and more responsive behavior depending on how selective they want the state model to be.
HOLD / CONFIRMATION SETTINGS
These controls affect how much sustained price behavior is required before the script recognizes an accepted state.
TOLERANCE AND OPEN ZONE SETTINGS
These help define how tightly or loosely the script interprets price behavior around the daily open area.
FIRST RECLAIM SETTINGS
These controls determine whether reclaim events are tracked as part of the daily open behavior model.
DISPLAY SETTINGS
Users can control whether the current daily open, previous daily open, acceptance area, ribbon, labels, and panel elements are shown.
VISUAL SIZE SETTINGS
Panel and label sizing can be adjusted depending on symbol volatility, screen resolution, and chart density preferences.
LIMITATIONS AND TRANSPARENCY
This script is not a forecasting engine. It does not predict where price must go next. It evaluates how price is behaving relative to the current daily open and displays that information in a structured way.
It is also not a substitute for complete market analysis. It does not include broader trend context, liquidity analysis, volume profile logic, macro structure interpretation, news impact, or instrument-specific catalysts unless the user applies those separately.
Different symbols and timeframes can also produce different daily open behavior. In some instruments the daily open may act as a very strong intraday reference, while in others price may rotate around it more loosely. Because of that, the script should be interpreted as a contextual decision aid rather than a universal standalone solution.
The previous daily open is included only as optional secondary context. It does not drive the main state model. The main live logic is built around the current daily open.
RISK DISCLOSURE
This script is provided for market analysis, chart organization, and educational use. It does not provide financial advice, investment advice, or guaranteed trade signals. No indicator can remove market risk, and no visual state model can ensure a profitable result.
Traders should use their own judgment, position sizing rules, and risk management process before making any decision. This tool can help structure chart interpretation, but execution responsibility always remains with the user.
Indicator

Vigilant Asset Allocation (VAA)1. Where VAA comes from
The basic observation behind VAA is not new. Jegadeesh and Titman showed in 1993 that stocks with strong recent returns keep outperforming for roughly three to twelve months. That finding was initially confined to equities, but Asness, Moskowitz and Pedersen (2013) later confirmed that the same pattern holds across bonds, currencies and commodities. Momentum, it turns out, is not just a stock-picking anomaly. It works at the asset-class level too.
Moskowitz, Ooi and Pedersen (2012) took this one step further. They looked at time-series momentum rather than cross-sectional momentum. The distinction matters: cross-sectional momentum asks "which asset is doing best?", while time-series momentum asks "is this asset going up at all?". VAA uses both questions, but the time-series version is what drives the breadth filter.
Faber (2007) probably deserves credit for bringing momentum into mainstream tactical allocation. His rule was simple: hold an asset when it trades above its ten-month average, sell when it drops below. Crude, but it cut drawdowns significantly. Antonacci (2014) refined this into dual momentum, combining trend direction with relative strength across two universes.
Keller and Keuning (2017) built on all of this but added something the earlier models lacked: a breadth dimension. Instead of looking at each asset independently, they count how many offensive assets carry positive momentum. If even one drops below zero (in the aggressive B=1 variant), the entire allocation goes defensive. The reasoning is straightforward. When breadth deteriorates, trouble is usually on the way. Waiting for every asset to turn negative is waiting too long.
In their original backtest (1970-2016, using Shiller extended data for the early period and ETF prices from inception), VAA-G4 produced roughly 17.7% annualised with a maximum drawdown of about 16.1% (Keller and Keuning, 2017, Table 2). These are in-sample numbers. They tell you what happened, not what will happen.
2. How the model works
2.1 Momentum scoring
Every asset gets a 13612W score, a weighted combination of four return lookbacks:
mom = 12 * r1 + 4 * r3 + 2 * r6 + r12
The r values are simple returns: r1 = close / close - 1, and so on for 63, 126 and 252 bars. The one-month return gets the heaviest weight (12), the twelve-month return the lightest (1). Recent momentum matters more, but the yearly anchor keeps the score from overreacting to short-term noise.
There is no normalisation. The raw score is used only for two things: ranking assets within each universe, and checking whether it is positive or negative for the breadth count.
2.2 The two universes
Keller and Keuning specified these defaults:
Offensive (growth):
- SPY (S&P 500)
- EFA (international developed)
- EEM (emerging markets)
- AGG (US aggregate bonds)
Defensive (preservation):
- LQD (investment-grade corporate bonds)
- IEF (7-10 year treasuries)
- SHY (1-3 year treasuries)
All seven are changeable in the settings. If you swap in other ETFs, make sure they have enough history.
2.3 The breadth rule
Each day the indicator counts how many offensive assets have positive momentum. Call the count of non-positive ones n_negative. The rule:
- n_negative >= B (default 1): go to the top defensive asset
- n_negative < B: go to the top offensive asset
With B=1, one single negative asset triggers the switch. That is aggressive in the sense of being quick to flee. Keller and Keuning argue this is the right trade-off. Breadth erosion tends to precede broader sell-offs, so early rotation is worth the occasional whipsaw.
2.4 Rebalancing
The paper prescribes monthly rebalancing. The indicator locks the allocation at the close of the last trading day of each month. Everything that happens between rebalances is monitoring only. The dashboard shows both the locked position ("held") and what the model would do today ("live").
Daily rebalancing is available as an option. It is not what the paper tested.
2.5 Ties
When two assets have the exact same momentum score, the one listed first wins. Sounds arbitrary because it is. But four overlapping return windows make exact ties rare in practice.
3. What you need
- TradingView, any plan (free works, Pro lifts the alert cap)
- A daily chart. The lookbacks assume daily bars. On weekly or intraday charts the periods are wrong and the dashboard flags it.
- 252 bars of history for every symbol. Until that is available, the model shows "warming up".
4. Setup and settings
4.1 Getting started
Add the indicator to any daily chart via the TradingView indicator search. It loads with the Keller/Keuning defaults. The status row at the bottom of the dashboard tells you when the model is ready.
4.2 Strategy
Breadth Threshold (B): 1 matches the paper. Raising it to 2 means two assets have to go negative before the model rotates. Fewer whipsaws, slower reaction.
Monthly Rebalancing: On by default. Off gives you daily updates, which is useful for experimentation but not what the literature tested.
4.3 Symbols
Offensive and defensive universes are fully configurable. If you replace an ETF, check that TradingView has daily data going back at least a year.
4.4 Visuals
Background Mode: "Position" tints the background green (offensive) or red (defensive). "Off" removes it.
Candle Colouring: Paints candles by breadth strength. Full green at 4/4 positive, full red at 0/4, faded tones in between. Transparency is adjustable.
Color Theme: Eight palettes. All of them work in both dark and light mode.
Glow Effect: Adds layered transparent lines behind the main plot. Useful if the signal gets lost in a busy chart. Off by default.
4.5 Dashboard
The table in the top right (moveable) shows:
- Regime: offensive or defensive, with the breadth count
- Allocate: which specific ETF to hold (100% always)
- Live: intra-month reading (only visible in monthly mode)
- Individual asset rows: 13612W scores and a trend arrow (up, down, or flat compared to 5 bars ago)
- Status: "active", "warming up", or "wrong timeframe"
4.6 Alerts
Five conditions, all behind a master switch:
- Regime switches to offensive at month-end
- Regime switches to defensive at month-end
- Held asset changed (same regime, different pick)
- Live breadth dropped between rebalances
- Live breadth recovered between rebalances
The live alerts are early warnings, not trade signals. They tell you the next rebalance might produce a change.
5. Reading the chart
The step line maps the breadth count to a 0-10 scale:
| Breadth | Value | What it means |
| 4/4 positive | 0.0 | Everything trending up |
| 3/4 positive | 2.5 | One weak link, still offensive with B=1 |
| 2/4 positive | 5.0 | Defensive if B is 2 or below |
| 1/4 positive | 7.5 | Broad weakness |
| 0/4 positive | 10.0 | Nothing working |
The threshold line sits at B * 2.5. Above it means defensive. The zone fill below the threshold marks the offensive region.
One thing to keep in mind: the distances between these steps do not mean anything quantitative. 5.0 is not "twice as bad" as 2.5. It is an ordinal display, not a risk score.
6. How to actually use it
The simplest workflow: check the dashboard on the last trading day of the month. Look at the "Allocate" row. Buy that ETF at the open of the next session. Done until next month.
If you want a heads-up, turn on the live alerts. A "breadth dropped" alert mid-month tells you the next rebalance might flip regimes. That gives you time to plan, not to act early. The month-end values are what count.
VAA does not know about your taxes, your broker fees, or your risk tolerance. Treat it as one input to your decision process, not the whole process.
7. What the model does not do
It does not model execution. There is no bid-ask spread, no slippage, no market impact.
It cannot protect you from whipsaws. Momentum systems by nature struggle in choppy, directionless markets. The breadth filter helps, but a month where sentiment flips back and forth will still produce unnecessary trades.
Monthly rebalancing is both a feature and a weakness. It keeps you from overtrading, but it also means a crash in the middle of a month does not trigger any action until month-end.
The backtests in the paper used extended data that goes back to 1970. The actual ETFs (EEM, AGG) only started trading in 2003. TradingView data will not replicate the full historical period.
The model is always invested. There is no cash option. You are either in the top offensive or the top defensive ETF.
Momentum can stop working. Correlations change. What the academic literature documents as a persistent anomaly can go through multi-year stretches of underperformance. The 2009 recovery, for instance, was fast enough to catch most trend-following systems off-guard.
8. Common questions
Why does it say "warming up"?
The model needs 252 daily bars per symbol. Loading the indicator on a chart without enough history means it cannot compute the twelve-month return component.
Can I run this on a 4-hour chart?
You can, but 21 bars on a 4-hour chart is not a month. The lookbacks will be wrong. The dashboard will flag this.
I changed the symbols and the readings look off.
Make sure the replacement ETFs actually have a year of daily data on TradingView. Some regional ETFs or newer funds do not.
The live reading disagrees with the held position.
That is expected in monthly mode. The held position only updates at month-end. The live reading shows what would happen if you rebalanced today. They diverge by design.
Should I trade every time the live reading changes?
No. Unless you deliberately turned off monthly rebalancing, the live reading is for awareness, not for execution.
References
Antonacci, G. (2014) Dual Momentum Investing: An Innovative Strategy for Higher Returns with Lower Risk. New York: McGraw-Hill.
Asness, C.S., Moskowitz, T.J. and Pedersen, L.H. (2013) 'Value and Momentum Everywhere', The Journal of Finance, 68(3), pp. 929-985. doi:10.1111/jofi.12021.
Faber, M.T. (2007) 'A Quantitative Approach to Tactical Asset Allocation', The Journal of Wealth Management, 9(4), pp. 69-79.
Jegadeesh, N. and Titman, S. (1993) 'Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency', The Journal of Finance, 48(1), pp. 65-91. doi:10.1111/j.1540-6261.1993.tb04702.x.
Keller, W. and Keuning, J.W. (2017) 'Breadth Momentum and Vigilant Asset Allocation (VAA): Winning More by Losing Less', SSRN Electronic Journal. doi:10.2139/ssrn.3002624.
Moskowitz, T.J., Ooi, Y.H. and Pedersen, L.H. (2012) 'Time series momentum', Journal of Financial Economics, 104(2), pp. 228-250. doi:10.1016/j.jfineco.2011.11.003.
Indicator

Indicator

Indicator

Index Futures Position Size CalculatorA simple, free position size calculator for CME index futures.
Click Entry, click Stop Loss, pick your asset, get your contract size. That's it.
═══════════════════════════════════
✦ SUPPORTED INSTRUMENTS
MNQ • MES • NQ • ES — all CME tick values hardcoded.
═══════════════════════════════════
✦ FEATURES
→ One-click Entry & Stop Loss directly on chart
→ Auto 1-handle SL buffer (protects against wick hunts)
→ Asset dropdown — no manual tick value entry
→ Custom rounding (≥0.75 rounds up, else down)
→ Green Entry / Red SL lines with price labels
→ Clean black-on-white size panel, top right
═══════════════════════════════════
✦ HOW TO USE
Add to chart → click Entry → click Stop Loss
Settings → pick asset, enter Account Size & Risk %
Read your size from the top-right panel
═══════════════════════════════════
✦ TIP
If you're trading a funded challenge, here are two clean ways to use this tool with your max loss limit:
Method 1 — Loss budget split
Decide how many consecutive losses you can take before you're out. Divide your max loss by that number, and use the result as your "Account Size" with Risk % at 100.
Example: $2,000 max loss ÷ 5 losses = $400 per trade
→ Account Size: $400 | Risk %: 100
Method 2 — Direct percentage
Enter your full max loss as Account Size and set Risk % to your per-trade percentage.
Example: $2,000 max loss, risking 20% per trade
→ Account Size: $2,000 | Risk %: 20
Both give the same result — pick whichever feels more natural.
═══════════════════════════════════
✦ A NOTE FROM THE AUTHOR
Built with Claude AI for my own daily trading. Sharing it free because clean tools shouldn't be locked behind paywalls.
100% free. 100% open source. No Discord, no course, no affiliate links, nothing to buy. Copy it, modify it, republish your own version — it's yours.
═══════════════════════════════════
✦ DISCLAIMER
Educational tool only. Not financial advice. Futures trading carries substantial risk of loss. Always verify calculations against your broker's parameters before trading.
Built with ❤️ by REDz & Claude Indicator

Sovereign Trade Setup [Pro]Sovereign Trade Setup 👑
Stop manually calculating risk. Stop drawing messy lines. And most importantly—stop staring at the chart waiting for your levels to hit.
The Sovereign Trade Setup is a premium, fully interactive visual trade manager designed to bridge the gap between trade ideation and flawless execution. Built with modern UI/UX principles, this indicator allows you to map out your entire trade directly on the chart using point-and-click mechanics, dynamically calculates your exact position size, and acts as an automated sentinel that alerts you the exact second your parameters are breached.
🌟 Key Features
Interactive Point & Click Setup: No more typing numbers into settings menus. When you add the indicator, simply click the chart to anchor your Start Time, Entry Zone (High/Low), Stop Loss, and Take Profit targets. Hold Ctrl / Cmd (or use Magnet Mode) to snap directly to candle highs and lows!
Auto-Direction Detection: Whether you are planning a Long breakout or a Short breakdown, the script instantly calculates the math. It compares your Entry to your Stop Loss and flips all logic and visual colors automatically.
Dynamic Risk & Position Sizing Calculator: Input your total Account Balance and Risk Percentage (%). The indicator instantly calculates your maximum dollar risk and tells you exactly how many units/shares you need to buy to mathematically protect your capital.
Pro-Grade Visuals & HUD: Features a sleek, translucent heads-up display (HUD) that tracks your real-time Risk-to-Reward (R:R) ratios and the exact status of your trade (Pending, Filled, Hit, or Stopped). Visuals can be fully customized or toggled off to keep your chart clean.
🚨 The Crown Jewel: State-Based "Set & Forget" Alerts 🚨
Trading should be about executing a plan, not babysitting a 1-minute candle. This indicator features a highly advanced, sequential alert system designed to prevent notification spam and only notify you when it matters.
How the Alert Engine Works:
The script remembers the "state" of your trade. It will only alert you to a Take Profit or Stop Loss if your Entry Zone has actually been filled first. Furthermore, if you get stopped out, it completely disables the Take Profit alerts so you don't get false positives later in the week.
You can configure 4 distinct, single-fire alerts:
🟢 Entry Hit: Price has officially dropped into your setup zone.
🔴 Stop Loss Hit: Your invalidation level was breached. Trade over.
🎯 Take Profit 1 Hit: First target reached. Time to scale out or move stops.
🚀 Take Profit 2 Hit: Final target reached.
How to set it up:
Once your levels are drawn on the chart, click the Alert icon (the clock) in TradingView. Select "Sovereign Trade Setup " as the condition, choose "Any alert() function call", and let the indicator do the heavy lifting. Go live your life, and let your phone notify you when it's time to act!
📖 How to Use
Add to Chart: Apply the indicator to your chart.
Point & Click: TradingView will prompt you to click the chart 6 times.
Click 1: Set the Start Time (click the specific candle where your setup begins so the script ignores historical data).
Clicks 2-6: Set your Entry Zone boundaries, Stop Loss, and Take Profit levels.
Fine-Tune: Open the indicator settings (⚙️) to micro-adjust your exact price levels to the penny, input your account balance, or customize your colors.
Set Your Alerts: Create an alert using the "Any alert() function call" condition.
Walk Away: Let the Sovereign Trade Setup watch the market for you. Indicator

Backtest Template [Backtest Terminal]Overview — What Is This Script?
Backtest Template (BTT) is an open-source strategy framework designed to let traders test their own indicator logic without building the backtest infrastructure from scratch. Instead of writing stop loss management, session filters, alert systems, and trailing stops yourself, BTT handles all of that automatically. You bring your signal idea — BTT handles the rest.
The template is designed for all markets: stocks, Forex, gold (XAUUSD), crypto spot, and crypto futures. It ships with a pre-built Moving Average Cross trigger and Moving Average Trend filter as working examples that you replace with your own logic.
What Makes It Original
Most backtest templates on TradingView are fixed strategies that test one specific indicator. BTT introduces a User Zone architecture: a single clearly marked section near the top of the script where the user replaces one pre-built trigger and one pre-built filter with their own Pine Script code. The engine below reads four fixed variable names and runs automatically — the user never needs to touch strategy orders, stop management, session logic, or the alert system.
This design means a complete beginner can run their first backtest by changing fewer than ten lines of code, while an advanced user can plug in arrays, multi-timeframe calculations, or complex signal logic and the engine handles it identically.
What The Engine Handles Automatically
Once your signal is connected through the User Zone, the following run without any additional code:
Stop Loss and Take Profit — three unit modes: percentage of price, fixed points (Forex / CFD), or fixed dollar amount (crypto / stocks)
Stop Mode — Fixed (original level), Trailing (follows price), or Breakeven (moves to entry price)
Trailing Stop — configurable distance and activation offset, each with matching %, point, and dollar unit inputs consistent with your Stop/Target Mode selection
Breakeven Stop — configurable activation offset in the same unit system
Disable Take Profit — when using Trailing mode, an optional toggle removes the fixed TP so the trailing stop becomes the sole exit
Trade Direction — Long only, Short only, or Both
Backtest Date Range — start and end date inputs
Trading Day Filter — enable or disable any day of the week
Trade Session Hours — exchange server time filter (HHMM-HHMM format)
Trade Windows — four configurable local-time windows each independently set to Off, Blackout, or Trade Only mode with full timezone support
Entry Signal Markers — green and red triangles that only appear when all conditions pass, so chart visuals exactly match what the strategy trades
App Alerts — pre-formatted alert messages with ticker, direction, stop and target prices
Custom JSON Alerts — four separate input fields for webhook bot integration, one per order event
How To Use It — Quick Start
Open the script in Pine Editor
Find the User Zone near the top — it is clearly marked with a visual border and is the only section you need to edit
Replace the pre-built Moving Average Cross trigger block with your own indicator signal, assigning your long condition to userLong and your short condition to userShort — always add and confirmed to both
Replace the pre-built Moving Average Trend filter block with your own market condition, assigning to userFilterLong and userFilterShort
Add to chart and open Strategy Tester
User Zone Contract
The engine connects to your signal through exactly four variables. Do not rename them:
userLong → true on the bar you want to enter Long
userShort → true on the bar you want to enter Short
userFilterLong → true when Long entries are allowed
userFilterShort → true when Short entries are allowed
Always add and confirmed (barstate.isconfirmed) to userLong and userShort. This ensures the signal locks in only when the bar closes, preventing signals from changing value mid-bar.
Setting userFilterLong = true disables the Long filter entirely. Setting it to a condition like close > ta.ema(close, 200) means Long entries are only allowed when price is above that EMA. Long and Short filters are independent — you can filter one direction while leaving the other open.
Stop Loss and Take Profit — Three Unit Modes
The Stop/Target Mode setting controls how SL and TP distances are measured:
% (Percentage) — distance as a percentage of price. Suitable for stocks and crypto. Stop source can be the close price or the candle High/Low. Take profit is derived from stop distance × Risk:Reward ratio.
Point - Forex / CFD — distance in instrument ticks (syminfo.mintick). Suitable for XAUUSD, EURUSD, and other Forex/CFD instruments. Example: 100 points on EURUSD (mintick = 0.00001) = 1 pip.
Dollar - Crypto / Stock — fixed dollar distance from entry. Suitable for BTCUSD and US stocks.
All trailing and breakeven offset inputs follow the same three-unit system. Use the , , or input that matches your selected Stop/Target Mode. Using the wrong unit input will result in a mismatch between your intended stop distance and the actual calculation.
Stop Mode — Fixed, Trailing, Breakeven
Fixed — stop loss stays at the original level from entry until hit or TP is reached
Trailing — stop follows price at a configurable distance, locking in profit as price moves. The trailing activation offset controls how far price must move before trailing begins (shown as a yellow line on chart). Enable "Disable Take Profit" to let the trailing stop manage the entire exit without a fixed TP ceiling
Breakeven — stop moves to the exact entry price once price moves a configurable distance in your favour (shown as a white line on chart)
Trade Windows — Off, Blackout, Trade Only
Each of the four time windows (Tokyo, London, New York, Custom) has an independent mode selector:
Off — this window has no effect on entries (default for all four)
Blackout — block all new entries while the current time is inside this window. Useful for avoiding high-volatility opens or news events
Trade Only — only allow new entries while the current time is inside this window. Useful for targeting specific sessions or news event windows such as NFP or Fed announcements
All times are entered in your local timezone selected from the My Timezone dropdown. The engine converts to UTC internally.
Logic rules:
Multiple Blackout windows use AND NOT logic — entries are blocked if the current time is inside any Blackout window
Multiple Trade Only windows use OR logic — entries are allowed when the current time is inside any one Trade Only window
If no windows are set to Trade Only, there is no time restriction on entries (same as all Off)
Blackout and Trade Only can be combined: for example, set London to Trade Only and New York to Blackout to only trade the London session while avoiding NY volatility
Trading Day and Session
Trading Days — enable or disable any individual day of the week. Disabling a day prevents new entries — open positions are still managed on disabled days.
Trade Session — set allowed hours in exchange server time (HHMM-HHMM format). Default 0000-0000 means 24 hours with no restriction. This uses exchange server time, not your local time.
Alert System — App Alert and Custom JSON
How to activate alerts:
Set the alert mode to App Alert or Custom in the settings panel
Create a TradingView alert on the chart (right-click → Add Alert)
In the alert message box, paste exactly: {{strategy.order.alert_message}}
This placeholder delivers the correct message for each order event automatically
App Alert mode sends a pre-formatted text message for each event:
ENTRY LONG : {price}
STOP LOSS : {stop level}
TARGET PRICE : {target level}
Exit alerts include a PNL percentage. No additional setup is required.
Custom mode — JSON webhook for bot integration:
Four separate input fields accept a single-line JSON string — one per order event:
Long Entry — fires when a Long position opens
Long Exit — fires when a Long position closes (TP, SL, or trailing stop)
Short Entry — fires when a Short position opens
Short Entry — fires when a Short position opens
Short Exit — fires when a Short position closes (TP, SL, or trailing stop)
Paste your JSON as a single line into each field. TradingView's input.string stores the content as a single line regardless of how it was formatted, making it safe for all webhook receivers.
Settings Guide — Commission, Slippage, Margin
Default values are conservative starting points. Edit the strategy() declaration at the top of the script to match your broker and market. Detailed inline comments in the script explain every parameter.
Commission defaults (0.1% per side, 2 ticks slippage):
Stocks zero-commission broker → 0.0%
Stocks SET Thailand → 0.16%
Crypto spot (Binance) → 0.1%
Crypto futures (Binance taker) → 0.04%
XAUUSD $7 per standard lot → change commission_type to strategy.commission.cash_per_contract and commission_value to 0.07 ($7 ÷ 100 oz)
Position sizing (default 2% of equity):
For lot-based markets (Forex, XAUUSD) change default_qty_type to strategy.fixed and default_qty_value to the number of units. On XAUUSD: 1 unit = 1 oz, so 0.01 lot = value of 1, 0.10 lot = value of 10, 1.00 lot = value of 100.
Margin/leverage simulation:
Both margin_long and margin_short are 0 by default (no margin simulation). Formula: margin value = 100 / leverage ratio. Example: 1:500 leverage → margin_long = 0.2. These values cannot be set from the input panel — edit them directly in the strategy() call.
Repainting Warning
Before connecting any indicator to the User Zone, verify it does not repaint. A repainting indicator places signal arrows on past bars using data from future bars that did not exist at the time — backtest results will look excellent while live trading produces nothing like it.
How to check using Bar Replay:
Open the indicator on your chart and find a signal arrow in the past
Open Bar Replay and rewind to before that signal appeared
Step forward one bar at a time using Shift + →
Do not use the Play button (Shift + ↓) — bars move too fast to catch a disappearing arrow
If the arrow appears and stays permanently → safe to use. If the arrow appears then disappears or moves as you advance → repainting confirmed, do not use in a strategy.
How to check using Alert Log:
Enable the indicator's built-in alert, wait for it to fire on a live bar, then compare the alert log entry to the signal arrow on the chart. If they do not match in timing or direction → repainting.
Disclaimer
This script is published for educational purposes only. It is a framework and template — not a complete trading system and not financial advice. Backtest results shown in Strategy Tester reflect historical data only and do not guarantee future performance. Past performance is not indicative of future results.
All trading involves significant risk of loss. Do not trade with money you cannot afford to lose. The results produced by this template depend entirely on the signal logic the user provides — the author accepts no responsibility for any trading decisions made using this script or any modifications of it.
Before using any strategy in live trading, you should fully understand how it works, verify its logic independently, and test it thoroughly on a demo account. Always consult a qualified financial advisor before making investment decisions.
The pre-built Moving Average Cross trigger and Moving Average Trend filter included in the User Zone are provided as examples only — they are not recommendations to trade any specific method. Strategy

Indicator

Indicator

Zen YCT - Liquidity MonitorThe "Zen YCT - Liquidity Monitor," is a sophisticated macro-overlay designed to track global liquidity stress by monitoring the Yen Carry Trade (YCT) and bond yield differentials. It translates complex intermarket relationships into a simple "Traffic Light" dashboard on your TradingView chart.
Core Concept - The indicator operates on the premise that global liquidity is often driven by the yield spread between US and Japanese government bonds. When these spreads compress rapidly (Z-score drops) or the USD/JPY pair breaks down, it signals a potential unwinding of the carry trade, which historically leads to volatility in equities (like the QQQ).
Key Features & Mechanics
1. Intermarket Data Integration - The script pulls data from several key asset classes to build a "Stress Profile":
-Yield Spreads: Monitors the gap between US and Japanese 2-Year and 5-Year yields.
-Currency Momentum: Tracks the Rate of Change (ROC) for USD/JPY on a 4-hour timeframe.
-Volatility: Monitors VIX acceleration to confirm if market fear is rising alongside liquidity shifts.
2. Statistical "Stress" Logic (Z-Scores)
Rather than looking at raw prices, the script calculates a Daily Z-Score for the spreads and the VIX. This measures how many standard deviations the current value is from its mean over a specific lookback period (default 20 days).
-A negative Z-score in the yield spreads suggests the "carry" is becoming less attractive or a squeeze is occurring.
-A positive Z-score in the VIX indicates an abnormal spike in fear.
3. The "Traffic Light" Status System
🟢 Liquidity Stable - Normal historical range
🟡 Stress Rising - 2y/5Y spreads not favorable
🔴 Liquidity Crunch Spreads
Dashboard Elements
The script renders a clean, customizable table (default: Top Right) displaying:
-Zen YCT Header: Shows the emoji status (🟢/🟡/🔴) for at-a-glance monitoring.
-2Y / 5Y Stress: The real-time Z-scores of the US-Japan bond spreads.
-Stress Delta: The difference between the 2Y and 5Y stress levels.
-VIX Accel: The current sigma move of the VIX (e.g., "2.5σ").
Usage Tip
This is a Macro-Overlay, not a traditional buy/sell signal generator. Use it to determine "Market Regime." If the Zen YCT turns Red, it suggests that even if your technical setup looks good, the underlying plumbing of the market is broken, and the risk of a "Sigma Move" to the downside is significantly elevated. Indicator

AG Pro Trend Continuation Quality [AGPro Series]AG Pro Trend Continuation Quality
Overview / What it does
AG Pro Trend Continuation Quality is an overlay built to evaluate whether a pullback is behaving like a healthy retracement inside an active trend, or whether the move is losing structural quality before continuation can develop.
Instead of treating every dip in an uptrend or every pop in a downtrend as equally important, the script isolates pullback sequences and scores them through a continuation-quality framework. The goal is not to predict every next candle. The goal is to help traders judge whether the market is showing disciplined retracement behavior that often precedes trend continuation.
The model combines trend alignment, pullback depth, pullback duration, relative volume behavior during the retracement, and the strength of the bounce candle that attempts to resume the trend. These conditions are translated into a compact quality score so the user can quickly separate cleaner continuation structures from weaker ones.
On the chart, the script highlights pullback zones, tracks the retracement box, displays a continuation-quality label, and maintains an information panel that summarizes trend state, recent quality readings, best quality, average quality, and internal distribution data. The result is a workflow-oriented continuation map rather than a simple trend-following overlay.
Unique Edge
The distinctive part of this script is that it does not label trend continuation from trend direction alone. A bullish EMA stack or bearish EMA stack is not enough by itself. The script specifically evaluates the quality of the retracement before the continuation attempt is scored.
That makes it meaningfully different from basic EMA trend tools, pullback highlighters, or single-condition continuation signals. Many tools can say that price is above or below an average. Fewer tools attempt to measure whether the internal anatomy of the pullback remains constructive for continuation.
The scoring engine focuses on five practical questions:
1. Is the broader trend aligned?
2. Is the pullback still structurally controlled rather than excessively deep?
3. Did the retracement last a reasonable number of bars?
4. Did volume contract during the pullback instead of expanding aggressively against trend?
5. Did the bounce show enough intent to suggest renewed directional participation?
This creates a cleaner framework for evaluating continuation setups in a way that is visual, systematic, and easier to compare across multiple pullbacks on the same chart.
Methodology
The script first determines directional context using EMA alignment and, when needed, swing-structure logic. This creates a working trend state that frames whether the script should be looking for bullish or bearish pullback behavior.
Once a directional leg is active, the script begins tracking a pullback when price retraces against that trend. During the retracement, it measures:
- how far the pullback travels relative to the prior trend leg,
- how many bars the pullback lasts,
- how pullback volume compares with the prior expansion leg,
- and whether the bounce candle shows convincing re-engagement.
These components are translated into a 0 to 10 quality score. Higher scores represent more orderly and structurally coherent pullbacks. Lower scores represent weaker or more suspect retracements.
The visual output is designed to make those evaluations easier to read in real time:
- pullback boxes frame the retracement zone,
- optional fib-depth line shows the deepest retracement point tracked inside the pullback,
- labels display score, quality grade, depth, duration, and relative volume,
- panel metrics summarize the current continuation environment.
Signals & Alerts
The script is designed as a quality-mapping tool, not as an automatic trade system.
Its event logic revolves around the completion of a pullback and the appearance of a bounce candle that attempts to resume the trend. When that bounce qualifies, the script calculates the final continuation-quality score and can display the setup if it meets the user-defined minimum score threshold.
Available workflow signals include:
- active bullish or bearish trend state,
- pullback in progress,
- completed pullback with scored continuation attempt,
- high-quality continuation events when the score reaches stronger thresholds.
Optional alerts can be used for:
- high-quality continuation conditions,
- or any scored pullback event, depending on user preference.
Because alerts are tied to the script’s scoring and confirmation logic, they are intended to support chart review and decision-making rather than act as guaranteed execution instructions.
Key Inputs
EMA Fast Length / EMA Mid Length / EMA Slow Length
These define the trend stack used to frame directional bias.
Swing Pivot Length
Controls the swing-structure sensitivity used in secondary trend detection.
Max Pullback Depth (%)
Defines how strict the script is when assessing whether a retracement remains healthy relative to the prior trend leg.
Min Pullback Bars / Max Pullback Bars
Controls the acceptable pullback duration window.
Volume Decline Ratio
Helps determine whether the retracement is occurring on lighter activity relative to the prior directional leg.
Minimum Score to Display
Filters weaker continuation events from the chart.
Label Size / Label Offset / Reduce Label Overlap
Lets the user adapt chart readability to their own zoom level and instrument volatility.
Panel Position / Panel Font Size / Panel Theme
Allows the continuation dashboard to be integrated into different chart layouts without dominating screen space.
Limitations & Transparency
This script does not know future market intent. It evaluates observable price and volume behavior after conditions form on the chart.
A high score does not guarantee continuation. It only indicates that the completed pullback meets the script’s internal definition of stronger continuation quality relative to other pullbacks.
The model is also sensitive to market regime. Trend continuation behavior tends to be clearer in directional markets and less reliable in highly compressed, erratic, or news-driven conditions.
Volume behavior can vary across instruments and data feeds. On some assets, especially where volume data is synthetic, limited, or structurally uneven, the volume component should be interpreted with caution.
Like other structure-based tools, this script can produce different practical usefulness depending on timeframe, instrument, volatility regime, and chart cleanliness. Users should calibrate inputs based on the market they are studying rather than treating defaults as universal settings.
This script should not be viewed as:
- a prediction engine,
- a standalone trade system,
- a replacement for risk management,
- or a guarantee that a bounce will develop into a full continuation leg.
Risk Disclosure
This script is for chart analysis and educational use. It is designed to help users study pullback quality inside established trends, not to provide financial, investment, or trading advice.
All trading and investing involve risk. Market conditions can change quickly, and even high-quality continuation structures can fail. Users should apply their own confirmation process, position sizing rules, and risk controls before acting on any market observation.
Use the script as a structured continuation framework, not as certainty.
Indicator

Indicator

Machine Learning Supertrend [Aslan]Hey everyone 👋, This is an indicator I've been working on for a long time. Its not really finished yet, but I think it has huge potential.
It uses a SuperTrend foundation layer with momentum filtering, volume confirmation, and, most importantly, an adaptive engine that continuously adjusts its own parameters based on recent performance. It fires entry arrows on the chart while running a background simulation to score how the current settings are performing — then quietly adjusts itself over time.
Two systems run in parallel: the signal engine that produces the arrows you see, and a background test matrix that opens and closes simulated trades to feed the optimizer. The optimizer adjusts parameters, which produces better signals, which feeds back into better learning.
The Core Concept
At its heart this is a SuperTrend indicator — a volatility band that flips bullish or bearish as price crosses it. Signals fire either when that flip occurs (Reversal mode) or when price pushes to a new extreme within the current trend (Breakout mode).
On top of this, three adaptive learning layers run continuously:
Global Optimizer — rolling window of recent trade results that proposes parameter changes based on win rate, Sortino ratio, and profit factor
Micro-Batch Processor — a faster layer that groups results into mini-batches for quicker adjustments
Regime Grid — a 2D memory map that remembers what settings worked under similar market conditions (trend strength × volatility) and biases proposals accordingly
The Most Important Settings — Start Here
Band Width (Group ②) — Default: 1.4
The single most impactful setting in the entire indicator. Controls how wide the SuperTrend bands are. Lower values (1.0–1.2) create tight bands that flip often, giving more signals but more noise. Higher values (2.0–3.0) only flip on large structural moves, giving fewer but stronger signals. If your chart feels too noisy, raise this first. Higher values result in more trend following signals, while lower ones result in more contrarian signals.
Lookback Window (Group ②) — Default: 30
How many bars back the indicator scans when detecting new highs and lows. Lower values (10–15) react to minor swings and fire frequently. Higher values (50–100) only react to large structural pivots. Tune this alongside Band Width — they work together.
Signal Type (Group ①) — Default: Reversal
Pick one and stick with it. Reversal catches turning points when a trend exhausts. Breakout rides momentum to new extremes.
Reactivity / Master Dial (Group ⑥) — Default: 10
Controls how aggressively the adaptive engine responds to new information. Value of 1 = very conservative, slow to adapt, stays close to your base inputs. Value of 20 = aggressive, adapts quickly and can drift far from base settings. Start at 10 and only raise it if the market you're trading changes character frequently.
Signal Spacing (Group ①) — Default: 10
Minimum bars between any two signals. Prevents clustered rapid-fire entries in choppy zones. Lower on fast timeframes (3–5 on 1-min), higher on daily charts (20–30).
Group-by-Group Reference
① Signal Mode
Signal Type — Reversal catches trend exhaustion flips. Breakout rides momentum to new extremes. Pick one.
Require Fresh Pivot — When on, a signal only fires if price made a genuine new high/low first. Off = more signals, more noise.
Signal Spacing — Minimum bars between signals. Tune per timeframe.
② Volatility Envelope
Lookback Window — Bars scanned for new highs/lows. Lower = more reactive, more signals.
Smoothing Period — ATR calculation period. Lower = faster reaction to volatility, more band flips.
Band Width — ATR multiplier for band width. The most impactful setting in the indicator. Lower = more signals, higher = fewer stronger signals.
Price Basis — Which price source feeds SuperTrend. hlcc4 (default) is smoothest, close is most reactive.
True Range Mode — On = RMA-smoothed ATR (standard). Off = EMA-smoothed, faster but noisier.
③ Momentum Filter
Active — Toggles RSI filtering. Off = more signals but no momentum confirmation.
Length — RSI period. Lower = more volatile RSI, filter triggers more easily.
Hot Zone Memory — How many bars back it checks whether RSI was overbought (for sell confirmation). Higher = more lenient.
Cold Zone Memory — Same concept for oversold / buy confirmation.
RSI Hot/Cold Levels (set in Group ⑬) — Overbought/oversold thresholds. Default 70/30. Wider = more signals, tighter = fewer.
④ Flow Analysis
Sample Depth — Bars averaged to define "normal" volume.
Surge Threshold — Volume must exceed this multiple of average to count as a surge (1.2 = 20% above average).
Require Surge — When on, signals only fire with volume confirmation. Dramatically reduces count but greatly improves quality. Worth enabling.
⑤ Signal Quality
Key Levels Only — Only signals at major structural turning points fire. Fewer signals — suited for swing traders.
Key Level Depth — ATRs the price range must span to qualify as a key level. Only matters when Key Levels Only is on.
⑥ Master Dial
Reactivity (1–20) — The meta-knob for the entire adaptive engine. Controls batch size, adaptation speed, deadband sensitivity, and EMA alpha simultaneously. If you only change one adaptive setting, change this.
Micro-Batch Processing — Enables the faster mini-batch learning layer. On = quicker adaptation.
Live Pressure Sensor — Tracks cumulative up/down-tick volume flow on live bars to bias the optimizer's step size. Only affects live charts.
⑦ Auto-Tune Engine
Enable Auto-Tune — Master switch. Off = fixed parameters forever, just a traditional indicator.
Use Background Test Matrix — Runs the 5×5 simulated trade grid. Must be on for any adaptation to occur.
Lock Envelope to Base — Forces plotted bands to use your original inputs visually even if internal parameters have drifted. The signal engine always uses adapted values regardless.
⑧ Optimizer
Most users don't need to touch these — the defaults work well.
Step Size — Base learning rate. Higher = faster but potentially overshooting adaptation.
History Depth — Rolling window of trades used to compute statistics. Higher = slower but more stable learning.
Win Ceiling / Floor — Win rate thresholds that trigger parameter tightening or loosening.
Momentum Smoothing — EMA blend factor for applying new proposals. Higher = faster-acting changes.
Update Cooldown — Minimum bars between parameter updates. Prevents rapid oscillation.
Deadband Width / Period — Proposed changes must exceed these thresholds before being applied. Filters micro-jitter.
Anchor Revert Interval / Strength — Every N bars, parameters drift back toward your base inputs. Safety mechanism against unbounded drift.
P&L Cap per Trade — Clips outlier trades at this USD value before learning from them. Prevents one giant win/loss from distorting statistics.
⑨ Risk Guard
Max Entries / Session — Stops new signals after this many trades in a day.
Session Loss Limit — Pauses trading if cumulative session P&L drops below this USD amount.
Base Pause After Loss — Bars to wait after a losing trade. Prevents revenge trading.
Streak Limit — Pauses after this many consecutive losses.
Scale Pause by Loss Size — Larger losses trigger proportionally longer pauses.
Enforce on Test Matrix — Applies risk rules to the background simulation too. Usually leave off so the matrix always has fresh data.
⑩ Context Memory (Regime Grid)
Enable Regime Grid — Activates the market-context memory system.
Regime / Volatility Bins — Resolution of the grid on each axis. More bins = finer resolution but slower confidence buildup per cell.
Neighbor Blend Radius — How much adjacent grid cells blend into each other. Higher = smoother but less precise.
Decay Half-Life — How quickly older data in a cell loses weight. Lower = faster forgetting.
Max Grid Influence — How much the regime grid can dominate the global optimizer. 0.65 = up to 65% grid contribution.
⑪ Decay Traces
Short-term fading trade memory that specifically monitors for large adverse moves to tighten stops.
Enable Trace Buffer — Activates short-term memory.
Fade Rate — Energy reduction per bar. Higher = only very recent outcomes matter.
Adverse Move Threshold — MAE in ATR units above which a trade is flagged as a tail event.
Guard Tighten Cap — Maximum stop tightening allowed from tail-event feedback.
⑫ State Snapshot
Restore String — Paste a previously exported snapshot here to reload learned parameters and grid cells across reloads.
Export Now — Toggle on to emit the current learned state as an alert string. Toggle off afterward.
Import on Next Bar — Applies the Restore String on the next confirmed bar.
Risk Management (TP/SL Overlay)
Show TP & SL — Toggles the visual overlay.
TP/SL for — Which signal type drives the levels — Contrarian, AI Supertrend, or Both.
TP 1/2/3 — Take-profit multipliers relative to the stop distance. Set any to 0 to disable that level.
Quick Tuning Guide
Too many noisy signals? Raise Band Width → raise Lookback Window → raise Signal Spacing → enable Require Surge → enable Key Levels Only.
Too few signals? Lower Band Width → lower Lookback Window → lower Signal Spacing → disable Require Surge → disable Key Levels Only → widen RSI Hot/Cold levels.
Want faster adaptation? Raise Reactivity toward 15–18 → lower History Depth → lower Decay Half-Life.
Want more stability? Lower Reactivity toward 3–5 → raise History Depth → raise Anchor Revert Interval.
Starting fresh on a new instrument? Let the indicator run for at least 50–100 bars before evaluating, then use Export Now to save the learned state so it survives a chart reload. Indicator

OTC Buy Signal: Name Change & SplitsOTC Buy Signal: Name Change & Splits
This script is a simple event-driven tool designed for traders who monitor OTC equities for corporate actions that may affect price behavior, sentiment, or speculative interest.
The main focus of the script is split activity, with specific logic for forward splits and reverse splits. It is intended to help visually identify situations where a stock may become relevant again after a qualifying event, while also filtering out symbols that have recently undergone reverse splits.
In many OTC names, corporate actions can matter just as much as technical structure.
This script tracks stock split data and applies a basic event filter:
• Forward splits can be treated as buy signals
• Reverse splits are treated as caution events
• A user-defined exclusion period blocks signals after a reverse split
The purpose is to reduce noise and avoid immediately qualifying symbols that may still be in a weaker post-reverse-split phase.
How It Works
The script requests split data directly from TradingView’s corporate actions feed and evaluates the split ratio:
• Ratio greater than 1.0 = forward split
• Ratio less than 1.0 = reverse split
When a reverse split is detected, the script stores the event time and begins an exclusion window based on the number of days selected in settings.
If forward split signals are enabled, a buy signal will only print when the symbol is outside that exclusion period.
Signal Logic
Buy Signal
• Triggered by a forward split event
• Only valid if the chart is outside the reverse split exclusion window
Reverse Split Warning
• Printed when a reverse split occurs
• Used as a visual warning and as the starting point for the exclusion timer
Exclusion Zone
• The chart background is shaded during the exclusion period after a reverse split
• This makes it easier to visually confirm when signals are being suppressed
Visual
• Buy markers below price for qualifying events
• Reverse split markers above price
• Background highlight during the exclusion window
• Alert conditions for both buy signals and reverse split warnings
Important Limitation
This script can detect split events through TradingView’s corporate action data, but it does not automatically detect historical name changes unless those changes are reflected through ticker or corporate action behavior.
Because of that, the script is best understood as a split-based OTC event tracker rather than a full name-change detection system.
Use Cases
This tool may be useful for:
• OTC traders screening for event-driven setups
• Monitoring forward split activity
• Avoiding recent reverse split names
• Building a broader OTC watchlist process
Notes
This is a specialized filter, not a full trading system.
It is best used alongside:
• Manual OTC research
• Corporate action review
• Chart structure and liquidity analysis
• Risk management
As always, event-based setups should be validated with additional context before acting on them. Indicator

Leverage Strategy Shell [by Oberlunar]Leverage Strategy Shell ★ by Oberlunar
A quantitative strategy shell that executes no logic of its own. It receives entry and exit signals from any external indicator through a standardised protocol, then sizes each position through a full risk engine, executes against TradingView's broker emulator, and produces a post-trade analytics suite that no native strategy tester can match. Think of it as a risk manager that sits between your signal generator and the market.
The core idea is the separation of concerns. Your indicator decides when to trade. This shell decides how much to trade, enforces margin constraints, tracks every position through intrabar LTF data, and decomposes your equity curve into R-multiple and time distributions so you can see exactly where your edge lives — and where it doesn't.
Signal Protocol
The shell reads three values from your indicator via input.source() . Your indicator must plot them with display=display.none so they don't clutter the chart.
// In your indicator:
signal = longCondition ? 1 : shortCondition ? -1 : exitLong ? 2 : exitShort ? -2 : 0
stopPx = longCondition ? yourStopPrice : shortCondition ? yourStopPrice : 0
tpPx = longCondition ? yourTPPrice : shortCondition ? yourTPPrice : 0
plot(signal, "Signal", display=display.none)
plot(stopPx, "Stop", display=display.none)
plot(tpPx, "TP", display=display.none)
Signal is the only mandatory source. It accepts five discrete values: +1 opens a long, -1 opens a short, +2 closes an open long, -2 closes an open short, and 0 means no action. The shell is edge-triggered — it fires only on the transition from one value to another, so holding +1 for multiple bars will not produce multiple entries.
Stop is optional. When your indicator provides a stop price, the shell uses it for the exit order and for computing the risk distance that drives position sizing. When the source reads zero or equals the bar's close, the shell falls back to its internal stop model (ATR × multiplier or percentage). This means any indicator, from a simple moving-average crossover to a complex volatility regime detector, can plug in and immediately inherit disciplined risk management.
TP is also optional. If provided, the shell places a limit exit at that price alongside the stop. If not, the position lives until a +2 or -2 signal closes it.
To connect: apply your signal indicator to the chart first, then apply the shell to the same chart. In the shell's settings, map each input.source() to the corresponding plot from your indicator. That is the entire integration. No code changes to your indicator beyond adding the three plot lines above.
Risk Engine
Position sizing is not a percentage of equity and not a fixed lot. It is derived from the actual risk per trade, defined as the monetary distance from entry to stop expressed in account currency.
The engine computes tick value as tickSize × pointValue , converts to account currency through request.currency_rate() , then calculates the cost of the stop being hit: stopTicks × tickValue × ccyRate . To this it adds a friction estimate (spread + entry slippage + exit slippage, all in ticks) and the round-trip commission cost. The budget available for the trade is capital × riskPercent / 100 . Raw quantity is budget / totalCostPerUnit , floored to the instrument's minimum contract step and capped by the margin constraint capital / (notionalPerUnit × marginPercent) . The final quantity is the smaller of the risk-sized and margin-capped values.
The commission model supports three modes. Per Order subtracts a fixed dollar amount per order from the risk budget before dividing by the per-unit cost — this is the simplest to configure and is the default. Per Contract scales linearly with quantity. Percent scales with notional value. In all three cases, the engine accounts for the full round-trip cost before committing capital.
The strategy declaration at the top of the script uses compile-time constants for initial_capital , commission_type , commission_value , slippage , and margin_long/short . These are the values TradingView's broker emulator actually uses during the backtest. The input panel exposes the same parameters for the dashboard and sizing engine. If the two diverge, a red DECL MISMATCH warning appears at the bottom of the table — edit the constants in the source (marked with ✏️) to match your inputs.
Trade Tracking
Once a position is filled, the shell begins monitoring it through lower-timeframe intrabar data via request.security_lower_tf() . For each open trade it checks, bar by bar, whether the price path has reached -1R, +1R, +2R, +3R, or +5R from the entry, using the stop distance frozen at signal time as the unit of R. It records whether each level was touched and how many minutes it took to get there.
Trade close detection uses strategy.closedtrades as an event counter, not strategy.position_size == 0 . This is critical for robustness: when the strategy reverses from long to short in a single bar, position_size never passes through zero, but closedtrades still increments. The entry price for R-multiple calculation comes from strategy.position_avg_price — the real fill, not the close of the signal bar.
The stop distance follows a three-stage chain. At signal time, stop and distance are frozen into pending variables. At fill time, when the position actually exists, they transfer into active tracking variables. At trade close, when closedtrades increments, the active stop distance is pushed into a closed-trade array that stays perfectly aligned with TradingView's internal trade index. This eliminates the fragile parallel-array problem that plagues most custom trade trackers.
Analytics Dashboard
The dashboard is a single unified table rendered on the last bar. It has three main blocks.
Left panel shows live strategy metrics computed from all closed trades: Profit Factor, Win Rate, Expectancy in account currency, average R-multiple at exit, average Win R and Loss R with trade counts, maximum drawdown, annualised Sortino ratio and Calmar ratio, and average trade duration. These are not approximations — they iterate over every strategy.closedtrades.profit(i) , entry_price(i) , exit_price(i) , and entry_time(i)/exit_time(i) on the final bar.
Right panel, upper block — R Distribution. Every closed trade is binned by its R-multiple at exit into eight buckets: below -1R, -1R to -0.5R, -0.5R to zero, zero to +0.5R, +0.5R to +1R, +1R to +2R, +2R to +3R, and above +3R. Each row shows the count of trades in that bin, the average P&L, the average duration, and the win percentage. The background colour shifts from red to green with the bin's average R. This is the distribution that tells you whether your strategy is a small-loss / big-win machine or something else entirely.
Right panel, lower block — Time Distribution. The same closed trades are binned by duration into six buckets: under 6 hours, 6–24 hours, 1–3 days, 3–7 days, 1–4 weeks, and over 4 weeks. Each row shows count, average R, average P&L, and win rate. This reveals the time structure of your edge. A well-functioning trend-following signal will show negative average R in the short buckets (quick stops) and strongly positive R in the long buckets (runners). If the pattern is flat or inverted, the signal has no time edge.
Below the distributions, a Trade R-Level HIT% row shows what fraction of completed trades touched each R-level during their lifetime, with the average time to reach it. This is a different question from exit R: a trade can touch +3R intrabar and then close at +1.5R. The HIT% row captures the maximum favourable excursion in R-space, which is useful for evaluating whether wider take-profit targets are viable.
A Multi-Risk Sizing table at the bottom shows what the position size, notional, margin, and risk dollar would be at seven different risk percentages from 0.25% to 10%, so you can instantly see the scaling profile of your current instrument without changing any input.
Setup checklist
Add three plot() lines to your indicator (Signal, Stop (optional), TP(optional)) following the protocol above.
Apply your indicator to the chart.
Apply this strategy shell to the same chart.
In the shell's settings, map the three input.source() fields to the corresponding plots from your indicator.
Set Account Capital, Leverage, Commission Type and Value to match your broker. Then edit the ✏️ constants at the top of the script to the same values — these are compile-time and cannot follow input changes.
Verify no DECL MISMATCH warning appears in the table.
Run the backtest. Read the R and Time distributions. Decide whether your signal has edge.
The strategy declaration uses process_orders_on_close=false and use_bar_magnifier=true by default. Orders fill on the next bar's open, which is realistic for market orders. Bar magnifier uses lower-timeframe data to improve fill simulation on higher timeframes. Both settings can be changed in the source if your workflow requires it.
The very simple tested strategy is the following:
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © Oberlunar ★
//@version=6
indicator("EMA Trend Signal ★ Oberlunar", overlay=true)
// ═══════════════════════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════════════════════
i_emaFast = input.int(19, "EMA Fast", minval=2, group="EMA")
i_emaMid = input.int(49, "EMA Mid", minval=2, group="EMA")
i_emaSlow = input.int(154, "EMA Slow", minval=2, group="EMA")
i_slopeBars = input.int(5, "Slope Lookback", minval=1, maxval=50, group="EMA", tooltip="Bars to measure EMA slope. Positive = ema now > ema N bars ago.")
i_atrMult = input.float(1.5,"Stop ATR Mult", minval=0.1, step=0.1, group="Stop & TP")
i_rrRatio = input.float(2.0,"R:R Ratio for TP", minval=0.5, step=0.5, group="Stop & TP", tooltip="0 = no TP, exit by signal only.")
i_showEMA = input.bool(true,"Show EMAs", group="Visual")
// ═══════════════════════════════════════════════════════════════════════════════
// EMAs + SLOPE
// ═══════════════════════════════════════════════════════════════════════════════
float ema21 = ta.ema(close, i_emaFast)
float ema50 = ta.ema(close, i_emaMid)
float ema200 = ta.ema(close, i_emaSlow)
float atr = ta.atr(14)
// Slope: positive if EMA21 is rising over N bars
float slope21 = ema21 - ema21
bool slopeUp = slope21 > 0
bool slopeDn = slope21 < 0
// ═══════════════════════════════════════════════════════════════════════════════
// ENTRY CONDITIONS
// ═══════════════════════════════════════════════════════════════════════════════
// ── LONG ─────────────────────────────────────────────────────────────────────
// Price crosses above EMA21
// EMA50 and EMA200 are BELOW (bullish alignment: 21 > 50 > 200 under price)
// Slope is positive
bool bullishAlignment = ema50 < ema21 and ema200 < ema50
bool priceCrossUp = ta.crossover(close, ema21)
bool longEntry = priceCrossUp and bullishAlignment and slopeUp
// ── SHORT ────────────────────────────────────────────────────────────────────
// EMA21 below EMA50 AND below EMA200 (bearish alignment)
// Slope is negative
// Trigger: price crosses below EMA21
bool bearishAlignment = ema21 < ema50 and ema21 < ema200
bool priceCrossDn = ta.crossunder(close, ema21)
bool shortEntry = priceCrossDn and bearishAlignment and slopeDn
// ── EXITS ────────────────────────────────────────────────────────────────────
// Long exit: bullish alignment breaks (EMA21 crosses below EMA50)
bool exitLong = ta.crossunder(ema21, ema50)
// Short exit: bearish alignment breaks (EMA21 crosses above EMA50)
bool exitShort = ta.crossover(ema21, ema50)
// ═══════════════════════════════════════════════════════════════════════════════
// STOP & TP CALCULATION
// ═══════════════════════════════════════════════════════════════════════════════
float longStop = longEntry ? math.min(low, ema50) - atr * i_atrMult : 0.0
float shortStop = shortEntry ? math.max(high, ema50) + atr * i_atrMult : 0.0
float longRisk = longEntry ? close - longStop : 0.0
float shortRisk = shortEntry ? shortStop - close : 0.0
float longTP = longEntry and i_rrRatio > 0 ? close + longRisk * i_rrRatio : 0.0
float shortTP = shortEntry and i_rrRatio > 0 ? close - shortRisk * i_rrRatio : 0.0
// ═══════════════════════════════════════════════════════════════════════════════
// SIGNAL PROTOCOL — Output for Leverage Strategy Shell
// ═══════════════════════════════════════════════════════════════════════════════
// +1 = Long entry -1 = Short entry
// +2 = Close long -2 = Close short
// 0 = No signal
float signal = longEntry ? 1 : shortEntry ? -1 : exitLong ? 2 : exitShort ? -2 : 0
float stopPx = longEntry ? longStop : shortEntry ? shortStop : 0
float tpPx = longEntry ? longTP : shortEntry ? shortTP : 0
// Plots: connect these to Strategy Shell's input.source()
plot(signal, "Signal", color=color.new(color.yellow, 100), display=display.none)
plot(stopPx, "Stop", color=color.new(color.red, 100), display=display.none)
plot(tpPx, "TP", color=color.new(color.green, 100), display=display.none)
// ═══════════════════════════════════════════════════════════════════════════════
// VISUAL — EMAs + Entry markers + Stop/TP levels
// ═══════════════════════════════════════════════════════════════════════════════
plot(i_showEMA ? ema21 : na, "EMA 21", color=color.new(#FFD700, 0), linewidth=2)
plot(i_showEMA ? ema50 : na, "EMA 50", color=color.new(#5b7dff, 0), linewidth=1)
plot(i_showEMA ? ema200 : na, "EMA 200", color=color.new(#c792ea, 0), linewidth=1)
// Entry arrows
plotshape(longEntry, "Long", shape.triangleup, location.belowbar, color.new(#22d47a, 0), size=size.small)
plotshape(shortEntry, "Short", shape.triangledown, location.abovebar, color.new(#f05050, 0), size=size.small)
// Exit crosses
plotshape(exitLong, "Exit L", shape.xcross, location.abovebar, color.new(#22d47a, 60), size=size.tiny)
plotshape(exitShort, "Exit S", shape.xcross, location.belowbar, color.new(#f05050, 60), size=size.tiny)
// Stop & TP lines on signal bars
plot(longEntry ? longStop : na, "L Stop", color=color.new(#f05050, 0), style=plot.style_circles, linewidth=3)
plot(longEntry ? longTP : na, "L TP", color=color.new(#22d47a, 0), style=plot.style_circles, linewidth=3)
plot(shortEntry ? shortStop : na, "S Stop", color=color.new(#f05050, 0), style=plot.style_circles, linewidth=3)
plot(shortEntry ? shortTP : na, "S TP", color=color.new(#22d47a, 0), style=plot.style_circles, linewidth=3)
// ═══════════════════════════════════════════════════════════════════════════════
// INFO LABEL — slope + alignment status
// ═══════════════════════════════════════════════════════════════════════════════
var label infoLbl = na
if barstate.islast
string status = bullishAlignment ? "BULL ▲" : bearishAlignment ? "BEAR ▼" : "NEUTRAL —"
string slopeTxt = "Slope 21: " + (slopeUp ? "+" : "") + str.tostring(slope21, "#.##")
string txt = "EMA Signal ★ " + status + " " + slopeTxt
color bg = bullishAlignment ? color.new(#22d47a, 80) : bearishAlignment ? color.new(#f05050, 80) : color.new(#888888, 80)
if not na(infoLbl)
label.delete(infoLbl)
infoLbl := label.new(bar_index, high, txt, style=label.style_label_down, color=bg, textcolor=color.white, size=size.small)
Credits
Concept, architecture, and code: Oberlunar.
Built in Pine Script™ v6. Strategy

AG Pro Aroon Trend Freshness [AGPro Series]AG Pro Aroon Trend Freshness
OVERVIEW / WHAT IT DOES
AG Pro Aroon Trend Freshness is an overlay indicator designed to map the lifecycle of a trend through the lens of Aroon recency. Instead of treating Aroon as a simple crossover oscillator, this script reorganizes Aroon behavior into a freshness framework that helps users distinguish between newly refreshed trends, still-active trends, aging trends, and reset or neutral phases.
The core idea is straightforward: Aroon is naturally linked to recency because it measures how recently the market printed its highest high or lowest low within a selected lookback window. This script uses that characteristic to answer a more practical charting question: is the current directional structure still fresh, or is it starting to age?
To make that information easier to read directly on price, the script plots a trend backbone on the chart and classifies the current state into lifecycle phases such as Ignition, Fresh Trend, Mature Trend, Aging, and Reset / Neutral. The result is not a buy/sell engine. It is a context layer designed to help users assess whether a directional move is still renewing itself or gradually losing freshness.
This script is intended for traders and analysts who want a cleaner way to read trend recency without relying only on momentum, volatility, or moving-average distance. It can be used as a directional context tool, a state filter, or an additional confirmation layer when studying structure, pullbacks, continuation attempts, or exhaustion behavior.
UNIQUE EDGE
Most Aroon-based tools stop at directional interpretation, threshold crossings, or oscillator-style reading. AG Pro Aroon Trend Freshness takes a different path. It does not focus on standard crossover events as the primary message. Instead, it translates Aroon behavior into a trend-age map.
That distinction matters. Two trends can both remain directional while having very different freshness profiles. One may still be regularly refreshing with new structural extremes, while the other may be drifting forward without meaningful renewal. This script is built to highlight that difference.
The indicator is therefore not trying to measure everything at once. It does not attempt to replace trend strength tools, volume tools, volatility tools, market breadth tools, or correlation tools. Its job is narrower and more specific: to visualize whether directional structure is being refreshed, maintained, aged, or reset.
METHODOLOGY
The script starts from classic Aroon logic, which evaluates how recently the highest high and lowest low occurred within a user-defined lookback. From there, the script derives a directional bias and a freshness profile.
The directional side of the model evaluates which side currently dominates the lookback structure. The freshness side evaluates how recent and how persistent that dominance is, whether it is accelerating, stabilizing, or decaying, and whether the market is showing signs of reset rather than continuation.
To make the output easier to interpret on a live chart, the script organizes that information into lifecycle states:
- Ignition: a newly refreshed directional phase where recency improves sharply.
- Fresh Trend: an active directional state with strong freshness characteristics.
- Mature Trend: a still-valid trend state where freshness remains constructive but is no longer in its earliest phase.
- Aging: a state where directional structure may still exist, but freshness has started to decay.
- Reset / Neutral: a state where the previous directional freshness has weakened enough that the structure becomes less directional or less renewed.
The backbone and glow are visual aids, not forecasts. They are designed to make state transitions easier to see without forcing the user to inspect raw oscillator values. Panel statistics such as Trend Age Score, Refresh Pulse, Reset Risk, and Last Refresh Bars Ago are also contextual measures. They help summarize the current lifecycle condition, but they should not be interpreted as guarantees or as standalone trade instructions.
SIGNALS & ALERTS
The script can be used to monitor lifecycle transitions rather than raw directional triggers.
In practical use, users may watch for situations such as:
- a move entering Ignition after a reset phase,
- a trend remaining in Fresh Trend while structure continues to refresh,
- a shift from Fresh or Mature conditions into Aging,
- an increase in reset risk after an extended directional phase.
These state changes can be useful when analyzing pullback quality, continuation attempts, or exhaustion risk. However, the script is not intended to predict future price movement on its own. Alerts should be treated as structured notifications about state changes, not as automatic trade commands.
KEY INPUTS
- Aroon Length: controls the recency lookback window used by the freshness model.
- Confirmation / Filtering Settings: help reduce noise and make state transitions more selective.
- Label and Visual Settings: allow users to manage the amount of chart annotation.
- Panel Settings: control how lifecycle information is displayed on the chart.
Shorter settings generally make the model more reactive, while longer settings usually make it more selective and smoother. Users should adapt these inputs to the symbol, timeframe, and charting style they are working with.
LIMITATIONS & TRANSPARENCY
This script does not measure profitability, expectancy, or trade performance. It does not know position size, account risk, execution quality, slippage, spread, or portfolio context. It also does not replace market structure analysis, support/resistance work, volume interpretation, or higher-timeframe review.
Because the model is built on recency logic, it can react differently across instruments and regimes. Choppy markets may produce frequent state shifts. Strong trends may remain constructive longer than expected. Very low-volatility or highly erratic symbols may also affect how smoothly lifecycle states appear.
Users should understand that this indicator is designed to classify trend freshness, not to promise reversals, continuations, or outcomes. It is best used as a chart-reading framework that complements a broader process.
RISK DISCLOSURE
This indicator is for chart analysis and educational use. It is not financial advice and it does not provide guaranteed signals or future performance expectations. All trading and investing decisions involve risk. Users should evaluate markets with their own judgment, risk controls, and testing process before acting on any chart-based observation.
Indicator

Indicator

Smart Money Flow [CIO Edition] - Volumen Institucional PuroLa vieja regla de Wall Street es clara: "Los minoristas abren el mercado, los profesionales lo cierran."
La inmensa mayoría de los indicadores de "Smart Money Index" (SMI) públicos cometen un error matemático crítico: mezclan la volatilidad emocional y las noticias de la mañana con la actividad de la tarde. El resultado es un indicador ruidoso que termina rastreando al "Dumb Money" (Dinero Minorista).
Este script nace de la necesidad de operar con un radar institucional real. Ha sido rediseñado desde cero para rastrear Flujo Puro y Confirmado.
¿Qué hace único a este indicador?
🛡️ Filtro de Ruido Matutino: Ignora por completo lo que ocurre desde las 9:30 AM hasta las 3:00 PM. Se enfoca única y exclusivamente en los últimos 60 minutos de la sesión, el territorio donde operan las "manos fuertes" (fondos, ETFs, algoritmos).
⚖️ Ponderación por Volumen (El Filtro de la Verdad): No se deja engañar por manipulaciones de precio con poca liquidez. El algoritmo multiplica el movimiento del precio por el volumen real de acciones transadas. Si la línea se mueve, es porque hay millones de dólares respaldando ese movimiento.
🚦 Inteligencia Visual Integrada: El indicador cambia de color automáticamente en relación con su propia tendencia (SMA de 18 periodos) para darte veredictos instantáneos:
Línea VERDE (Acumulación): El flujo institucional está entrando. Las ballenas compran al cierre. Tienes "viento a favor" para buscar compras.
Línea ROJA (Distribución): Los profesionales están descargando posiciones silenciosamente. Alerta máxima de Bull Trap (Trampa Alcista) o techo de mercado.
La Estrategia (Cómo usarlo):
No lo uses para seguir el precio ciegamente; úsalo para buscar divergencias.
El Suelo Oculto: Si el mercado general cae víctima del pánico, pero este indicador sube y se pinta de VERDE, los institucionales están absorbiendo las ventas minoristas. Es tu señal para comprar empresas de alta calidad con margen de seguridad.
El Techo Silencioso: Si el mercado marca máximos históricos, pero el indicador cae en picado en color ROJO, el dinero profesional está usando la euforia para salir. Protege tu capital y guarda liquidez.
Diseñado para inversores de valor, gestores de cartera y estrategas que necesitan ver detrás de la cortina del precio diario. Indicator

Indicator

Trend Pro Master SuiteTrend Pro Master - Advanced Trend & Target Suite
Description:
Overview
Trend Pro Master is a comprehensive trend-following indicator designed to provide high-precision entry signals and dynamic, pro-active target management. Based on a refined HalfTrend core, it filters market noise to provide a clean, stepped visualization of market momentum, making it suitable for Scalping, Day Trading, and Swing Trading across all asset classes.
Core Methodology
The indicator utilizes price action pivots and ATR-based offsets to identify trend reversals with minimal lag.
Cyan Line/Arrows: Indicate a confirmed Bullish Trend.
Red Line/Arrows: Indicate a confirmed Bearish Trend.
Key Features
🚀 Pro-Active Take Profit Projections
Unlike traditional indicators that show targets after the fact, Trend Pro Master draws horizontal TP1 and TP2 projection lines the instant a signal appears. These lines help traders visualize their exit strategy immediately upon entry. Once a target is hit, the line solidifies and marks the exact hit-bar.
🎯 4 Take Profit Calculation Modes
Custom-tailor your targets to your specific strategy:
Points: Fixed point distance (ideal for standard pip targets).
ATR Multiple: Dynamic targets that expand and contract with market volatility.
Risk:Reward: Targets calculated as a multiple of your Stop Loss distance.
Indicator Offset: Unique targets based on the current "width" of the trend line.
📊 Dynamic Performance Dashboard
A fully customizable, real-time stats table that tracks:
Current Trade Status & Entry Price.
Total number of signals generated.
TP1 Hit count and percentage.
Success Rate: Live win-probability calculation based on target hits.
Customizable: Change the position (9 different spots) and size (Tiny to Large) to fit your chart layout.
🔔 Professional Push Alerts
Integrated alert() function support for high-quality push notifications. Get entry signals and target prices sent directly to your phone or browser in a clear format:
Example: "Buy Signal EURUSD (H1) TP1: 1.08550 TP2: 1.09200"
Settings Guide
Amplitude: Controls the sensitivity. Higher values = smoother trend, fewer signals. Lower values = more sensitive, more signals.
Channel Deviation: Adjusts the offset of the trend line from price.
Visuals & Styling: Full control over Trend Line thickness, TP Marker colors, and Label sizes.
How to Use
Entry: Enter a trade when an "Entry" arrow appears.
Targets: Aim for TP1 for consistent wins or TP2 for higher reward-to-risk ratios.
Exit: Exit the remainder of your position if the trend line changes color (reversal). Indicator

Gap Analyzer [ThetaLoop]Every stock has a gap personality.
Some barely move overnight. Others routinely open 4% away from where they closed. Some gap up more than down. Others are the opposite. Some calm down quickly after a gap. Others stay volatile for weeks.
You cannot see any of this on a standard candlestick chart. This indicator builds a complete statistical profile of how your stock behaves around overnight gaps — how often, how big, which direction, and what happens to volatility afterward.
What it does
Scans the entire visible price history for significant overnight gaps (open vs. previous close). Every gap that exceeds your size threshold gets logged, classified by direction, and analyzed for post-gap volatility behavior. The result is a table showing this stock's gap DNA.
What the table shows
Gap Profile — Overall classification. FREQUENT means this stock gaps often (20+ times per year). RARE means gaps are unusual events when they happen.
Gaps Found — Total count and annualized frequency. "12 (5.2/yr)" means 12 gaps detected, roughly 5 per year.
Direction — How many gaps went up vs. down. UPSIDE BIAS means this stock gaps up more often. DOWNSIDE BIAS means more gaps are to the downside. BALANCED means roughly even.
Avg Size — Average absolute gap size across all detected events.
Largest — The biggest gap up and gap down in the visible history. This is your worst-case reference.
After Gap — What typically happens to volatility after this stock gaps. STRONG CRUSH means vol drops significantly (common for earnings-type events). VOL EXPANDS means gaps tend to trigger extended volatility (common for regime shifts or bad news).
Vol Change — The average percentage change in realized volatility from gap day to the end of the post-gap window. Negative = vol decreased. Positive = vol increased.
Crush Rate — What percentage of gaps led to a decrease in volatility afterward. Above 60% means gaps on this stock tend to be one-time events. Below 40% means gaps trigger sustained instability.
Avg Drift — After the gap, does price tend to continue in the gap direction (momentum) or reverse (mean reversion)? Positive drift after gap-downs means the stock tends to recover. Negative drift means it keeps falling.
Status — Where you are right now. JUST GAPPED, POST-GAP (with day count), or NORMAL.
The chart
Green triangles mark gap-up events. Red triangles mark gap-downs. Teal background zones show the post-gap observation window. The main plot shows either vol change, gap size, or post-gap drift as a time series (switchable).
Why this matters for options sellers
If you sell puts, gap-downs are your primary risk. Knowing that your stock gaps down on average 4.2% and does it roughly 6 times per year is directly actionable information. Compare that gap size to your buffer (strike distance from current price) — if your typical buffer is 5% and the average gap-down is 4.2%, you are cutting it close.
The post-gap vol behavior tells you whether to hold or close after a gap event. If this stock has a high crush rate (vol drops after gaps), sitting tight is statistically the better move. If vol tends to expand after gaps, getting out quickly is wiser.
The direction bias helps with strategy selection. A stock with strong upside gap bias is more suited for put selling (gaps tend to go in your favor). A stock with downside bias carries more overnight assignment risk.
Important note on gap detection
This indicator identifies gaps purely from price and volume data. It does not use an earnings calendar or news feed. A gap is a gap regardless of the cause — earnings, news, FOMC, analyst upgrades, tariff announcements, or random overnight moves. This is intentional. Your risk from a 5% gap-down is identical whether it came from earnings or a tweet. The statistical profile captures all of them.
You can toggle volume confirmation on or off. With it on, only gaps accompanied by above-average volume are counted — this filters out thin overnight moves and catches events where real participation occurred. With it off, all gaps above the size threshold are counted regardless of volume.
Settings
Min Gap Size (default 3%) — Threshold for what counts as a significant gap. Adjust based on the stock. 3% is meaningful for a $100 large-cap. For a $15 small-cap, you might want 5%.
Volume Confirmation (default on) — Require above-average volume on gap day.
Volume Multiple (default 1.5x) — How much above average volume needs to be.
Post-Gap Window (default 10) — How many days after a gap to measure vol behavior and price drift.
Display Mode — Vol Change (default), Gap Size, or Post-Gap Drift as the main time series plot.
Alerts
Gap Down Detected — Significant downside gap. Check your put exposure.
Gap Up Detected — Significant upside gap.
Post-Gap Window Complete — Analysis period after last gap is finished.
Indicator
