OPEN-SOURCE SCRIPT
Range Trading Strategy

OVERVIEW
The Range Trading Strategy is a systematic trading approach that identifies price ranges
from higher timeframe candles or trading sessions, tracks pivot points, and generates
trading signals when range extremes are mitigated and confirmed by pivot levels.
CORE CONCEPT
The strategy is based on the principle that when a candle (or session) closes within the
range of the previous candle (or session), that previous candle becomes a "range" with
identifiable high and low extremes. When price breaks through these extremes, it creates
trading opportunities that are confirmed by pivot levels.
RANGE DETECTION MODES
1. HTF (Higher Timeframe) Mode:
2. Sessions Mode:
PIVOT DETECTION
Pivots are detected based on candle color changes (bullish/bearish transitions):
1. Pivot Low:
2. Pivot High:
IMPORTANT: There is always only ONE active pivot high and ONE active pivot low at any
given time. When a new pivot is created, it replaces the previous one.
RANGE CREATION
A range is created when:
Range Properties:
RANGE MITIGATION
A range extreme is considered "mitigated" when price interacts with it:
Mitigation can happen:
SIGNAL GENERATION
1. Pending Signals:
When a range extreme is mitigated, a pending signal is created:
a) BEARISH Pending Signal:
Signal Confirmation

b) BULLISH Pending Signal:
IMPORTANT: There is only ever ONE pending bearish signal and ONE pending bullish signal
at any given time. When a new pending signal is created, it replaces the previous one
of the same type.
2. Signal Confirmation:
- Bearish: Confirmed when price closes below the pivot low (confirmation level)
- Bullish: Confirmed when price closes above the pivot high (confirmation level)
- Upon confirmation, a trade is entered immediately
- The confirmation line is drawn from the pivot bar to the confirmation bar
TRADE EXECUTION
When a signal is confirmed:
1. Position Management:
2. Stop Loss:
4. Trade Comments:
SPECIAL RANGES
Special ranges are created when:
In these cases:
- The pivot value is stored in an array (storedPivotHighs or storedPivotLows)
- A "special range" is created with only ONE extreme:
* If pivotHigh < rangeHigh: Creates a range with rangeHigh = pivotLow, rangeLow = na
* If pivotLow > rangeLow: Creates a range with rangeLow = pivotHigh, rangeHigh = na
- Special ranges can generate signals just like normal ranges
- If a special range is mitigated on the creation bar or the next bar, it is removed
entirely without generating signals (prevents false signals)
Special Ranges

REVERSE ON STOP LOSS
When enabled, if a stop loss is hit, the strategy automatically opens a trade in the
opposite direction:
1. Long Stop Loss Hit:
2. Short Stop Loss Hit:
The reverse trade uses the same R:R ratio and respects the "Stop Loss Only" setting.
VISUAL ELEMENTS
1. Range Lines:
2. Confirmation Lines:
STRATEGY SETTINGS
1. Range Detection Mode:
2. Auto HTF:
3. Risk:Reward Ratio:
4. Stop Loss Only:
5. Reverse on Stop Loss:
6. Max Ranges to Display:
KEY FEATURES
1. Dynamic Pivot Tracking:
2. Range Lifecycle:
3. Signal Priority:
4. Position Management:
5. Time-Based Drawing:
USAGE NOTES
The strategy combines range identification, pivot tracking, and signal confirmation to
create a systematic approach to trading breakouts and reversals based on price structure, past performance does not in any way predict future performance
The Range Trading Strategy is a systematic trading approach that identifies price ranges
from higher timeframe candles or trading sessions, tracks pivot points, and generates
trading signals when range extremes are mitigated and confirmed by pivot levels.
CORE CONCEPT
The strategy is based on the principle that when a candle (or session) closes within the
range of the previous candle (or session), that previous candle becomes a "range" with
identifiable high and low extremes. When price breaks through these extremes, it creates
trading opportunities that are confirmed by pivot levels.
RANGE DETECTION MODES
1. HTF (Higher Timeframe) Mode:
- Automatically selects a higher timeframe based on the current chart timeframe
- Uses request.security() to fetch HTF candle data
- Range is created when an HTF candle closes within the previous HTF candle's range
- The previous HTF candle's high and low become the range extremes
2. Sessions Mode:
- - Divides the trading day into 4 sessions (UTC):
- * Session 1: 00:00 - 06:00 (6 hours)
- * Session 2: 06:00 - 12:00 (6 hours)
- * Session 3: 12:00 - 20:00 (8 hours)
- * Session 4: 20:00 - 00:00 (4 hours, spans midnight)
- - Tracks high, low, and close for each session
- - Range is created when a session closes within the previous session's range
- - The previous session's high and low become the range extremes
PIVOT DETECTION
Pivots are detected based on candle color changes (bullish/bearish transitions):
1. Pivot Low:
- Created when a bullish candle appears after a bearish candle
- Pivot low = minimum of the current candle's low and previous candle's low
- The pivot bar is the actual bar where the low was formed (current or previous bar)
2. Pivot High:
- Created when a bearish candle appears after a bullish candle
- Pivot high = maximum of the current candle's high and previous candle's high
- The pivot bar is the actual bar where the high was formed (current or previous bar)
IMPORTANT: There is always only ONE active pivot high and ONE active pivot low at any
given time. When a new pivot is created, it replaces the previous one.
RANGE CREATION
A range is created when:
- (HTF Mode) An HTF candle closes within the previous HTF candle's range AND a new HTF
- candle has just started
- (Sessions Mode) A session closes within the previous session's range AND a new session
- has just started
- Or Range Can Be Created when the Extreme of Another Range Gets Mitigated and We Have a Pivot low Just Above the Range Low or Pivot High just Below the Range High
Range Properties:
- rangeHigh: The high extreme of the range
- rangeLow: The low extreme of the range
- highStartTime: The timestamp when the range high was actually formed (found by looping
- backwards through bars)
- lowStartTime: The timestamp when the range low was actually formed (found by looping
- backwards through bars)
- highMitigated / lowMitigated: Flags tracking whether each extreme has been broken
- isSpecial: Flag indicating if this is a "special range" (see Special Ranges section)
RANGE MITIGATION
A range extreme is considered "mitigated" when price interacts with it:
- High is mitigated when: high >= rangeHigh (any interaction at or above the level)
- Low is mitigated when: low <= rangeLow (any interaction at or below the level)
Mitigation can happen:
- At the moment of range creation (if price is already beyond the extreme)
- At any point after range creation when price touches the extreme
SIGNAL GENERATION
1. Pending Signals:
When a range extreme is mitigated, a pending signal is created:
a) BEARISH Pending Signal:
- - Triggered when: rangeHigh is mitigated
- - Confirmation Level: Current pivotLow
- - Signal is confirmed when: close < pivotLow
- - Stop Loss: Current pivotHigh (at time of confirmation)
- - Entry: Short position
Signal Confirmation
b) BULLISH Pending Signal:
- - Triggered when: rangeLow is mitigated
- - Confirmation Level: Current pivotHigh
- - Signal is confirmed when: close > pivotHigh
- - Stop Loss: Current pivotLow (at time of confirmation)
- - Entry: Long position
IMPORTANT: There is only ever ONE pending bearish signal and ONE pending bullish signal
at any given time. When a new pending signal is created, it replaces the previous one
of the same type.
2. Signal Confirmation:
- Bearish: Confirmed when price closes below the pivot low (confirmation level)
- Bullish: Confirmed when price closes above the pivot high (confirmation level)
- Upon confirmation, a trade is entered immediately
- The confirmation line is drawn from the pivot bar to the confirmation bar
TRADE EXECUTION
When a signal is confirmed:
1. Position Management:
- - Any existing position in the opposite direction is closed first
- - Then the new position is entered
2. Stop Loss:
- - Bearish (Short): Stop at pivotHigh
- - Bullish (Long): Stop at pivotLow
- 3. Take Profit:
- - Calculated using Risk:Reward Ratio (default 2:1)
- - Risk = Distance from entry to stop loss
- - Target = Entry ± (Risk × R:R Ratio)
- - Can be disabled with "Stop Loss Only" toggle
4. Trade Comments:
- - "Range Bear" for short trades
- - "Range Bull" for long trades
SPECIAL RANGES
Special ranges are created when:
- - A range high is mitigated AND the current pivotHigh is below the range high
- - A range low is mitigated AND the current pivotLow is above the range low
In these cases:
- The pivot value is stored in an array (storedPivotHighs or storedPivotLows)
- A "special range" is created with only ONE extreme:
* If pivotHigh < rangeHigh: Creates a range with rangeHigh = pivotLow, rangeLow = na
* If pivotLow > rangeLow: Creates a range with rangeLow = pivotHigh, rangeHigh = na
- Special ranges can generate signals just like normal ranges
- If a special range is mitigated on the creation bar or the next bar, it is removed
entirely without generating signals (prevents false signals)
Special Ranges
REVERSE ON STOP LOSS
When enabled, if a stop loss is hit, the strategy automatically opens a trade in the
opposite direction:
1. Long Stop Loss Hit:
- - Detects when: position_size[1] > 0 AND position_size <= 0 AND low <= longStopLoss
- - Action: Opens a SHORT position
- - Stop Loss: Current pivotHigh
- - Trade Comment: "Reverse on Stop"
2. Short Stop Loss Hit:
- - Detects when: position_size[1] < 0 AND position_size >= 0 AND high >= shortStopLoss
- - Action: Opens a LONG position
- - Stop Loss: Current pivotLow
- - Trade Comment: "Reverse on Stop"
The reverse trade uses the same R:R ratio and respects the "Stop Loss Only" setting.
VISUAL ELEMENTS
1. Range Lines:
- - Drawn from the time when the extreme was formed to the mitigation point (or current
- time if not mitigated)
- - High lines: Blue (or mitigated color if mitigated)
- - Low lines: Red (or mitigated color if mitigated)
- - Style: SOLID
- - Width: 1
2. Confirmation Lines:
- - Drawn when a signal is confirmed
- - Extends from the pivot bar to the confirmation bar
- - Bearish: Red, solid line
- - Bullish: Green, solid line
- - Width: 1
- - Can be toggled on/off
STRATEGY SETTINGS
1. Range Detection Mode:
- - HTF: Uses higher timeframe candles
- - Sessions: Uses trading session boundaries
2. Auto HTF:
- - Automatically selects HTF based on current chart timeframe
- - Can be disabled to use manual HTF selection
3. Risk:Reward Ratio:
- - Default: 2.0 (2:1)
- - Minimum: 0.5
- - Step: 0.5
4. Stop Loss Only:
- - When enabled: Trades only have stop loss (no take profit)
- - Trades close on stop loss or when opposite signal confirms
5. Reverse on Stop Loss:
- - When enabled: Hitting a stop loss opens opposite trade with stop at opposing pivot
6. Max Ranges to Display:
- - Limits the number of ranges kept in memory
- - Oldest ranges are purged when limit is exceeded
KEY FEATURES
1. Dynamic Pivot Tracking:
- - Pivots update on every candle color change
- - Always maintains one high and one low pivot
2. Range Lifecycle:
- - Ranges are created when price closes within previous range
- - Ranges are tracked until mitigated
- - Mitigation creates pending signals
- - Signals are confirmed by pivot levels
3. Signal Priority:
- - Only one pending signal of each type at a time
- - New signals replace old ones
- - Confirmation happens on close of bar
4. Position Management:
- - Closes opposite positions before entering new trades
- - Tracks stop loss levels for reverse functionality
- - Respects pyramiding = 1 (only one position per direction)
5. Time-Based Drawing:
- - Uses time coordinates instead of bar indices for line drawing
- - Prevents "too far from current bar" errors
- - Lines can extend to any historical point
USAGE NOTES
- - Best suited for trending and ranging markets
- - Works on any timeframe, but HTF mode adapts automatically
- - Sessions mode is ideal for intraday trading
- - Pivot detection requires clear candle color changes
- - Range detection requires price to close within previous range
- - Signals are generated on bar close, not intra-bar
The strategy combines range identification, pivot tracking, and signal confirmation to
create a systematic approach to trading breakouts and reversals based on price structure, past performance does not in any way predict future performance
オープンソーススクリプト
TradingViewの精神に則り、この作者はスクリプトのソースコードを公開しているので、その内容を理解し検証することができます。作者に感謝です!無料でお使いいただけますが、このコードを投稿に再利用する際にはハウスルールに従うものとします。
免責事項
これらの情報および投稿は、TradingViewが提供または保証する金融、投資、取引、またはその他の種類のアドバイスや推奨を意図したものではなく、またそのようなものでもありません。詳しくは利用規約をご覧ください。
オープンソーススクリプト
TradingViewの精神に則り、この作者はスクリプトのソースコードを公開しているので、その内容を理解し検証することができます。作者に感謝です!無料でお使いいただけますが、このコードを投稿に再利用する際にはハウスルールに従うものとします。
免責事項
これらの情報および投稿は、TradingViewが提供または保証する金融、投資、取引、またはその他の種類のアドバイスや推奨を意図したものではなく、またそのようなものでもありません。詳しくは利用規約をご覧ください。