Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Indicators to Strategy Blueprint

Here is the transformation of the “Structure Retest Engine Delta Hybrid” indicator into a production-ready algorithmic trading framework.

1. Execution Triggers (Entry & Direction)

The core of this strategy is a “break and retest” of a market structure level, defined as a recent swing high or low. An entry is only considered after a “Change of Character” (CHoCH) establishes a new potential trend direction.

Execution Nuances & Signal Reversals

2. Multi-Tiered Exit Logic

The original indicator lacks any exit logic. A professional framework requires a dynamic and multi-faceted exit strategy to manage risk and secure profits.

3. Capital Allocation & Risk Management

Position sizing is the most critical component for long-term viability. We will move from the default fixed-quantity contract model to a dynamic risk-based model.

4. Implementation Snippet (Pine Logic)

This snippet demonstrates the conversion from an indicator to a strategy, incorporating the professional-grade components discussed above. It focuses on the new logic and assumes the core signal generation (bullEntry, bearEntry, activeLevel, etc.) from the original script remains intact.

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0.
//@version=5

// 1. STRATEGY DECLARATION with realistic friction and execution settings
strategy("Structure Retest Engine - Strategy", 
     overlay=true, 
     process_orders_on_close=true, // Execute on bar close for reliability
     commission_type=strategy.commission.percent, 
     commission_value=0.075, // Example commission
     slippage=2) // Example slippage in ticks

// ... [Keep all original inputs from the indicator] ...

// 2. NEW INPUTS FOR RISK AND EXIT MANAGEMENT
GRP_RISK = "Risk & Exit Management"
riskPercent    = input.float(1.0, "Risk Per Trade (%)", minval=0.1, maxval=10, step=0.1, group=GRP_RISK)
stopAtrMult    = input.float(2.0, "Stop Loss ATR Multiplier", minval=0.5, group=GRP_RISK)
tp1Rr          = input.float(1.5, "Take Profit 1 R:R", minval=0.5, group=GRP_RISK)
useTimeExit    = input.bool(true, "Use Time-Based Exit?", group=GRP_RISK)
maxBarsInTrade = input.int(100, "Max Bars in Trade", minval=10, group=GRP_RISK)

// ... [Keep all original logic for pivot detection, delta, state, and entry conditions] ...
// Assume 'bullEntry', 'bearEntry', 'activeLevel', 'activeDir', and 'atr' are calculated as before.

// 3. POSITION SIZING AND EXECUTION LOGIC
var float stopLossPrice = na
var float takeProfit1Price = na

// --- Bullish Entry Execution ---
if (bullEntry and strategy.position_size == 0)
    // Calculate Stop Loss and Take Profit levels AT THE TIME OF ENTRY
    stopLossPrice := activeLevel - (atr * stopAtrMult)
    entryPrice := close
    riskDistance := entryPrice - stopLossPrice
    takeProfit1Price := entryPrice + (riskDistance * tp1Rr)

    // Calculate Position Size based on risk
    riskAmount = strategy.equity * (riskPercent / 100)
    positionSize = riskAmount / riskDistance

    // Execute Orders
    strategy.entry("Long", strategy.long, qty=positionSize, comment="Bull Entry")
    // Set a two-stage exit: 50% at TP1, remainder managed by the second exit call
    strategy.exit("TP1/SL", from_entry="Long", qty_percent=50, limit=takeProfit1Price, stop=stopLossPrice)
    strategy.exit("SL2", from_entry="Long", stop=stopLossPrice) // Manages the stop for the second half

// --- Bearish Entry Execution ---
if (bearEntry and strategy.position_size == 0)
    // Calculate Stop Loss and Take Profit levels
    stopLossPrice := activeLevel + (atr * stopAtrMult)
    entryPrice := close
    riskDistance := stopLossPrice - entryPrice
    takeProfit1Price := entryPrice - (riskDistance * tp1Rr)

    // Calculate Position Size
    riskAmount = strategy.equity * (riskPercent / 100)
    positionSize = riskAmount / riskDistance

    // Execute Orders
    strategy.entry("Short", strategy.short, qty=positionSize, comment="Bear Entry")
    strategy.exit("TP1/SL", from_entry="Short", qty_percent=50, limit=takeProfit1Price, stop=stopLossPrice)
    strategy.exit("SL2", from_entry="Short", stop=stopLossPrice)

// 4. TRADE MANAGEMENT LOGIC (REVERSALS AND TIME EXITS)

// --- Reversal Exit: Close position if a CHoCH occurs in the opposite direction ---
isNewBearishChoch = bearishBreak and trendState[1] == 1
isNewBullishChoch = bullishBreak and trendState[1] == -1

if (strategy.position_size > 0 and isNewBearishChoch)
    strategy.close("Long", comment="Exit: Bearish CHoCH")

if (strategy.position_size < 0 and isNewBullishChoch)
    strategy.close("Short", comment="Exit: Bullish CHoCH")

// --- Time-Based Exit: Close if trade is open for too long ---
if (useTimeExit and strategy.position_size != 0)
    barsSinceEntry = bar_index - strategy.opentrades.entry_bar_index(0)
    if (barsSinceEntry > maxBarsInTrade)
        strategy.close_all(comment="Exit: Time Stop")

// --- EOD Exit: Close all positions at the end of the day (for intraday charts) ---
isNewDay = dayofweek != dayofweek[1]
if (isNewDay and timeframe.isintraday)
    strategy.close_all(comment="Exit: EOD")

// ... [Plotting logic can be adapted to show trades on chart using plotshape for strategy.opentrades, etc.] ...