PROTECTED SOURCE SCRIPT
Enhanced Oversold | 超跌信号 + 历史统计 + 模拟入出场 (v2.4)

Enhanced Oversold | Oversold Signal + Historical Stats + Simulated Entries/Exits (v2.4) – Release Notes (EN)
1. Overview
This script is an advanced “buy-the-dip” toolkit for US stocks and ETFs. It detects rare, deep intraday selloffs on fundamentally strong names, then simulates a three-tier entry strategy around the event and tracks different exit paths.
The goal is to answer three questions:
* When did similar crashes happen in the past?
* How would a disciplined laddered entry have performed?
* How long did it take for price to recover under different exit rules?
2. Core idea
* Define an 8-hour “crash” relative to a robust reference price yBase = min(previous-day VWAP, previous close).
* Combine this with short-term RSI and 15m Z-score filters to avoid “random noise” dips.
* Filter out regime-level risk (index / sector crash, volatility spikes, liquidity stress, bad long-term trend).
* When a valid oversold event appears, simulate staged entries (E1/E2/E3) and exits, then record everything into a historical table and JSON for external analysis.
3. Signal logic (summary)
* Timeframe: designed for 15m / 5m charts, using US RTH session 09:30–16:00.
* Crash trigger (must all be true):
* 8h drawdown from yBase ≤ fixed threshold (default −6%) and the 8h low is recent within N×15m bars.
* RSI(1h) below an oversold level (default < 30).
* 15m return Z-score ≤ threshold (default ≤ −1.5) over a configurable window.
* Optional filters:
* Circuit breaker: SPY + sector ETF + VIX/VIX3M + VVIX conditions to avoid market-wide panic regimes.
* Liquidity stress: SPY 1h “stress index” (ATR/price, intraday range vs volume, and VIX Z-score) normalised to 0–100, with a user threshold.
* Shape filter: only accept “A-type” healthy long-term trend set-ups (6m / 12m performance vs VWAP/EMA and daily 200SMA slope).
4. Simulated entries (E1 / E2 / E3)
* E1: first ladder price anchored to the first RTH after the event, with optional “same-day RTH” entry if the event happens during RTH.
* E2: only becomes valid from the next RTH day onward, and only if the new RTH low breaks the E1-execution-day low. The target depth is based on E1 discount × (1+α).
* E3: only after E2, on a different day (not the E1 “anchor” day). Depth is based on the max discount of E1/E2 × (1+β).
* Stair and cap rules:
* A minimum tick step between ladders, adjustable in ticks.
* Optional cap so that every entry price must be below a multiple of the event price.
* Optional “chase on first RTH bar”: if nothing fills on the first RTH bar, prices can be lifted once toward the intraday low, while keeping ladder spacing and cap constraints.
* All actual fills are simulated against bar lows. The script records:
* Whether E1/E2/E3 filled.
* Actual execution prices.
* Average entry price and the entry sequence string (e.g. “13”, “123”).
5. Exit logic and timing metrics
Two exit rules are tracked in parallel:
* Exit Ref: exit when close returns to yBase.
* Exit Open+Y%: exit when close reaches min(event close, first post-event open) × (1+Y%).
For each event the script records:
* t_ref_d: days from event to first touch of yBase.
* tY_d: days until Open+Y% level is reached.
* tUp_d: days until price turns “bullish again” (RTH VWAP ≥ previous daily VWAP and close > previous close).
* tLow_d: days until the minimum price between event and t_ref (or end of window) is reached.
* lowToRef: that minimum price.
* ddMinPct: maximum drawdown (in %) from average entry to lowToRef.
Additional intraday stats for the first RTH after the event:
* dayFirstLow: low of the first RTH bar from the chosen statistics start.
* rthLow: overall RTH low of that day.
* eqFirst: whether the overall low equals the first-bar low.
* postDipAvg: average close after the daily low is formed (equal-weighted).
6. Historical table on chart
* The on-chart table shows up to maxRows events, most recent first.
* Columns include:
* Date, 8h drawdown, yBase, stress, circuit conditions, shape (A/B/C).
* Entry sequence and actual execution prices.
* Average entry price.
* Exit prices and PnL (in % and absolute) for both exit modes.
* Timing metrics (t_ref, tY, tUp, tLow).
* Min price to t_ref, max drawdown vs average entry.
* First RTH low, day RTH low, equality flag, post-dip average, and market flag (US/HK).
The table is only redrawn on bar close to reduce CPU load.
7. Liquidity stress pane
* Optional lower pane that plots the SPY-based liquidity stress index (0–100).
* Components (all on 60m SPY/VIX data):
* rvZ: Z-score of ATR/price.
* rpvZ: Z-score of intraday range divided by volume.
* vixZ: Z-score of VIX.
* Stress index = 50 + 10 × (rvZ + rpvZ + vixZ), clipped to [0,100].
* A horizontal line marks the current filter threshold.
8. Webhook JSON outputs
The indicator can send three types of alerts via alert():
* Signal
* Emitted only when a new oversold event fires.
* Contains ticker, market flag, event time, drop8h, RSI1h, Z15, yBase, shape, circuit reason, and stress.
* History
* Emitted when requested, containing a full snapshot of the latest event:
* All key metrics used in the table, including absolute PnL for both exit modes, timing metrics, drawdown stats, and post-dip averages.
* HistoryAll
* Compressed bulk export of all events as a compact JSON object:
* Short keys (d, dr8, yb, st, c, sh, e, px, avg, xr, pr, absR, xy, py, absY, tr, ty, tu, tl, l2r, dd, fl, rl, eq, pavg).
* Numbers rounded to 3 decimals to reduce payload size.
* Because TradingView enforces a payload size limit, HistoryAll is automatically split into multiple chunks (up to ~3200 characters each).
* When HistoryAll is selected and a manual “dump all” flag is turned on, the script will emit multiple alerts on the same bar until all chunks are sent.
9. What is new in v2.3
Compared with previous versions, v2.3 adds:
* Deeper risk metrics:
* Tracking of the minimum price until recovery (lowToRef) and its timing (tLow_d).
* Max drawdown vs average entry (ddMinPct) for each event.
* E1-execution-day RTH low tracking, used to decide whether later days truly “make a new low” before adding E2.
* Absolute PnL fields:
* absRef and absOY for both exit modes, calculated using user-defined share/contract sizes for E1/E2/E3.
* More compact and robust HistoryAll:
* Short-key JSON objects, 3-decimal numeric formatting, chunked output suitable for 3rd-party storage and analysis.
* Performance optimisations:
* Array length normalisation is done once per bar instead of inside the per-event loop.
* Table rendering only happens on bar close, and no longer clears the whole grid every bar.
* Same-day RTH pricing for event-day entries is restricted to the latest event only, reducing redundant work on historical events.
10. Usage notes and disclaimer
* Recommended canvas: 15m or 5m chart, US stocks / ETFs, with RTH session set to 09:30–16:00.
* For stable operation on TradingView’s servers, avoid extremely large lookback windows and oversized history tables if your symbol has very long history.
* This script is for educational and research purposes only.
* It is not financial advice and does not guarantee profitability. Always combine it with your own risk management, fundamental research, and market context.
1. Overview
This script is an advanced “buy-the-dip” toolkit for US stocks and ETFs. It detects rare, deep intraday selloffs on fundamentally strong names, then simulates a three-tier entry strategy around the event and tracks different exit paths.
The goal is to answer three questions:
* When did similar crashes happen in the past?
* How would a disciplined laddered entry have performed?
* How long did it take for price to recover under different exit rules?
2. Core idea
* Define an 8-hour “crash” relative to a robust reference price yBase = min(previous-day VWAP, previous close).
* Combine this with short-term RSI and 15m Z-score filters to avoid “random noise” dips.
* Filter out regime-level risk (index / sector crash, volatility spikes, liquidity stress, bad long-term trend).
* When a valid oversold event appears, simulate staged entries (E1/E2/E3) and exits, then record everything into a historical table and JSON for external analysis.
3. Signal logic (summary)
* Timeframe: designed for 15m / 5m charts, using US RTH session 09:30–16:00.
* Crash trigger (must all be true):
* 8h drawdown from yBase ≤ fixed threshold (default −6%) and the 8h low is recent within N×15m bars.
* RSI(1h) below an oversold level (default < 30).
* 15m return Z-score ≤ threshold (default ≤ −1.5) over a configurable window.
* Optional filters:
* Circuit breaker: SPY + sector ETF + VIX/VIX3M + VVIX conditions to avoid market-wide panic regimes.
* Liquidity stress: SPY 1h “stress index” (ATR/price, intraday range vs volume, and VIX Z-score) normalised to 0–100, with a user threshold.
* Shape filter: only accept “A-type” healthy long-term trend set-ups (6m / 12m performance vs VWAP/EMA and daily 200SMA slope).
4. Simulated entries (E1 / E2 / E3)
* E1: first ladder price anchored to the first RTH after the event, with optional “same-day RTH” entry if the event happens during RTH.
* E2: only becomes valid from the next RTH day onward, and only if the new RTH low breaks the E1-execution-day low. The target depth is based on E1 discount × (1+α).
* E3: only after E2, on a different day (not the E1 “anchor” day). Depth is based on the max discount of E1/E2 × (1+β).
* Stair and cap rules:
* A minimum tick step between ladders, adjustable in ticks.
* Optional cap so that every entry price must be below a multiple of the event price.
* Optional “chase on first RTH bar”: if nothing fills on the first RTH bar, prices can be lifted once toward the intraday low, while keeping ladder spacing and cap constraints.
* All actual fills are simulated against bar lows. The script records:
* Whether E1/E2/E3 filled.
* Actual execution prices.
* Average entry price and the entry sequence string (e.g. “13”, “123”).
5. Exit logic and timing metrics
Two exit rules are tracked in parallel:
* Exit Ref: exit when close returns to yBase.
* Exit Open+Y%: exit when close reaches min(event close, first post-event open) × (1+Y%).
For each event the script records:
* t_ref_d: days from event to first touch of yBase.
* tY_d: days until Open+Y% level is reached.
* tUp_d: days until price turns “bullish again” (RTH VWAP ≥ previous daily VWAP and close > previous close).
* tLow_d: days until the minimum price between event and t_ref (or end of window) is reached.
* lowToRef: that minimum price.
* ddMinPct: maximum drawdown (in %) from average entry to lowToRef.
Additional intraday stats for the first RTH after the event:
* dayFirstLow: low of the first RTH bar from the chosen statistics start.
* rthLow: overall RTH low of that day.
* eqFirst: whether the overall low equals the first-bar low.
* postDipAvg: average close after the daily low is formed (equal-weighted).
6. Historical table on chart
* The on-chart table shows up to maxRows events, most recent first.
* Columns include:
* Date, 8h drawdown, yBase, stress, circuit conditions, shape (A/B/C).
* Entry sequence and actual execution prices.
* Average entry price.
* Exit prices and PnL (in % and absolute) for both exit modes.
* Timing metrics (t_ref, tY, tUp, tLow).
* Min price to t_ref, max drawdown vs average entry.
* First RTH low, day RTH low, equality flag, post-dip average, and market flag (US/HK).
The table is only redrawn on bar close to reduce CPU load.
7. Liquidity stress pane
* Optional lower pane that plots the SPY-based liquidity stress index (0–100).
* Components (all on 60m SPY/VIX data):
* rvZ: Z-score of ATR/price.
* rpvZ: Z-score of intraday range divided by volume.
* vixZ: Z-score of VIX.
* Stress index = 50 + 10 × (rvZ + rpvZ + vixZ), clipped to [0,100].
* A horizontal line marks the current filter threshold.
8. Webhook JSON outputs
The indicator can send three types of alerts via alert():
* Signal
* Emitted only when a new oversold event fires.
* Contains ticker, market flag, event time, drop8h, RSI1h, Z15, yBase, shape, circuit reason, and stress.
* History
* Emitted when requested, containing a full snapshot of the latest event:
* All key metrics used in the table, including absolute PnL for both exit modes, timing metrics, drawdown stats, and post-dip averages.
* HistoryAll
* Compressed bulk export of all events as a compact JSON object:
* Short keys (d, dr8, yb, st, c, sh, e, px, avg, xr, pr, absR, xy, py, absY, tr, ty, tu, tl, l2r, dd, fl, rl, eq, pavg).
* Numbers rounded to 3 decimals to reduce payload size.
* Because TradingView enforces a payload size limit, HistoryAll is automatically split into multiple chunks (up to ~3200 characters each).
* When HistoryAll is selected and a manual “dump all” flag is turned on, the script will emit multiple alerts on the same bar until all chunks are sent.
9. What is new in v2.3
Compared with previous versions, v2.3 adds:
* Deeper risk metrics:
* Tracking of the minimum price until recovery (lowToRef) and its timing (tLow_d).
* Max drawdown vs average entry (ddMinPct) for each event.
* E1-execution-day RTH low tracking, used to decide whether later days truly “make a new low” before adding E2.
* Absolute PnL fields:
* absRef and absOY for both exit modes, calculated using user-defined share/contract sizes for E1/E2/E3.
* More compact and robust HistoryAll:
* Short-key JSON objects, 3-decimal numeric formatting, chunked output suitable for 3rd-party storage and analysis.
* Performance optimisations:
* Array length normalisation is done once per bar instead of inside the per-event loop.
* Table rendering only happens on bar close, and no longer clears the whole grid every bar.
* Same-day RTH pricing for event-day entries is restricted to the latest event only, reducing redundant work on historical events.
10. Usage notes and disclaimer
* Recommended canvas: 15m or 5m chart, US stocks / ETFs, with RTH session set to 09:30–16:00.
* For stable operation on TradingView’s servers, avoid extremely large lookback windows and oversized history tables if your symbol has very long history.
* This script is for educational and research purposes only.
* It is not financial advice and does not guarantee profitability. Always combine it with your own risk management, fundamental research, and market context.
Skrip terproteksi
Skrip ini diterbitkan sebagai sumber tertutup. However, you can use it freely and without any limitations – learn more here.
Pernyataan Penyangkalan
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Skrip terproteksi
Skrip ini diterbitkan sebagai sumber tertutup. However, you can use it freely and without any limitations – learn more here.
Pernyataan Penyangkalan
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.