OPEN-SOURCE SCRIPT

BOCS Adaptive

264
BOCS Adaptive Strategy - Automated Volatility Breakout System

WHAT THIS STRATEGY DOES:
This is an automated trading strategy that detects consolidation patterns through volatility analysis and executes trades when price breaks out of these channels. Take-profit and stop-loss levels are calculated dynamically using Average True Range (ATR) to adapt to current market volatility. The strategy closes positions partially at the first profit target and exits the remainder at the second target or stop loss.

TECHNICAL METHODOLOGY:

Price Normalization Process:
The strategy begins by normalizing price to create a consistent measurement scale. It calculates the highest high and lowest low over a user-defined lookback period (default 100 bars). The current close price is then normalized using the formula: (close - lowest_low) / (highest_high - lowest_low). This produces values between 0 and 1, allowing volatility analysis to work consistently across different instruments and price levels.

Volatility Detection:
A 14-period standard deviation is applied to the normalized price series. Standard deviation measures how much prices deviate from their average - higher values indicate volatility expansion, lower values indicate consolidation. The strategy uses ta.highestbars() and ta.lowestbars() functions to track when volatility reaches peaks and troughs over the detection length period (default 14 bars).

Channel Formation Logic:
When volatility crosses from a high level to a low level, this signals the beginning of a consolidation phase. The strategy records this moment using ta.crossover(upper, lower) and begins tracking the highest and lowest prices during the consolidation. These become the channel boundaries. The duration between the crossover and current bar must exceed 10 bars minimum to avoid false channels from brief volatility spikes. Channels are drawn using box objects with the recorded high/low boundaries.
Breakout Signal Generation:
Two detection modes are available:

Strong Closes Mode (default): Breakout occurs when the candle body midpoint math.avg(close, open) exceeds the channel boundary. This filters out wick-only breaks.
Any Touch Mode: Breakout occurs when the close price exceeds the boundary.

When price closes above the upper channel boundary, a bullish breakout signal generates. When price closes below the lower boundary, a bearish breakout signal generates. The channel is then removed from the chart.

ATR-Based Risk Management:
The strategy uses request.security() to fetch ATR values from a specified timeframe, which can differ from the chart timeframe. For example, on a 5-minute chart, you can use 1-minute ATR for more responsive calculations. The ATR is calculated using ta.atr(length) with a user-defined period (default 14).
Exit levels are calculated at the moment of breakout:

Long Entry Price = Upper channel boundary
Long TP1 = Entry + (ATR × TP1 Multiplier)
Long TP2 = Entry + (ATR × TP2 Multiplier)
Long SL = Entry - (ATR × SL Multiplier)

For short trades, the calculation inverts:

Short Entry Price = Lower channel boundary
Short TP1 = Entry - (ATR × TP1 Multiplier)
Short TP2 = Entry - (ATR × TP2 Multiplier)
Short SL = Entry + (ATR × SL Multiplier)

Trade Execution Logic:
When a breakout occurs, the strategy checks if trading hours filter is satisfied (if enabled) and if position size equals zero (no existing position). If volume confirmation is enabled, it also verifies that current volume exceeds 1.2 times the 20-period simple moving average.
If all conditions are met:

strategy.entry() opens a position using the user-defined number of contracts
strategy.exit() immediately places a stop loss order
The code monitors price against TP1 and TP2 levels on each bar

When price reaches TP1, strategy.close() closes the specified number of contracts (e.g., if you enter with 3 contracts and set TP1 close to 1, it closes 1 contract). When price reaches TP2, it closes all remaining contracts. If stop loss is hit first, the entire position exits via the strategy.exit() order.
Volume Analysis System:
The strategy uses ta.requestUpAndDownVolume(timeframe) to fetch up volume, down volume, and volume delta from a specified timeframe. Three display modes are available:

Volume Mode: Shows total volume as bars scaled relative to the 20-period average
Comparison Mode: Shows up volume and down volume as separate bars above/below the channel midline
Delta Mode: Shows net volume delta (up volume - down volume) as bars, positive values above midline, negative below

The volume confirmation logic compares breakout bar volume to the 20-period SMA. If volume ÷ average > 1.2, the breakout is classified as "confirmed." When volume confirmation is enabled in settings, only confirmed breakouts generate trades.
INPUT PARAMETERS:
Strategy Settings:

Number of Contracts: Fixed quantity to trade per signal (1-1000)
Require Volume Confirmation: Toggle to only trade signals with volume >120% of average
TP1 Close Contracts: Exact number of contracts to close at first target (1-1000)
Use Trading Hours Filter: Toggle to restrict trading to specified session
Trading Hours: Session input in HHMM-HHMM format (e.g., "0930-1600")

Main Settings:

Normalization Length: Lookback bars for high/low calculation (1-500, default 100)
Box Detection Length: Period for volatility peak/trough detection (1-100, default 14)
Strong Closes Only: Toggle between body midpoint vs close price for breakout detection
Nested Channels: Allow multiple overlapping channels vs single channel at a time

ATR TP/SL Settings:

ATR Timeframe: Source timeframe for ATR calculation (1, 5, 15, 60, etc.)
ATR Length: Smoothing period for ATR (1-100, default 14)
Take Profit 1 Multiplier: Distance from entry as multiple of ATR (0.1-10.0, default 2.0)
Take Profit 2 Multiplier: Distance from entry as multiple of ATR (0.1-10.0, default 3.0)
Stop Loss Multiplier: Distance from entry as multiple of ATR (0.1-10.0, default 1.0)
Enable Take Profit 2: Toggle second profit target on/off

VISUAL INDICATORS:

Channel boxes with semi-transparent fill showing consolidation zones
Green/red colored zones at channel boundaries indicating breakout areas
Volume bars displayed within channels using selected mode
TP/SL lines with labels showing both price level and distance in points
Entry signals marked with up/down triangles at breakout price
Strategy status table showing position, contracts, P&L, ATR values, and volume confirmation status

HOW TO USE:
For 2-Minute Scalping:
Set ATR Timeframe to "1" (1-minute), ATR Length to 12, TP1 Multiplier to 2.0, TP2 Multiplier to 3.0, SL Multiplier to 1.5. Enable volume confirmation and strong closes only. Use trading hours filter to avoid low-volume periods.
For 5-15 Minute Day Trading:
Set ATR Timeframe to match chart or use 5-minute, ATR Length to 14, TP1 Multiplier to 2.0, TP2 Multiplier to 3.5, SL Multiplier to 1.2. Volume confirmation recommended but optional.
For Hourly+ Swing Trading:
Set ATR Timeframe to 15-30 minute, ATR Length to 14-21, TP1 Multiplier to 2.5, TP2 Multiplier to 4.0, SL Multiplier to 1.5. Volume confirmation optional, nested channels can be enabled for multiple setups.
BACKTEST CONSIDERATIONS:

Strategy performs best during trending or volatility expansion phases
Consolidation-heavy or choppy markets produce more false signals
Shorter timeframes require wider stop loss multipliers due to noise
Commission and slippage significantly impact performance on sub-5-minute charts
Volume confirmation generally improves win rate but reduces trade frequency
ATR multipliers should be optimized for specific instrument characteristics

COMPATIBLE MARKETS:
Works on any instrument with price and volume data including forex pairs, stock indices, individual stocks, cryptocurrency, commodities, and futures contracts. Requires TradingView data feed that includes volume for volume confirmation features to function.
KNOWN LIMITATIONS:

Stop losses execute via strategy.exit() and may not fill at exact levels during gaps or extreme volatility
request.security() on lower timeframes requires higher-tier TradingView subscription
False breakouts inherent to breakout strategies cannot be completely eliminated
Performance varies significantly based on market regime (trending vs ranging)
Partial closing logic requires sufficient position size relative to TP1 close contracts setting

RISK DISCLOSURE:
Trading involves substantial risk of loss. Past performance of this or any strategy does not guarantee future results. This strategy is provided for educational purposes and automated backtesting. Thoroughly test on historical data and paper trade before risking real capital. Market conditions change and strategies that worked historically may fail in the future. Use appropriate position sizing and never risk more than you can afford to lose. Consider consulting a licensed financial advisor before making trading decisions.
ACKNOWLEDGMENT & CREDITS:

This strategy is built upon the channel detection methodology created by AlgoAlpha in the "Smart Money Breakout Channels" indicator. Full credit and appreciation to AlgoAlpha for pioneering the normalized volatility approach to identifying consolidation patterns and sharing this innovative technique with the TradingView community. The enhancements added to the original concept include automated trade execution, multi-timeframe ATR-based risk management, partial position closing by contract count, volume confirmation filtering, and real-time position monitoring.

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.