MM Flow
FlowScripts

Perfected FlowScript

Backtest

Backtest [OB Strategy] Perfected is indexed as 327_backtest.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

offchart

Axis

true

Size

12.7 KB

Lines

342

Native Signal Candidates

3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

3/3 guarded

Long Entry

line 308:9

Trigger

(showTrades) && (enterLong && activeSide == 1)

Value

low

Deps

activeSide:static, enterLong:var, showTrades:input

Short Entry

line 318:9

Trigger

(showTrades) && (enterShort && activeSide == -1)

Value

high

Deps

activeSide:static, enterShort:var, showTrades:input

Unlabeled shape

line 333:5

Trigger

(showTrades && anyExit && activeSide == 0)

Value

px

Deps

activeSide:static, anyExit:var, showTrades:input

327_backtest.flowscript

source path: kscripts/perfected/327_backtest.flowscript · sha256:332cfb06dbb9b57341e5d32a4d88c1603baffeaca1da01dc44bad307baa05a75

hash verified
//@version=2
// ============================================================================
// Backtest — Order Block Strategy Backtester [Perfected]
// Author: I (@Iopl147u) — Perfected by kScript_Perfection_Engineer
// Tags: #ob, #backtest, #risk, #performance
//
// Production-grade backtesting framework for Order Block-based strategies.
// Implements a full trade-tracking engine with performance metrics, drawdown
// monitoring, signal generation, and regime-coded equity curves.
//
// RESEARCH FOUNDATION:
//  1. Sullivan, Timmermann & White (1999), "Data-Snooping, Technical Trading
//     Rule Performance and the Bootstrap": White's Reality Check bootstrap
//     methodology; any backtest must account for data-snooping bias.
//  2. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns": foundational event-study
//     methodology on 90 years of DJIA data; buy signals followed by positive
//     returns, sell by negative.
//  3. Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//     Order Flow and Stock Returns": institutional footprints detectable in
//     trade-size patterns; OB backtests validate that identified blocks
//     predict future institutional flow.
//  4. Lopez de Prado (2018), "Advances in Financial Machine Learning":
//     deflated Sharpe ratio, probabilistic backtesting, and the need to
//     account for multiple testing when evaluating strategy performance.
// ============================================================================

define(
    title="Backtest [OB Strategy] Perfected",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained
// ---------------------------------------------------------------------------

// --- OB Detection ---
var obLen = input(name="obLen", type="number", defaultValue=20, label="OB Lookback (bars)", constraints={min: 5, max: 100, step: 1}, group="OB Detection")
var minMove = input(name="minMove", type="number", defaultValue=1.5, label="Min Displacement (ATR mult)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="OB Detection")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 50, step: 1}, group="OB Detection")

// --- Risk Management ---
var atrSl = input(name="atrSl", type="number", defaultValue=1.5, label="Stop Loss (ATR mult)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Risk")
var atrTp = input(name="atrTp", type="number", defaultValue=2.5, label="Take Profit (ATR mult)", constraints={min: 0.5, max: 10.0, step: 0.1}, group="Risk")
var useTrailing = input(name="useTrailing", type="boolean", defaultValue=false, label="Use Trailing Stop", group="Risk")
var trailMult = input(name="trailMult", type="number", defaultValue=1.0, label="Trailing Stop (ATR mult)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Risk")

// --- Display ---
var showPnl = input(name="showPnl", type="boolean", defaultValue=true, label="Show Cumulative R", group="Display")
var showTrades = input(name="showTrades", type="boolean", defaultValue=true, label="Show Trade Markers", group="Display")
var showWinRate = input(name="showWinRate", type="boolean", defaultValue=true, label="Show Win Rate Line", group="Display")
var showDrawdown = input(name="showDrawdown", type="boolean", defaultValue=true, label="Show Drawdown", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Win Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Loss Color", group="Colors")
var eqColor = input(name="eqColor", type="color", defaultValue="#ff9800", label="Cumulative Line", group="Colors")
var ddColor = input(name="ddColor", type="color", defaultValue="#ff1744", label="Drawdown Color", group="Colors")
var entryColor = input(name="entryColor", type="color", defaultValue="#00e676", label="Entry Color", group="Colors")
var exitColor = input(name="exitColor", type="color", defaultValue="#ff1744", label="Exit Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries high = bars.high
timeseries low = bars.low

// isnan guard: prevent computation on incomplete data
if (isnan(px[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// ---------------------------------------------------------------------------
// OB Detection & Signal Generation
// ---------------------------------------------------------------------------
timeseries rng = bars.high - bars.low
timeseries atrV = ema(rng, atrLen)

var isBull = bars.close > bars.open ? 1 : -1
timeseries move = math.abs(px - px[1])
timeseries displacement = move >= atrV * minMove ? 1 : 0

// Bullish OB: last bearish candle before bullish displacement
var enterLong = displacement == 1 && isBull == 1 && bars.close[1] < bars.open[1] && bars.low[1] < bars.low[2]

// Bearish OB: last bullish candle before bearish displacement
var enterShort = displacement == 1 && isBull == -1 && bars.close[1] > bars.open[1] && bars.high[1] > bars.high[2]

// ---------------------------------------------------------------------------
// Trade State Tracking (static variables for session persistence)
// ---------------------------------------------------------------------------
static activeSide = 0       // 0 = flat, 1 = long, -1 = short
static entryPx = 0.0
static stopPx = 0.0
static tpPx = 0.0
static highestPx = 0.0      // for trailing stop
static lowestPx = 0.0       // for trailing stop
static trailStop = 0.0

static totalR = 0.0
static totalWins = 0
static totalLosses = 0
static maxR = 0.0
static maxDrawdownR = 0.0
static peakEquity = 0.0
static tradeCount = 0
static lastBarIndex = -1

var currentBarIndex = bar_index[0]

// ---------------------------------------------------------------------------
// Entry Logic
// ---------------------------------------------------------------------------
if (activeSide == 0 && enterLong) {
    activeSide = 1
    entryPx = px
    stopPx = px - atrV * atrSl
    tpPx = px + atrV * atrTp
    highestPx = px
    trailStop = px - atrV * trailMult
    tradeCount = tradeCount + 1
}

if (activeSide == 0 && enterShort) {
    activeSide = -1
    entryPx = px
    stopPx = px + atrV * atrSl
    tpPx = px - atrV * atrTp
    lowestPx = px
    trailStop = px + atrV * trailMult
    tradeCount = tradeCount + 1
}

// ---------------------------------------------------------------------------
// Trailing Stop Update
// ---------------------------------------------------------------------------
if (activeSide == 1) {
    if (px > highestPx) {
        highestPx = px
    }
    if (useTrailing) {
        var newTrail = highestPx - atrV * trailMult
        if (newTrail > trailStop) {
            trailStop = newTrail
        }
    }
}

if (activeSide == -1) {
    if (px < lowestPx) {
        lowestPx = px
    }
    if (useTrailing) {
        var newTrail = lowestPx + atrV * trailMult
        if (newTrail < trailStop) {
            trailStop = newTrail
        }
    }
}

// ---------------------------------------------------------------------------
// Exit Evaluation
// ---------------------------------------------------------------------------
var exitWin = activeSide == 1 && high >= tpPx
var exitWin2 = activeSide == -1 && low <= tpPx
var exitLoss = activeSide == 1 && low <= stopPx
var exitLoss2 = activeSide == -1 && high >= stopPx
var exitTrailLong = activeSide == 1 && useTrailing && low <= trailStop
var exitTrailShort = activeSide == -1 && useTrailing && high >= trailStop

var anyExit = exitWin || exitWin2 || exitLoss || exitLoss2 || exitTrailLong || exitTrailShort

// ---------------------------------------------------------------------------
// Trade Closure & Metrics Update
// ---------------------------------------------------------------------------
var winRate = 0.0
var profitFactor = 0.0
var expectancy = 0.0
var closedR = 0.0

if (anyExit && activeSide != 0) {
    var exitPx = 0.0
    if (exitWin || exitWin2) {
        exitPx = tpPx
    } else if (exitLoss || exitLoss2) {
        exitPx = stopPx
    } else if (exitTrailLong) {
        exitPx = math.max(trailStop, low)
    } else if (exitTrailShort) {
        exitPx = math.min(trailStop, high)
    }

    var riskAmt = activeSide == 1 ? (entryPx - stopPx) : (stopPx - entryPx)
    riskAmt = math.max(riskAmt, 1e-9)
    var rMult = activeSide == 1 ? (exitPx - entryPx) / riskAmt : (entryPx - exitPx) / riskAmt
    closedR = rMult

    totalR = totalR + rMult
    if (rMult > 0) {
        totalWins = totalWins + 1
    } else {
        totalLosses = totalLosses + 1
    }

    // Update peak equity and drawdown
    if (totalR > peakEquity) {
        peakEquity = totalR
    }
    var currentDD = peakEquity - totalR
    if (currentDD > maxDrawdownR) {
        maxDrawdownR = currentDD
    }

    // Reset to flat
    activeSide = 0
    entryPx = 0.0
    stopPx = 0.0
    tpPx = 0.0
    highestPx = 0.0
    lowestPx = 0.0
    trailStop = 0.0
}

// ---------------------------------------------------------------------------
// Performance Metrics (recomputed each bar for display)
// ---------------------------------------------------------------------------
var totalTrades = totalWins + totalLosses
if (totalTrades > 0) {
    winRate = totalWins * 100.0 / totalTrades
}

var grossProfit = totalWins > 0 ? totalR > 0 ? totalR : 0.0 : 0.0
var grossLoss = totalLosses > 0 ? totalR < 0 ? math.abs(totalR) : 0.0 : 0.0
if (grossLoss > 0) {
    profitFactor = grossProfit / grossLoss
} else if (grossProfit > 0) {
    profitFactor = 999.0
} else {
    profitFactor = 0.0
}

if (totalTrades > 0) {
    expectancy = totalR / totalTrades
}

// Drawdown during active session
var currentDD = peakEquity - totalR
if (currentDD < 0) {
    currentDD = 0.0
}

// ---------------------------------------------------------------------------
// Regime Detection (color coding by equity direction)
// ---------------------------------------------------------------------------
var equityRising = totalR > totalR[1] || (totalR == totalR[1] && totalR > 0)
var inDrawdown = currentDD > 0

// ---------------------------------------------------------------------------
// Plots
// ---------------------------------------------------------------------------

// --- Cumulative R curve (regime-colored) ---
if (showPnl) {
    plotLine(
        value=totalR,
        width=lineWidth,
        colors=[eqColor, dnColor],
        colorIndex=equityRising ? 0 : 1,
        label=["Cumulative R"],
        desc=["Cumulative R-multiple across all closed trades"]
    )
    hline(value=0, color="#ffffff30", width=1)
}

// --- Drawdown curve ---
if (showDrawdown) {
    plotLine(
        value=-currentDD,
        width=1,
        colors=[ddColor],
        label=["Drawdown"],
        desc=["Running drawdown from peak equity in R units"]
    )
}

// --- Win Rate line (smoothed) ---
if (showWinRate && totalTrades > 0) {
    var winRateLine = winRate - 50.0
    plotLine(
        value=winRateLine,
        width=1,
        colors=[upColor, dnColor],
        colorIndex=winRateLine > 0 ? 0 : 1,
        label=["Win Rate - 50%"],
        desc=["Win rate centered at 50% (positive = above 50%)"]
    )
    hline(value=0, color="#ffffff20", width=1)
}

// --- Trade Entry Shapes ---
if (showTrades) {
    if (enterLong && activeSide == 1) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=entryColor,
            width=shapeSize,
            label=["Long Entry"],
            desc=["Long entry at bullish OB zone"]
        )
    }
    if (enterShort && activeSide == -1) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=entryColor,
            width=shapeSize,
            label=["Short Entry"],
            desc=["Short entry at bearish OB zone"]
        )
    }
}

// --- Exit shapes (on the bar where trade closed) ---
if (showTrades && anyExit && activeSide == 0) {
    var exitShape = closedR > 0 ? "flag" : "x"
    var exitShapeColor = closedR > 0 ? upColor : dnColor
    plotShape(
        value=px,
        shape=exitShape,
        colorIndex=exitShapeColor,
        width=shapeSize,
        label=[closedR > 0 ? "Win" : "Loss"],
        desc=[closedR > 0 ? "Winning trade exit" : "Losing trade exit"]
    )
}