Pine Script®策略
指標和策略
Reverse Pulse System# Reverse Pulse Trading System – Strategy Description for TradingView
---
## Overview
**Reverse Pulse** is a deterministic sweep-and-reverse trading system for TradingView. It identifies liquidity sweeps at fractal-defined Point-of-Interest (POI) levels and enters counter-trend when the price fails to follow through—using an "Attempted Candle" or "Trigger Break" confirmation.
- **Type:** Mean-reversion / Sweep-reversal
- **Timeframe:** M5 (recommended)
- **Instruments:** XAUUSD, EURUSD, and similar liquid pairs
- **Session:** 09:00–20:00 (Europe/Berlin, DST-safe; default for Gold US session)
- **Non-repainting:** Closed-bar logic, no lookahead bias
---
## Concept
1. **Trend Bias (H1):** Supertrend on H1 with body-break confirmation—long setups only when bias is long, short setups only when bias is short.
2. **POI Level:** Fractal highs (short bias) or fractal lows (long bias) define the key levels to watch.
3. **Sweep:** Price breaks the POI level (wick) but reverses back.
4. **Entry:** "Attempted Candle"—the candle that prints the new extreme and confirms reversal (either directly bullish/bearish or via a trigger break).
---
## Components
### Trend Bias (Supertrend H1)
- Supertrend on H1 with adjustable Factor and ATR Length.
- **Body-break:** Direction change only when the candle body breaks the Supertrend line (not just the wick).
- Reduces false signals from volatile wicks.
### POI (Point of Interest)
- **MTF Fractals ** – CC BY-NC-SA 4.0
- Long bias: Fractal low as POI (lowest fractal low in lookback).
- Short bias: Fractal high as POI (highest fractal high in lookback).
- Fractal size: 3, 5, 7, or 9 bars.
- Optional: Higher timeframe for fractals (MTF).
### Sweep Detection
- **Long:** Price makes a new low below the POI level.
- **Short:** Price makes a new high above the POI level.
- While sweep is active, the extreme low/high is tracked.
### Entry Logic (Two Paths)
**1. Attempted Candle (direct)** – Sweep + failure on the same candle:
- **Long:** `low < poiLevel` (sweep), `close > open` (bullish), `low < low ` (new low).
- **Short:** `high > poiLevel` (sweep), `close < open` (bearish), `high > high ` (new high).
- SL: Low/High of this attempted candle. Entry: Close.
**2. Trigger + Break** – Candle prints the extreme but has the wrong color → wait for break:
- **Long:** Trigger candle = bearish, prints low. Trigger level = its high. Entry when a bullish candle closes above the trigger level.
- **Short:** Trigger candle = bullish, prints high. Trigger level = its low. Entry when a bearish candle closes below the trigger level.
- SL: Option A = Low/High of the break candle. Option B = Low/High of the trigger candle.
### Williams %R Filter (Optional)
- **Long:** Trade only if Williams %R (0–100) reached at least 95 (overbought) within the last X bars.
- **Short:** Trade only if Williams %R (0–100) reached at most 5 (oversold) within the last X bars.
- Default lookback: 20 bars. Default length: 14.
- When disabled, the filter is not applied.
---
## Exits
- **TP:** Minimum R:R (e.g. 2R)—Take-Profit = Entry ± (Risk × Min R:R).
- **SL:** Stop-Loss based on entry logic (Low/High of the relevant candle).
---
## Risk Management
- **Position sizing:** `qty = RiskAmount / (SL distance × USD per point)`.
- **XAUUSD:** USD per point = 1 (1 USD P&L per 1 USD price move per oz).
- **Daily stop:** After N stop-loss losses (default: 4), no further trades until session reset (09:00).
- **Max Qty:** Upper limit for position size (e.g. 500 oz for Gold).
---
## Session & Time
- **DST-safe:** Timestamps use IANA timezone (e.g. `Europe/Berlin`).
- **Default:** 09:00–20:00 Europe/Berlin (for Gold US session).
- **Session OFF:** Debug option to disable session filter (24/7 testing).
---
## Settings Overview
| Group | Parameter | Default |
|-------|-----------|---------|
| Session | Start/End Hour, Min, Timezone | 09:00–20:00, Europe/Berlin |
| Supertrend | Factor, ATR Length | 3.0, 10 |
| Fractals | Bars in Fractal, Timeframe | 5, Chart TF |
| Entry | Trigger-Break SL (A/B) | A |
| Filter Williams %R | Use Filter, Lookback, Length | Off, 20, 14 |
| Filter Williams %R | Min for Long, Max for Short | 95, 5 |
| Risk | Risk %, USD per Point, Max Qty | 1%, 1, 500 |
| Risk | Min R:R, Max SL per Day | 2, 4 |
| Debug | Show Debug, Level Lines, Legend | true, true, true |
---
## Recommended Instruments
- **XAUUSD** (Gold)
- **EURUSD**
- Other liquid forex and metal pairs with suitable tick size
---
## Technical Notes
- **process_orders_on_close:** Orders are executed at bar close.
- **pyramiding:** 0 (no pyramiding).
- **Float comparison:** `approxEq()` with `syminfo.mintick` for stable behavior.
---
## License Notice
- Fractals: MTF Fractals – CC BY-NC-SA 4.0
creativecommons.org
---
## Disclaimer
This system is for educational and research purposes only. There is no guarantee of profits. Trading involves substantial risk. Only trade with capital you can afford to lose.
Pine Script®策略
ACADEMIC TSMOM 5TF Description:
This script is a robust implementation of the Time Series Momentum (TSMOM) strategy, designed to capture high-probability trends by analyzing 5 different timeframes (MTF) simultaneously while applying a sophisticated Volatility Targeting mechanism to manage position sizing.
How it Works:
The strategy evaluates price direction across five user-defined timeframes (from scalping levels to daily trends). Each timeframe contributes a weighted value to a master "Momentum Score":
Multi-Timeframe Consensus: Entries are only triggered when the aggregate trend strength (Score) exceeds a specific confidence threshold.
No-Trade Zone Filter: This feature prevents overtrading in choppy, sideways markets by requiring a minimum momentum conviction before switching direction.
Advanced Risk Management (Vol Targeting):
Unlike static strategies, this script utilizes Dynamic Volatility Targeting. It automatically scales the position size (qty) based on the asset's current volatility (Standard Deviation):
High Volatility: The script scales down position size to protect equity from large swings.
Low Volatility: The script increases size to maximize capital efficiency when the trend is stable.
Max Leverage Cap: Includes a safety limit to ensure the strategy stays within realistic simulation bounds.
Key Features:
Real-Time Debug Table: A visual HUD on your chart displaying the status of all 5 TFs, current momentum score, sigma (volatility), and calculated position units.
Independent Alert System: Built with specific alertcondition triggers for LONG ONLY and SHORT ONLY signals, making it easy to connect to Webhooks (3Commas, Cornix, etc.) or mobile notifications.
Highly Adaptive: Fully customizable lookback periods, timeframe weights, and risk percentages.
How to Use:
Configure Timeframes: Set your 5 preferred TFs and their respective lookback periods in the inputs.
Define Risk: Adjust the Target Vol and Max Risk % to match your personal trading plan.
Filter Noise: Use the Score Threshold to fine-tune how much momentum is required to trigger a trade.
Pine Script®策略
aurora//@version=6
strategy("AURORA PRIME — MAX CAGR v3",
overlay=true,
initial_capital=100000,
pyramiding=2,
process_orders_on_close=true)
//----------------------------------------------------
// INPUTS
//----------------------------------------------------
baseRisk = input.float(0.6, "Base Risk %", step=0.1)
expRisk = input.float(0.9, "Expansion Risk %", step=0.1)
atrLen = input.int(14, "ATR Length")
stopATRmult = input.float(1.5, "Stop ATR Mult")
trailATRmult = input.float(2.0, "Trail ATR Mult")
adxLen = input.int(14, "ADX Length")
adxThresh = input.float(22, "ADX Trend Threshold")
volMult = input.float(1.5, "Volume Expansion Mult")
//----------------------------------------------------
// CORE INDICATORS
//----------------------------------------------------
atr = ta.atr(atrLen)
ema200 = ta.ema(close, 200)
// --- Manual ADX Calculation ---
upMove = high - high
downMove = low - low
plusDM = (upMove > downMove and upMove > 0) ? upMove : 0
minusDM = (downMove > upMove and downMove > 0) ? downMove : 0
trur = ta.rma(ta.tr(true), adxLen)
plusDI = 100 * ta.rma(plusDM, adxLen) / trur
minusDI = 100 * ta.rma(minusDM, adxLen) / trur
dx = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
adx = ta.rma(dx, adxLen)
volPower = volume / ta.sma(volume, 20)
volExpansion = volPower > volMult
trendRegime = adx > adxThresh
expansionRegime = trendRegime and volExpansion
// Structure bias (HTF)
htfClose = request.security(syminfo.tickerid, "60", close)
htfEMA = request.security(syminfo.tickerid, "60", ta.ema(close, 50))
bullBias = htfClose > htfEMA
bearBias = htfClose < htfEMA
//----------------------------------------------------
// ENTRY LOGIC
//----------------------------------------------------
longSignal = bullBias and trendRegime and close > ema200
shortSignal = bearBias and trendRegime and close < ema200
//----------------------------------------------------
// RISK ENGINE
//----------------------------------------------------
riskPct = expansionRegime ? expRisk : baseRisk
riskCash = strategy.equity * riskPct * 0.01
stopDist = atr * stopATRmult
qty = stopDist > 0 ? riskCash / stopDist : 0
//----------------------------------------------------
// EXECUTION
//----------------------------------------------------
longSL = close - stopDist
shortSL = close + stopDist
// 2R partial
longTP1 = close + stopDist * 2
shortTP1 = close - stopDist * 2
// ATR trail
trailLong = atr * trailATRmult
trailShort = atr * trailATRmult
if longSignal and strategy.position_size <= 0
strategy.entry("AURORA", strategy.long, qty)
strategy.exit("TP1", "AURORA", qty_percent=50, limit=longTP1)
strategy.exit("Trail", "AURORA", stop=longSL, trail_points=trailLong)
if shortSignal and strategy.position_size >= 0
strategy.entry("AURORA", strategy.short, qty)
strategy.exit("TP1", "AURORA", qty_percent=50, limit=shortTP1)
strategy.exit("Trail", "AURORA", stop=shortSL, trail_points=trailShort)
// Pyramiding logic
inLong = strategy.position_size > 0
inShort = strategy.position_size < 0
entryPrice = strategy.position_avg_price
unrealRLong = inLong ? (close - entryPrice) / stopDist : 0
unrealRShort = inShort ? (entryPrice - close) / stopDist : 0
if inLong and unrealRLong >= 1 and expansionRegime
strategy.entry("AURORA-ADD", strategy.long, qty)
if inShort and unrealRShort >= 1 and expansionRegime
strategy.entry("AURORA-ADD", strategy.short, qty)
plot(ema200, color=color.orange)
Pine Script®策略
DTFX Fusion Suite (Supertrend + QQE + FVG)A7 is a structure-driven trading strategy framework built around liquidity behavior
rather than indicator prediction.
Core sequence:
Sweep → First Return → Pullback → Reversal Trigger
Key concepts:
1. Trades are considered only after a clear liquidity sweep.
2. The system enforces a mandatory First Return, preventing chase entries.
3. Entries require a pullback followed by a reversal trigger
(Engulfing or Impulse candle).
4. Trend and regime filters are applied to avoid structurally adverse conditions.
About the 4H Heikin Ashi FVG:
- The 4H HA Fair Value Gap is used strictly as higher-timeframe visual context.
- It does NOT generate entries.
- It does NOT act as a buy/sell signal.
- Its purpose is environmental awareness and trade management context only.
Included components:
- Liquidity sweep state machine
- First Return time window constraint
- Pullback validation logic
- Engulf / Impulse reversal triggers
- EMA, Supertrend, and LWMA trend filters
- Structure-based stop and trailing exit logic
- 4H HA-FVG visualization (non-signal)
Important notice:
This script is provided for research and educational purposes only.
It does not constitute financial advice.
All parameters must be independently tested and adjusted per market and timeframe.
Pine Script v5
Pine Script®策略
Swing Strategy Feature Set S [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set S includes concepts beginning with the letter "S" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Schaff Trend Cycle
Sentiment Zone Oscillator
Stochastic Oscillator
Stochastic Relative Strength Index
Super Trend
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Above-Equal/Below Zero Filter
The above-equal/below zero filter is defined as an entry filter that evaluates zero centred indicator values relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the oscillator value is greater than or equal to zero.
"Below" returns true when the oscillator value is less than zero.
Close Above-Equal/Below Filter
The close price above-equal/below filter is defined as an entry filter that evaluates the most recent candle close price relative to a given time-series value and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the most recent candle close price is greater than or equal to any given time-series value.
"Below" returns true when the most recent candle close price is less than any given time-series value.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET S SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
As there are no built-in TradingView indicators for the STC and SZO values used in this script, code samples are provided in the relevant sections so that users can build their own Pine Script indicators.
For further information on how to build Pine Script indicators, please refer to:
www.tradingview.com
www.tradingview.com
Schaff Trend Cycle (STC) Filters
As there is no built-in indicator for the STC value used in this script, users can build their own STC indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Schaff Trend Cycle", shorttitle = "STC", overlay = false)
import TradingView/ta/12 as ta
stc_source = input.source(defval = close, title = 'STC Source', group = 'Schaff Trend Cycle (STC)')
stc_fast_length = input.int(defval = 23, minval = 1, title = 'STC Fast Length', group = 'Schaff Trend Cycle (STC)')
stc_slow_length = input.int(defval = 50, minval = 1, title = 'STC Slow Length', group = 'Schaff Trend Cycle (STC)')
stc_cycle_length = input.int(defval = 10, minval = 1, title = 'STC Cycle Length', group = 'Schaff Trend Cycle (STC)')
stc_d1_length = input.int(defval = 3, minval = 1, title = 'STC D1 Length', group = 'Schaff Trend Cycle (STC)')
stc_d2_length = input.int(defval = 3, minval = 1, title = 'STC D2 Length', group = 'Schaff Trend Cycle (STC)')
stc = ta.stc(stc_source, stc_fast_length, stc_slow_length, stc_cycle_length, stc_d1_length, stc_d2_length)
plot(stc, color = color.blue)
The STC indicator defaults are as follows:
Source is set to "Close".
Fast length is set to 23.
Slow length is set to 50.
Cycle length is set to 10.
D1 length is set to 3.
D2 length is set to 3.
Users can adjust the STC inputs via strategy Settings/Inputs/SCHAFF TREND CYCLE (STC).
The STC minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply STC above-equal is set to false.
STC above-equal threshold is set to 0.
Apply STC below-equal is set to false.
STC below-equal threshold is set to 100.
The STC minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The STC trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the STC filters and adjust filter parameters via strategy Settings/Inputs/STC FILTERS.
Sentiment Zone Oscillator (SZO) Filters
As there is no built-in indicator for the SZO value used in this script, users can build their own SZO indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Sentiment Zone Oscillator", shorttitle = "SZO", overlay = false)
import TradingView/ta/12 as ta
szo_source = input.source(defval = close, title = 'SZO Source', group = 'Sentiment Zone Oscillator (SZO)')
szo_length = input.int(defval = 14, minval = 1, title = 'SZO Length', group = 'Sentiment Zone Oscillator (SZO)')
szo = ta.szo(szo_source, szo_length)
plot(szo, color = color.blue)
The SZO indicator defaults are as follows:
Source is set to "Close".
Length is set to 14.
Users can adjust the SZO inputs via strategy Settings/Inputs/SENTIMENT ZONE OSCILLATOR (SZO).
The default mode for the SZO above-equal/below zero filter (see generic filters section above) is set to "None".
The SZO minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The SZO trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the SZO filters and adjust filter parameters via strategy Settings/Inputs/SZO FILTERS.
Stochastic Oscillator (SO) Filters
The SO indicator defaults are as follows:
Length is set to 14.
%K smoothing is set to 1.
%D smoothing is set to 3.
Users can adjust the SO inputs via strategy Settings/Inputs/STOCHASTIC OSCILLATOR (SO).
The SO %K above-equal/below %D filter is defined as an entry filter that evaluates the relative positioning of the SO %K and SO %D values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the SO %K above-equal/below %D filter is set to "None".
The SO %K minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply SO %K above-equal is set to false.
SO %K above-equal threshold is set to 0.
Apply SO %K below-equal is set to false.
SO %K below-equal threshold is set to 100.
The SO %D minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply SO %D above-equal is set to false.
SO %D above-equal threshold is set to 0.
Apply SO %D below-equal is set to false.
SO %D below-equal threshold is set to 100.
The SO %K minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The SO %D minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The SO %K trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
The SO %D trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the SO filters and adjust filter parameters via strategy Settings/Inputs/SO FILTERS.
Stochastic Relative Strength Index (SRSI) Filters
The SRSI indicator defaults are as follows:
Source is set to "Close".
RSI length is set to 14.
Stoch length is set to 14.
%K smoothing is set to 3.
%D smoothing is set to 3.
Users can adjust the SRSI inputs via strategy Settings/Inputs/STOCHASTIC RELATIVE STRENGTH INDEX (SRSI).
The SRSI %K above-equal/below %D filter is defined as an entry filter that evaluates the relative positioning of the SRSI %K and SRSI %D values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the SRSI %K above-equal/below %D filter is set to "None".
The SRSI %K minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply SRSI %K above-equal is set to false.
SRSI %K above-equal threshold is set to 0.
Apply SRSI %K below-equal is set to false.
SRSI %K below-equal threshold is set to 100.
The SRSI %D minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply SRSI %D above-equal is set to false.
SRSI %D above-equal threshold is set to 0.
Apply SRSI %D below-equal is set to false.
SRSI %D below-equal threshold is set to 100.
The SRSI %K minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The SRSI %D minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The SRSI %K trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
The SRSI %D trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the SRSI filters and adjust filter parameters via strategy Settings/Inputs/SRSI FILTERS.
Super Trend (ST) Filters
The ST indicator defaults are as follows:
ATR length is set to 10.
Factor (ATR multiplier) is set to 3.0.
Users can adjust the ST inputs via strategy Settings/Inputs/SUPER TREND (ST).
The default mode for the close above-equal/below ST filter (see generic filter section above) is set to "None".
Users can apply the ST filters via strategy Settings/Inputs/ST FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script®策略
Holy Grail by Linda Bradford Raschke Holy Grail - Linda Raschke (v6)
Trend-following pullback strategy inspired by Linda Bradford Raschke & Larry Connors' classic "Holy Grail" setup from Street Smarts: High Probability Short-Term Trading Strategies.
Captures high-probability continuations in strong trends by entering on low-risk pullbacks to the 20-period EMA after ADX confirms trend strength.
Overview:
This open-source Pine v6 strategy implements the famous "Holy Grail" setup — ironically named for its elegant simplicity. It uses only two core indicators (14-period ADX + 20-period EMA/SMA) to identify strong trends and enter on the resumption after a pullback. Designed for swing and intraday trading on trending instruments like indices (DAX, Dow, NQ, ES), forex majors, or stocks.
The strategy:
Filters for strong, rising trends (ADX > 30 and increasing)
Waits for price to touch the 20 MA during a retracement
Places simulated stop-entry orders (buy above high / sell below low of the touch bar)
Applies tight initial stops + ATR-based trailing to let winners run
Includes an additional exit when trend momentum fades (ADX < user-defined weak level)
Best suited for 15-min to daily timeframes in volatile, directional markets.
Concepts & Core Rules (from Street Smarts):
Trend Strength Filter : 14-period ADX must be > threshold (default 30) and rising (ADX > ADX ) to confirm a strong trend — avoids choppy/range-bound conditions.
Pullback Identification : In uptrends (close > MA), price retraces to touch the 20 MA (low ≤ MA). In downtrends (close < MA), price rallies to touch (high ≥ MA).
Entry : Buy-stop above the high of the pullback bar (longs) or sell-stop below the low (shorts) — simulates breakout confirmation of trend resumption.
Risk Management : Initial stop at the pullback bar's extreme (low for longs, high for shorts). Trailing stop activates using ATR multiplier.
Exits : No fixed targets — trail profits + close position if ADX falls below a "weak" level (default 25), indicating potential trend exhaustion.
This implementation adds modern touches: optional EMA vs SMA, ATR trailing, background trend coloring, and setup labels for easy visual confirmation.
How to Use :
Add to chart (works on any symbol/timeframe; best on trending ones like indices or forex).
Look for green background + "HG L" label (long setup) or red background + "HG S" label (short setup).
The strategy places orders on the next bar after a valid pullback — review backtest results in the Strategy Tester tab.
Adjust inputs for your market/timeframe (e.g., lower ADX threshold on lower timeframes if needed).
Important: This is not financial advice. Always backtest thoroughly, forward-test on demo, and use proper risk management (1-2% per trade max).
Inputs :
ADX Length (default 14)
ADX Threshold (default 30) — must exceed and rise
ADX Exit Weak (default 25) — closes when trend fades
EMA Length (default 20)
Use EMA instead of SMA (toggle)
Trailing ATR Multiplier (default 2.5)
ATR Length for trailing (default 14)
Plots & Visuals :
Orange 20 MA line
"HG L" / "HG S" labels on setup bars
Green/red background tint during strong trend conditions
Notes & Limitations :
Simulation Note: Pine Script cannot place persistent broker-style stop orders across bars; entries use limit ≈ stop-entry on the next bar (close approximation — many traders place manual stops in live trading).
Prefers first pullback after ADX rise (highest probability); later pullbacks may work but are not filtered here.
Performs best in trending, volatile conditions — avoid ranging/choppy markets (ADX filter helps).
No pyramiding (one position at a time); no fixed R:R targets (focus on trailing winners).
Backtest results vary by symbol/timeframe — optimize cautiously and avoid curve-fitting.
Inspired by public domain rules from Street Smarts (1996) — this is an independent adaptation with Pine v6 improvements for clarity and flexibility.
If you find this useful, consider liking/favoriting. Feedback welcome — happy to add alerts, fixed targets, or "first pullback only" logic in future updates!
Original open-source release — feel free to study/modify.
Pine Script®策略
Rishi Heikin-Ashi Trend High‑Level Purpose of Your Strategy
Your script is a Heikin‑Ashi trend‑following strategy that:
1. Enters trades when HA candles flip color
- Bullish flip → potential long
- Bearish flip → potential short
2. Confirms the flip using real‑price indicators
- EMA trend filter
- MACD histogram direction
- Optional RSI filter
3. Uses ATR‑based stop‑loss and take‑profit
- Risk‑based position sizing
- Optional exit on opposite HA flip
4. Adds visual clarity
- BUY/SELL tags
- Price labels
- Trend shading
- Performance label
It’s a complete, professional‑grade strategy.
Pine Script®策略
BB + EMA10 Confirm + Color Filldouble bollinger band with ema 10 ,when the candles go out of the band it reverses and wait for the candle to touch the middle bollinger band,when ema 10 crosses below or above buy and sell with green fill and red fill
Pine Script®策略
SmartDCA by TradeAkademiSmartDCA is a single-direction (Long or Short) step-based DCA strategy with adaptive take-profit and structured risk management.
All core parameters are fully user-configurable. The strategy logic does not enforce a fixed trading style; behavior depends entirely on user-selected settings.
General Structure
The strategy operates in one direction at a time (Long or Short).
All position management logic is applied relative to the selected direction.
The following components are fully controlled by the user:
Trade direction (Long / Short)
Entry model
Entry filters
Take-profit percentage
DCA distance percentage
TP/DCA increment scaling mode
Order size model
Maximum DCA steps
Risk management options
Exit model selection
The strategy plan is visualized either across the entire chart history or within a user-defined custom backtest date range.
Entry Configuration
Users can select the entry model:
Structural breakout
RSI reversal
Trend flip
None (manual disable)
Optional entry filters refine signal selection based on:
Reward space
Entry quality
RSI extremity
Fair value (VWMA)
Trend alignment
DCA & Position Scaling
After initial entry:
Additional DCA orders are triggered when price deviates from the average position price by the defined DCA percentage.
DCA distance and take-profit levels expand step-by-step according to the selected scaling mode.
Order size progression depends on the selected order size model.
Maximum DCA steps define the upper exposure limit.
This ensures the full theoretical risk is bounded and visible.
Exit Models
Users can choose the exit behavior:
Fixed take-profit
Structure-based exit
Adaptive Fast
Adaptive Slow
Protect Profit
Trend Ended
None
All exits are executed using market orders.
Additional Risk Controls
Optional risk features include:
DCA Compression (partial size reduction after recovery)
Defensive Profit Exit
Trend Soft Stop (breakeven protection after trend reversal)
These mechanisms are configurable and do not override the predefined maximum DCA limit.
Visualization & Reporting
The strategy provides:
Active position tracking
DCA step monitoring
Position notional transparency
Trend strength visualization
Historical DCA performance summary
Users may restrict execution to a custom backtest range or allow the strategy to operate across the full visible chart history.
Risk Disclosure
The maximum DCA step defines the full predefined risk envelope.
Strong and sustained one-directional trends may lead to full DCA utilization.
The strategy does not attempt unlimited recovery.
Users are responsible for configuring position sizing and DCA parameters relative to their capital.
This script is for educational and analytical purposes only and does not constitute investment advice.
Pine Script®策略
Linda Bradford Raschke Quantitative Trading JLKJ Formula█ OVERVIEW
This strategy implements a statistically-driven mean reversion system optimized for liquid instruments. It combines Bollinger Bands and Z-score analysis to identify statistically significant oversold/oversold conditions while employing institutional-grade risk management protocols.
█ CONCEPTS
The strategy operates on three core quantitative principles:
1 — Mean Reversion Detection: Identifies price extremes using a 20-period Bollinger Bands (2.0 std) combined with a Z-score threshold. Entries are triggered when price deviates beyond statistical norms.
2 — Adaptive Position Sizing: Implements a Kelly Criterion-based algorithm that dynamically adjusts exposure based on historical win rate, average win/loss ratio, and recent equity performance.
3 — Circuit Breakers: Features proprietary risk guards including Daily Loss Limits and Max Consecutive Losses. Trading automatically halts when predefined drawdown thresholds are met.
█ FEATURES
• Trend Filter: Optional EMA alignment (20/50) ensures mean reversion trades align with the broader trend.
• Volatility Filter: Automatically filters low/high volatility environments using ATR%.
• Dynamic Kelly Sizing: Starts conservatively (0.5% risk) and mathematically optimizes position size as trade history accumulates.
• Real-Time Dashboard: Displays Z-Score, Kelly %, Win Rate, Daily Loss %, and System Status.
• Compatibility: Works on all timeframes. Optimized for 5min–1h charts.
█ HOW TO USE
1. Apply the strategy to your chart (default settings are conservative).
2. Monitor the statistics table in the top-right corner.
3. The system trades automatically. Do not manually override signals.
4. Review the "Trading Status" indicator; if status is "HALTED", the circuit breakers are active.
█ LIMITATIONS
• This is a mean reversion strategy. It underperforms in strongly trending, low-volatility environments without pullbacks.
• Backtest results are hypothetical and do not guarantee future results.
• Sufficient trade history (20+ trades) is required for the Kelly formula to reach optimal sizing.
BACKTEST BEFORE USE.
Pine Script®策略
Swing Strategy Feature Set R [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set R includes concepts beginning with the letter "R" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Random Walk Index
Range Ratio
Rank Correlation Index
Rate of Change
Relative Strength Index
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET R SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
Random Walk Index (RWI) Filters
As there is no built-in indicator for the RWI values used in this script, users can build their own RWI indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Random Walk Index", shorttitle = "RWI", overlay = false)
import TradingView/ta/12 as ta
rwi_length = input.int(title = 'RWI Length', defval = 14, minval = 1, group = 'Random Walk Index (RWI)')
= ta.rwi(rwi_length)
plot(rwi_high, color = color.green)
plot(rwi_low, color = color.red)
For further information on how to build Pine Script indicators, please refer to:
www.tradingview.com
www.tradingview.com
By default, the RWI length is set to 14.
Users can adjust the RWI length via strategy Settings/Inputs/RANDOM WALK INDEX (RWI).
The RWI high above-equal/below RWI low filter is defined as an entry filter that evaluates the relative positioning of the RWI high and RWI low values and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the RWI high above-equal/below RWI low filter is set to "None".
The RWI high above-equal/below zero filter is defined as an entry filter that evaluates the RWI high value relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the RWI high above-equal/below zero filter is set to "None".
The RWI low above-equal/below zero filter is defined as an entry filter that evaluates the RWI low value relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the RWI low above-equal/below zero filter is set to "None".
The RWI bandwidth increasing/decreasing filter is defined as an entry filter that evaluates whether the distance between the RWI high and RWI low values is expanding or contracting over a configurable lookback period.
The default mode for the RWI bandwidth increasing/decreasing filter is set to "None".
The default RWI bandwidth increasing/decreasing lookback is set to 3.
The RWI high minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The RWI low minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The RWI high trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
The RWI low trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the RWI filters and adjust filter parameters via strategy Settings/Inputs/RWI FILTERS.
Range Ratio Filters
The range ratio value calculations used in this script are the same as those included in my retracement and extension ratios indicator. Link below:
For long trades, the range ratio filters evaluate swing low range ratios. Conversely, for short trades, the range ratio filters evaluate swing high range ratios.
The range ratio increasing/decreasing filter is defined as an entry filter that evaluates whether the most recent range ratio has expanded or contracted relative to the preceding value, invalidating trade signals that do not satisfy user-defined criteria.
The default mode for the range ratio increasing/decreasing filter is set to "None".
The range ratio minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply range ratio above-equal is set to false.
Range ratio above-equal threshold is set to 0.
Apply range ratio below-equal is set to false.
Range ratio below-equal threshold is set to 100.
Users can apply the range ratio filters and adjust filter parameters via strategy Settings/Inputs/RANGE RATIO FILTERS.
Rank Correlation Index (RCI) Filters
The RCI indicator defaults are as follows:
Source is set to "Close".
Length is set to 10.
Users can adjust the RCI inputs via strategy Settings/Inputs/RANK CORRELATION INDEX (RCI).
The RCI minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply RCI above-equal is set to false.
RCI above-equal threshold is set to -100.
Apply RCI below-equal is set to false.
RCI below-equal threshold is set to 100.
The RCI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The RCI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the RCI filters and adjust filter parameters via strategy Settings/Inputs/RCI FILTERS.
Rate of Change (ROC) Filters
The ROC indicator defaults are as follows:
Source is set to "Close".
Length is set to 9.
Users can adjust the ROC inputs via strategy Settings/Inputs/RATE OF CHANGE (ROC).
The ROC above-equal/below zero filter is defined as an entry filter that evaluates the ROC value relative to the zero line and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the ROC above-equal/below zero filter is set to "None".
The ROC minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The ROC trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the ROC filters and adjust filter parameters via strategy Settings/Inputs/ROC FILTERS.
Relative Strength Index (RSI) Filters
The RSI indicator defaults are as follows:
Source is set to "Close".
Length is set to 14.
Users can adjust the RSI inputs via strategy Settings/Inputs/RELATIVE STRENGTH INDEX (RSI).
The RSI minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply RSI above-equal is set to false.
RSI above-equal threshold is set to 0.
Apply RSI below-equal is set to false.
RSI below-equal threshold is set to 100.
The RSI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The RSI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the RSI filters and adjust filter parameters via strategy Settings/Inputs/RSI FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script®策略
INVESTOPIA CYCLE SIGNALThis is an advanced strategy script designed for traders who want to combine Long-term Market Cycles with Sniper Entries based on MACD and SMC concepts. It features a built-in "Accumulator Mode" for dynamic position sizing.
💎 Key Features:
1. Market Cycle Analysis (4 Phases) The strategy automatically identifies the market phase using Moving Average logic combined with Price Action, visualizing them as background colors:
🟡 Phase 1 (Accumulation): The "Smart Money" zone. The script looks for accumulation patterns.
🟢 Phase 2 (Markup): Strong uptrend. Ideal for trend-following.
🟠 Phase 3 (Distribution): Warning zone. Signals potential trend exhaustion.
🔴 Phase 4 (Markdown): Downtrend. The strategy avoids buying or minimizes risk here.
2. MACD Sniper Entry Instead of random buying, the strategy waits for specific "Sniper" conditions:
MACD Momentum confirmation.
SMC Filters: Integrates Fair Value Gaps (FVG) and Order Blocks (OB) visualization.
Discount Zone: Only looks for entries when the price pulls back to a discount level (fib levels).
3. Dynamic Money Management (Accumulator Mode)
Exponential Sizing: The strategy calculates the depth of the price dip relative to historical volatility.
Logic: The deeper the dip (within a bullish structure), the larger the calculated position size, aiming to optimize the average entry price.
⚠️ Risk Disclaimer & Usage
This strategy employs a dynamic sizing mechanism (referencing historical drawdowns). While this can enhance recovery during pullbacks, it carries a risk of higher drawdown during extended bearish markets.
Backtesting: Please use the Strategy Tester panel below to verify performance on your specific asset and timeframe before live trading.
Recommended for Spot trading or low-leverage Swing trading.
🔒 Access This is an Invite-Only script exclusively for Investopia members. Please contact me to request access.
Pine Script®策略
SVIS (Smart Volume Impact Strategy)SVIS is an algorithmic trading strategy designed to identify high-probability trend reversals and momentum shifts by analyzing the efficiency of volume distribution.
Core Mechanics :
Volume Efficiency Modeling : SVIS calculates the "Impact Delta" — a proprietary metric that measures how much price movement is actually backed by significant volume.
Multi-Asset Optimization : Features hardcoded, backtested presets for major cryptocurrencies (BTC, ETH, SOL etc.) and various timeframes.
Continuous Evolution : SVIS is regularly updated with new optimized presets for additional assets and timeframes, ensuring the strategy stays aligned with changing market conditions.
Key Advantages :
Minimized drawdown in choppy markets.
Dynamic signal generation based on volatility.
Fully compatible with automated trading engines via streamlined alerts.
Pine Script®策略
BETOttobre 2025The "Bet" is based on three fundamental technical components:
Extreme Responsiveness: Utilizing fast moving averages (SMA 5/13) to enter the market ahead of the competition.
Safety Shield: Capital protection set at €200.00, ensuring that the bet never wipes out the account.
Stress Management (Overthinking): A dynamic filter that closes positions when market "clarity" drops, protecting gains already achieved.
Pine Script®策略
V1 Long Trade EMA Elasticity Signal + Backtest🎯 Concept
This strategy exploits the elastic behavior between two EMAs (fast & slow). When price stretches too far below the slow EMA (like a rubber band), it tends to snap back — creating a high-probability long entry. When price stretches too far above, positions are closed for profit.
🔧 How It Works
Entry Logic (Long Only)
A buy signal triggers when the fast EMA (default: 3) drops below the slow EMA (default: 90) by a percentage threshold. This "elasticity gap" indicates an oversold stretch likely to revert.
Exit Logic — Profit-Guaranteed Close
Positions are only closed when:
The fast EMA crosses back above the slow EMA by the sell threshold
AND the candle's LOW is above entry price + a safety margin — ensuring real profit even with slippage
Adaptive ATR Filter
The entry/exit thresholds dynamically adjust to market volatility using ATR, preventing false signals in choppy markets and catching bigger moves in trending ones.
📊 Features
EMA Fan (Ribbon): Visual spread of intermediate EMAs between fast & slow — yellow = bullish, red = bearish
Multi-position pyramiding: Up to 50 simultaneous long entries, each independently tracked with unique IDs
Real-time info panel: Displays EMA values, elasticity gap %, open positions, ready/locked status, PnL, and win rate
Built-in filters (optional): EMA 200 trend filter, RSI oversold confirmation, volume filter, time-of-day filter
Color-coded zones: Green background = buy zone, red background = exit zone
⚙️ Key Parameters
ParameterDefaultDescriptionFast EMA3Reactive EMA for signal detectionSlow EMA90Anchor EMA for mean reversionBuy Threshold0.5%Min gap to trigger entrySell Threshold0.5%Min gap to trigger exitATR AdaptiveONAuto-adjusts thresholds to volatilityProfit Margin0.5%Safety buffer above entry price for exitsPosition Size5% equityPer-signal allocationMax Positions20Simultaneous open longs
💡 Best Use Cases
Crypto (BTC, ETH, altcoins) — high volatility = strong elastic snaps
Indices & Stocks — works on trending assets with regular pullbacks
Multiple timeframes — tested on 15m to Daily
⚠️ Notes
Long only — no short signals
Commission set at 0.04% (exchange-realistic for crypto)
Slippage: 1 tick
The profit margin check uses the candle LOW (worst case) to avoid paper profits that vanish on execution
All filters are OFF by default for maximum signal generation — enable them to increase selectivity
Pine Script®策略
Intraday Range Breakout Strategy (Research Tool)This script defines a configurable intraday price range and simulates breakout behavior using fixed risk parameters within the TradingView strategy framework.
Statistical outputs are derived exclusively from the built-in strategy engine and are presented for research and analytical purposes only.
Pine Script®策略
BTC 1h Donchian strat2 Inside BarThis strategy trades Bitcoin breakouts using a Donchian channel and filters entries with Kaufman’s Efficiency Ratio to avoid choppy conditions. Position size is based on a fixed percentage of equity risked per trade, with an ATR-based trailing stop and an additional hard stop for protection. It aims to capture strong directional moves while keeping drawdowns under control through adaptive risk management.
Pine Script®策略
Break-Retest-Scale [v1]Break of Structure (BOS) retest strategy with Thirds exit scaling (33/33/34%). Enters after price breaks and retests a swing level, then scales out at escalating R-multiples while moving to breakeven after TP1.
OVERVIEW
1 — BOS Detection : Price breaks above a swing high (bullish) or below a swing low (bearish)
2 — Retest Window : Strategy waits for price to return and test the broken level
3 — Entry : When price touches the retest zone and closes back on the right side
4 — Exit : Position is split into thirds with escalating profit targets
EXIT STRUCTURE (THIRDS PATTERN)
• TP1 : 33% at 1R — Stop stays at initial SL
• TP2 : 33% at 2R — Stop moves to breakeven
• TP3 : 34% at 3R — Stop at breakeven
After TP1 is hit, the stop automatically moves to breakeven (with a small ATR buffer to avoid stop-hunting wicks).
KEY FEATURES
• Split Pivot Detection : Separate left/right bars for swing significance vs detection speed
• Reclaim Modes : Three entry styles — Close, Wick Rejection, Full Bar (strictest)
• Volume Filter : Optional above-average volume requirement on BOS
• Frozen Brackets : SL and TP levels locked at entry — no ATR drift
• Smart BE Detection : Uses position reduction to detect TP1 hit
• Structure-Based SL : Stop placed below/above last swing with ATR floor
• BOS Max Age : Swing levels expire after N bars to prevent stale breakouts
VALIDATED RESULTS
• MYM 5min (Aug-Feb 2026): +56.6% | PF 2.10 | 52% win | 11.9% DD
• MES 5min (Dec-Feb 2026): +51.9% | PF 6.57 | 57.5% win | 7.3% DD
• M2K 5min (Dec-Feb 2026): +42.6% | PF 4.01 | 51.4% win | 7.2% DD
RECOMMENDED SETTINGS
MES 5min (Best Performance)
• Structure: Left=20, Right=2, Tol=0.2, Window=9, Age=20
• Reclaim Mode: Full Bar, Volume Filter: ON
• Risk: SL ATR Min=1.25, SL Buffer=0.2
• TP1/TP2/TP3: 0.7R / 1.5R / 4R
M2K 5min (Balanced)
• Structure: Left=16, Right=3, Tol=0.1, Window=11, Age=30
• Reclaim Mode: Close, Volume Filter: ON
• Risk: SL ATR Min=1.5, SL Buffer=0.1
• TP1/TP2/TP3: 1R / 3R / 3.5R
MYM 5min (Long-Bias)
• Structure: Left=16, Right=4, Tol=0.4, Window=15, Age=35
• Reclaim Mode: Close, Volume Filter: ON
• Risk: SL ATR Min=1.0, SL Buffer=0.2
• TP1/TP2/TP3: 1R / 1.5R / 2R
POSITION SIZING
With `strategy.fixed`, position size meaning varies by instrument:
• Futures : Contracts (3 = 3 contracts)
• FX : Units (30000 = 0.3 lots)
• Crypto : Coins (0.1 = 0.1 BTC)
• Stocks : Shares (100 = 100 shares)
NOTES
• Position size must be divisible by 3 for Thirds exit to work correctly
• For FX: use units (30000), not lots (0.3)
• Sunday filter enabled by default to avoid FX gaps
• The "look-ahead bias" warning is a false positive — uses `lookahead=barmerge.lookahead_off`
• Commission/slippage set for futures — adjust in Properties for your instrument
• Margin set to 5% ($500/contract on $10K) — adjust as needed
Not financial advice. Always backtest on your specific instrument and timeframe.
Pine Script®策略
Momentum Upon Clearing Candle WickA Continuation Strategy. Select for candle size by percentage of price movement. Following candles will take a position when price clears the wick of the large candle. Select the number of candles a potential trade is valid. Robust selection of take profit and stop loss conditions. Select window in which trades are valid. You can leave it open to any candle or you could narrow it to news candles or another specific time of day. Can be customized into a scalping strategy or as an attempt to capture larger portions of a move. Remember, smaller timeframes generate smaller candles and larger timeframes will generate more trades. Adjusting candle sizes and timeframes will require very different profit and loss settings to maximize the strategies potential.
No signals or information generated from this strategy is investment or trade advice. For entertainment purposes only. Code created with Gemini.
Pine Script®策略
Break-Retest-Scale [v1]Break-Retest-Scale is a Break of Structure (BOS) retest strategy that uses a Thirds exit pattern to scale out of winning trades while protecting profits.
How It Works
BOS Detection : Price breaks above a swing high (bullish) or below a swing low (bearish)
Retest Window : Strategy waits for price to return and test the broken level
Entry : When price touches the retest zone and closes back on the right side
Exit : Position is split into thirds with escalating profit targets
Exit Structure (Thirds Pattern)
Exit Size Target Stop After
TP1 33% 1R Initial SL
TP2 33% 2R Breakeven
TP3 34% 3R Breakeven
After TP1 is hit, the stop automatically moves to breakeven (with a small ATR buffer to avoid stop-hunting wicks).
Key Features
Split Pivot Detection : Separate left/right bars for swing significance vs detection speed
Reclaim Modes : Three entry styles - Close, Wick Rejection, Full Bar (strictest)
Volume Filter : Optional above-average volume requirement on BOS
Frozen Brackets : SL and TP levels are locked at entry - they don't drift with changing ATR
Smart BE Detection : Uses position reduction to detect TP1 hit (more reliable than price checks)
Structure-Based SL : Stop is placed below/above the last swing with an ATR floor for minimum distance
BOS Max Age : Swing levels expire after N bars to prevent stale breakouts
Validated Results
Instrument Period Net P&L PF Win % Max DD
MYM 5min Aug-Feb 2026 +56.6% 2.10 52% 11.9%
MES 5min Dec-Feb 2026 +51.9% 6.57 57.5% 7.3%
M2K 5min Dec-Feb 2026 +42.6% 4.01 51.4% 7.2%
Recommended Settings
MES 5min (Best Performance)
Structure: Left=20, Right=2, Tol=0.2, Window=9, Age=20
Reclaim Mode: Full Bar, Volume Filter: ON
Risk: SL ATR Min=1.25, SL Buffer=0.2
TP1/TP2/TP3: 0.7R / 1.5R / 4R
M2K 5min (Balanced)
Structure: Left=16, Right=3, Tol=0.1, Window=11, Age=30
Reclaim Mode: Close, Volume Filter: ON
Risk: SL ATR Min=1.5, SL Buffer=0.1
TP1/TP2/TP3: 1R / 3R / 3.5R
MYM 5min (Long-Bias)
Structure: Left=16, Right=4, Tol=0.4, Window=15, Age=35
Reclaim Mode: Close, Volume Filter: ON
Risk: SL ATR Min=1.0, SL Buffer=0.2
TP1/TP2/TP3: 1R / 1.5R / 2R
Multi-Instrument Position Sizing
With strategy.fixed , position size meaning varies by instrument type:
Instrument Position Size = Example
Futures Contracts 3 = 3 contracts
FX Units of base currency 30000 = 0.3 lots
Crypto Coins/tokens 0.1 = 0.1 BTC
Stocks Shares 100 = 100 shares
Important Notes
Position size must be divisible by 3 for Thirds exit to work correctly
For FX: use units (30000), not lots (0.3)
Sunday filter is enabled by default to avoid FX gaps
The "look-ahead bias" warning is a false positive - the strategy uses lookahead=barmerge.lookahead_off
Commission and slippage are set for futures - adjust in Properties for your instrument
Margin is set to 5% ($500 per contract on $10K account) - adjust in code or Properties if needed
Strategy logic is not meant to be financial advice. Always backtest on your specific instrument and timeframe.
Pine Script®策略
Trend Forge
Trend Forge is a fully configurable multi-trend strategy that lets you mix and match three independent trend indicators to define bullish and bearish market states. When all three trends align above price, the strategy enters long; when all three align below, it enters short. Every position is protected by an ATR-based stop loss, and trades close automatically when the trend alignment breaks down.
This script was converted from the original Bear & Bull Builder indicator I published into a back testable strategy with real entries, exits, and stop loss orders. It gives you access to TradingView's full Strategy Tester including equity curves, trade lists, and performance metrics.
How It Works
Trend Selection:
You choose three trend indicators independently, each with its own type and length:
- Trend 1 (default: EMA 21) — fast trend
- Trend 2 (default: EMA 55) — medium trend
- Trend 3 (default: SMA 89) — slow trend
Each trend slot supports five indicator types: EMA, SMA, RSI, CCI, and WaveTrend (WT). This gives you complete freedom to build a trend-following system tailored to your instrument and timeframe.
Entry Logic
Long Entry: Triggered on the first confirmed bar where price closes above all three trend values. The strategy enters long at market and simultaneously places an ATR-based stop loss order.
Short Entry: Triggered on the first confirmed bar where price closes below all three trend values. The strategy enters short at market with an ATR-based stop loss.
Stop Loss Calculation
The stop loss distance is calculated as:
`Stop Loss Distance = ATR(20) × Multiplier`
- For longs, the stop is placed below the highest of the three trend values at entry.
- For shorts, the stop is placed above the lowest of the three trend values at entry.
The ATR multiplier is user-adjustable (default: 2.5), letting you widen or tighten risk per trade based on volatility.
Exit Logic
Positions close via market order when the trend alignment condition that triggered the entry is no longer met — i.e., when price crosses back through one or more of the trend lines. If the stop loss is hit first, the strategy exits at the stop price instead.
---
Visual Features
All of the original indicator's visual overlays are preserved:
-Stop Loss Zones — shaded red regions between the entry level and the ATR stop loss, shown for longs and/or shorts (toggle on/off).
- Trend Zones — green-shaded areas that highlight when a bullish or bearish state is active.
- Signal-to-Order Fill Zones — a green zone that visualizes the one-bar delay between signal generation (bar close confirmation) and order execution (next bar open).
- Entry, Stop, and Exit Labels — price labels printed on the chart at entry, stop loss, and exit points with color coding (green = entry, orange = stop, cyan = exit). Toggleable for longs and shorts independently.
---
Settings Reference
| Group | Setting | Default | Description |
|-------|---------|---------|-------------|
| First Trend** | Trend Type | EMA | Indicator type for Trend 1 |
| First Trend** | Trend Length | 21 | Lookback period for Trend 1 |
| Second Trend | Trend 2 | EMA | Indicator type for Trend 2 |
| Second Trend | Trend Length | 55 | Lookback period for Trend 2 |
| Third Trend | Trend 3 | SMA | Indicator type for Trend 3 |
| Third Trend| Trend Length | 89 | Lookback period for Trend 3 |
| Stop Loss | ATR Multiplier | 2.5 | Multiplied by ATR(20) to set stop distance |
| Display | Long/Short Labels | Long on | Show entry, stop, and exit price labels |
| Display| Stop Loss Zones | Long on | Shade the region between entry and stop |
| Display | Trend Zones | Long on | Shade active bull/bear trend areas |
| Display | Signal-to-Order Zones | Long on | Show the fill delay visualization |
---
Strategy Properties
| Property | Value |
|----------|-------|
| Default Qty Type | 100% of equity |
| Initial Capital | 10,000 |
| Pyramiding | 0 (no stacking) |
| Order Fill | Next bar open |
| Bar Confirmation | Orders only on confirmed bars |
---
Usage Tips
- Start with the default EMA 21 / EMA 55 / SMA 89 combination and adjust from there.
- Pair faster trend lengths for scalping on lower timeframes, or slower lengths for swing trading on daily/weekly charts.
- Increase the ATR multiplier on volatile instruments to avoid premature stop outs; decrease it on stable instruments for tighter risk control.
- Use the Strategy Tester tab to compare different trend type and length combinations across your chosen symbol and timeframe.
- The WaveTrend and CCI options can provide earlier signals in ranging markets but may generate more whipsaws — backtest before committing.
---
Disclaimer
This strategy is provided for educational and backtesting purposes only. Past performance does not guarantee future results. Always validate with out-of-sample data and proper risk management before trading live capital.
Pine Script®策略
Reset Killer Reset Killer | Prop Firm Evaluation Engine
Reset Killer is a structured, discipline-first trading system built specifically for traders pursuing futures funded prop firm accounts.
This is not a breakout gamble.
This is not a high-frequency overtrading strategy.
This is not designed to chase volatility.
Reset Killer is engineered for controlled execution in evaluation environments.
Designed exclusively for:
NQ / MNQ on a 5-Minute Standard OHLC chart.
Built to Pass Evaluations
Most traders fail challenges because of:
• Overtrading
• Emotional entries
• No daily limits
• Lack of structure
• Revenge trading after drawdowns
Reset Killer addresses those failure points by enforcing:
• Initial balance unlock logic
• Structured zone-based entries
• Defined trailing methodology
• Hard-stop protection
• One-trade-per-day discipline
• Time-restricted execution
The objective is consistency, not adrenaline.
Designed for Safety & Control
This system prioritizes:
• Controlled risk
• Clean execution
• Limited daily exposure
• Structured confirmations before entry
It is built to reduce impulsive decision-making and eliminate common evaluation mistakes.
Integrated webhook support allows seamless execution from TradingView to NinjaTrader using CrossTrade.
Reset Killer is optimized exclusively for:
NQ / MNQ
5-Minute Standard OHLC charts
It is not intended for:
• ES
• CL
• GC
• Forex
• Crypto
Changing timeframe or market will alter performance characteristics.
Who This Is For
Reset Killer is for traders who:
• Want a structured approach to prop firm evaluations
• Prefer discipline over emotion
• Understand that risk management is everything
• Are focused on passing, not gambling
No strategy guarantees profit.
This system is designed to provide structure, control, and repeatability inside funded account environments.
Reset Killer
Built for evaluation discipline.
Pine Script®策略






















