Bastion Execution Protocol [JOAT] — Strategy by officialjackofalltrades

By officialjackofalltrades

Performance Metrics

Description

Bastion Execution Protocol [JOAT]IntroductionThe Bastion Execution Protocol is an open-source automated trading strategy built in Pine Script v6. It combines regime detection, market structure analysis, dual momentum confirmation (RSI + Stochastic Momentum Index), order flow validation (CVD), candle pattern recognition, session filtering, and dynamic risk management into a single institutional-grade execution framework. The strategy is designed to take high-confluence directional trades only when multiple independent factors align — regime, structure, momentum, volume flow, and session — while managing risk through ATR-based stop losses, configurable reward-to-risk ratios, trailing stops, regime-adaptive position sizing, daily trade limits, and end-of-day forced closes.This is not a "set and forget" black box. It is a transparent, fully configurable framework where every entry condition, risk parameter, and filter can be adjusted. The strategy is published open-source so traders can study the logic, understand why each trade is taken, and adapt the parameters to their instruments and timeframes.Why This Strategy ExistsMost published strategies on TradingView fall into two categories: overly simple (single indicator crossover) or overly complex (dozens of conditions that overfit to historical data). This strategy occupies the middle ground — it requires meaningful confluence from independent analytical dimensions without over-optimizing to specific historical patterns:Multi-Factor Entry Gate: Every trade requires agreement from regime detection, market structure, momentum oscillators, and optionally CVD order flow and candle patterns. No single factor can trigger a trade alone.Regime-Aware Execution: The strategy only trades in trending regimes by default. It avoids squeeze conditions and can be configured to require specific regime states. Position sizing automatically reduces in volatile or uncertain regimes.Session Intelligence: Trades are filtered by session (London, New York, Kill Zones) and day of week. The strategy avoids low-quality periods and forces position closure at end of day.Dynamic Risk Management: ATR-based stop losses adapt to current volatility. Trailing stops activate after a configurable profit threshold. Position sizing is calculated from account equity and risk percentage, then adjusted by regime conditions.Performance Tracking: Real-time HUD displays win rate, profit factor, max drawdown, daily trade count, and current position status.Strategy Architecture — 9 ModulesThe strategy is organized into 9 sequential modules, each responsible for a specific aspect of the trading process:Module 1: Regime DetectionThe regime engine classifies the market into four states using SMA alignment and VWAP slope:Trend Up: SMA 20 > 50 > 200 (bull alignment) AND positive VWAP slope — clear upward momentumTrend Down: SMA 20 = 70% of range and body >= 1.8x the 20-bar average body. These serve as entry triggers when all other conditions are met.Module 3: Momentum ConfirmationDual momentum confirmation requires both RSI and SMI to agree:RSI: Must be above the bull threshold (default 55) for longs, below the bear threshold (default 45) for shortsStochastic Momentum Index: Must be positive for longs, negative for shorts. The SMI measures where price sits relative to the midpoint of its recent range, double-smoothed for noise reduction.Both must agree — RSI bullish AND SMI bullish = momentum confirmed for longsModule 3B: CVD Order Flow ConfirmationWhen enabled, Cumulative Volume Delta must support the trade direction:Buy volume is estimated from bullish candles (close > open = full volume, otherwise proportional)Sell volume = total volume minus buy volumeCVD = cumulative sum of (buy volume - sell volume)CVD must be above its moving average for longs, below for shortsThis ensures that actual volume flow supports the intended trade directionModule 3C: Candle Pattern DetectionWhen enabled, the strategy detects institutional candle patterns as entry triggers:Bullish Engulfing: Current bullish candle fully engulfs the prior bearish candle's body, with volume above averageBearish Engulfing: Current bearish candle fully engulfs the prior bullish candle's body, with volume above averageBullish Pin Bar: Lower wick > 2x body, upper wick 2x body, lower wick bull threshold AND SMI > 0// 4. CVD above its MA (if enabled)// 5. Bar is confirmed (barstate.isconfirmed)// 6. Trade is allowed (daily limit, session, no squeeze)// 7. Trigger: displacement candle OR pattern OR price > SMA20 + VWAPExpand 3 linesThis multi-gate approach ensures that trades are only taken when regime, structure, momentum, volume flow, session, and a specific trigger all agree. The probability of a random signal passing all gates is very low, which is by design.Module 7: Risk CalculationsRisk is calculated dynamically for each trade:Stop Loss: ATR * configurable multiplier (default 1.5x) below entry for longs, above for shortsTake Profit: SL distance * reward-to-risk ratio (default 2.0x)Position Size: (Account Equity * Risk Percentage * Regime Multiplier) / SL DistanceRegime-Adaptive Sizing: When enabled, position size is reduced to 50% during squeeze conditions and 70% during non-trending conditions. Full size is used only in trending regimes.Module 8: Trade ExecutionEntries are executed using strategy.entry() with calculated position size. The strategy tracks active trade parameters (entry price, SL, TP) for trailing stop management.Module 9: Exit ManagementThree exit mechanisms operate simultaneously:Fixed SL/TP: strategy.exit() with the calculated stop loss and take profit levelsTrailing Stop: When enabled, activates after price moves a configurable multiple of R in profit (default 1.0R). The trail distance is ATR * configurable multiplier (default 1.0x). The trailing stop only moves in the favorable direction and replaces the fixed SL when it is tighter.End-of-Day Close: All positions are closed at the configured time to avoid overnight riskPerformance TrackingThe strategy tracks and displays real-time performance metrics:Win Rate: Wins / (Wins + Losses) as a percentageProfit Factor: Gross Profit / Gross Loss — values above 1.5 indicate a healthy edgeMax Drawdown: Peak-to-trough equity decline as a percentageNet P&L: Total net profit/lossDaily Trade Count: Current day's trades vs maximum allowedStrategy Settings and Backtesting NotesThe strategy is configured with realistic default parameters:Initial Capital: $100,000Default Position Size: 2% of equityRisk Per Trade: 1.5% (configurable)Commission: Not included by default — users should add commission appropriate to their broker in the strategy settingsSlippage: Not included by default — users should add slippage appropriate to their instrumentcalc_on_every_tick: false — the strategy only evaluates on confirmed bar closes to prevent repaintingcalc_on_order_fills: true — allows trailing stop updates on fill eventsImportant: Before evaluating backtest results, users should:Add realistic commission for their broker (e.g., $5 per trade for stocks, 0.1% for crypto)Add realistic slippage (e.g., 1-2 ticks for liquid instruments)Verify that the backtest period includes different market conditions (trending, ranging, volatile)Check that the number of trades is sufficient for statistical significance (100+ trades recommended)Understand that past performance does not guarantee future resultsInput ParametersRisk Management:Risk Per Trade %: Percentage of equity risked per trade (default: 1.5%)Reward:Risk Ratio: TP distance as multiple of SL distance (default: 2.0)SL ATR Multiplier: Stop loss distance as ATR multiple (default: 1.5)ATR Length: Period for ATR calculation (default: 14)Use Trailing Stop: Enable/disable trailing (default: true)Trail After X R Profit: Profit threshold to activate trail (default: 1.0R)Trail ATR Multiplier: Trail distance as ATR multiple (default: 1.0)Max Trades Per Day: Daily trade limit (default: 3)Regime-Adaptive Sizing: Reduce size in non-trending conditions (default: true)Regime Filter:VWAP Slope Lookback: Period for slope calculation (default: 20)Slope Threshold: Normalized threshold for trend detection (default: 0.12)Bollinger Length/Multiplier: BB parameters for squeeze detection (default: 20/2.0)Avoid Squeeze Entries: Skip entries during squeeze (default: true)Require Trend Regime: Only trade in trending conditions (default: true)Structure:Swing Lookback: Pivot detection length (default: 5)Displacement Min Body Ratio: Minimum body/range for displacement (default: 0.7)Displacement Body Multiplier: Minimum body vs average for displacement (default: 1.8)Momentum:RSI Length/Thresholds: RSI parameters (default: 14, bull 55, bear 45)SMI Lookback/Smoothing: SMI parameters (default: 13/25/2)Session Filter:Enable Session Filter: Toggle session-based trade gatingIndividual session toggles: NY KZ, London KZ, NY, LondonDay of week toggles: Monday through FridayForce Close End of Day: Toggle EOD position closureClose Hour/Minute: EOD close time (default: 15:45)Order Flow:CVD Confirmation: Require delta direction to match entry (default: true)CVD Lookback: Period for CVD moving average (default: 10)Candle Patterns:Use Pattern Confirmation: Enable pattern detection as entry trigger (default: true)Pattern Volume Multiplier: Minimum volume for pattern confirmation (default: 1.3x)How to Use This StrategyStep 1: Configure for Your InstrumentAdjust the ATR multiplier and displacement thresholds for your instrument's volatility. Add realistic commission and slippage in TradingView's strategy settings.Step 2: Set Your Risk ParametersChoose a risk percentage that matches your risk tolerance. The default 1.5% with 2:1 R:R is conservative. Adjust the trailing stop parameters based on your preference for locking in profits vs giving trades room.Step 3: Configure SessionsEnable the sessions relevant to your instrument. For US equities, NY KZ and NY Session are most relevant. For forex, both London and NY Kill Zones are important. Disable days you prefer not to trade.Step 4: Run the BacktestApply the strategy to your chart and review the backtest results. Check win rate, profit factor, max drawdown, and number of trades. Ensure results are realistic and not the product of overfitting.Step 5: Forward TestBefore trading live, run the strategy in paper trading mode for at least 2-4 weeks to verify that live performance matches backtest expectations.Best PracticesAlways add commission and slippage before evaluating backtest resultsThe strategy works best on liquid instruments with reliable volume dataHigher timeframes (15m+) produce fewer but higher-quality tradesThe multi-gate entry system means trades are infrequent by design — this is a feature, not a bugRegime-adaptive sizing is recommended — it automatically reduces exposure in uncertain conditionsThe daily trade limit prevents revenge trading and overexposureEnd-of-day forced close eliminates overnight gap risk for intraday strategiesMonitor the HUD during live trading for real-time regime, momentum, and session contextIf win rate drops below 40% or profit factor drops below 1.0, re-evaluate parameters for current market conditionsLimitationsThe strategy uses lagging indicators (SMAs, RSI, SMI) for entry conditions. Entries occur after the trend has started, not at the exact turn.Regime detection can lag regime changes. The strategy may miss the first portion of a new trend or take a trade just as a trend is ending.CVD is estimated from candle direction, not true order flow data. This is an approximation.Backtest results are hypothetical and do not account for real-world execution issues (partial fills, requotes, connectivity).The strategy is designed for intraday/swing trading. It is not optimized for scalping or long-term position trading.Session filtering is based on EST timezone. Instruments traded primarily in other timezones may need different session definitions.The multi-gate entry system can be too restrictive in some market conditions, producing very few trades. This is intentional — the strategy prioritizes quality over quantity.Past performance in backtesting does not guarantee future results. Market conditions change, and strategies that worked historically may not work in the future.Technical ImplementationBuilt with Pine Script v6 using:calc_on_every_tick=false for non-repainting executionbarstate.isconfirmed gating on all signal generation9-module architecture with clear separation of concernsATR-based dynamic stop loss and take profit calculationTrailing stop with configurable activation threshold and trail distanceRegime-adaptive position sizing with squeeze and non-trending penaltiesSession detection with timezone support and day-of-week filteringDaily trade counter with automatic resetEnd-of-day forced close mechanismReal-time performance tracking (win rate, profit factor, max drawdown)Dual momentum confirmation (RSI + SMI)CVD order flow validationCandle pattern detection (engulfing, pin bar) with volume confirmation6 alert conditions covering entries, regime changes, EOD close, patterns, and drawdownOriginality StatementThis strategy is original in its multi-dimensional confluence framework. While individual components (RSI, SMI, SMA alignment, session filtering) are established concepts, this strategy is justified because:The 9-module architecture creates a clear, auditable decision pipeline where each module's contribution to the final trade decision is transparentThe multi-gate entry system (regime + structure + dual momentum + CVD + session + trigger) requires an unusually high level of confluence, reducing false signalsRegime-adaptive position sizing automatically adjusts exposure based on market conditions, a feature rarely seen in published strategiesThe combination of trailing stops with regime-aware sizing creates a dynamic risk framework that adapts to changing conditionsSession filtering with Kill Zone preference and day-of-week controls provides institutional-grade time managementCVD order flow confirmation adds a volume-based validation layer that pure price-based strategies lackThe real-time HUD with performance tracking provides transparency into strategy behavior that most published strategies do not offerThe Volcanic theme provides a cohesive visual identity where every color choice carries meaning (lava = entry, amber = warning, teal = VWAP, crimson = bearish)DisclaimerThis strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Backtested results are hypothetical and do not represent actual trading. Past performance does not guarantee future results. The strategy involves risk of loss, including the potential loss of the entire investment. Commission, slippage, and other real-world execution costs are not included in the default configuration and must be added by the user for realistic evaluation. The author makes no claims about the profitability of this strategy and is not responsible for any losses incurred from its use. Always use proper risk management, trade with capital you can afford to lose, and consider consulting a qualified financial advisor before trading.-Made with passion by officialjackofalltrades

Browse all 5,900+ TradingView Pine Script strategies

View on TradingView