Jilly's Consolidation Breakout

jillyhatt · study · 524 行 · 点赞 32 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jillyhatt
 
//@version=6
// Consolidation Breakout
// Finds runs of bars with no appreciable new high or low, meaning nothing
// beyond m x ATR of a fixed anchor bar. Once a run reaches N bars it draws
// the range, and it signals when a bar closes beyond the anchor trigger.
// A run that grows taller than the width cap before it is confirmed is
// abandoned. Once confirmed, only a breakout close ends the box.
// The box top and bottom lock at the run's high and low on bar N. The first
// bar whose high (low) passes the locked top (bottom) turns that side dotted
// from there to the end of the box.
//
// Position tracking: a simulated position enters on each signal, tightens its
// k x ATR stop on repeat same-direction signals, reverses on opposite signals,
// and exits when the stop trades. The table reports that simulation; it is
// hypothetical and places no orders.
indicator("Jilly's Consolidation Breakout", "Consolidation BO", overlay = true, max_lines_count = 500, max_labels_count = 500,
     max_boxes_count = 500)
 
// INPUTS (logic first; everything that only changes what is drawn sits in
// Display and Color at the bottom)
int   atrLen   = input.int(14, "ATR Length", minval = 1)
float mult     = input.float(1.5, "m (ATR Multiple)", minval = 0.0, step = 0.1,
     tooltip = "Tolerance for an appreciable new high or low: a bar that trades more than m x ATR beyond the anchor bar's high or low ends the run. The same distance sets the breakout triggers.")
int   minBars  = input.int(5, "Minimum Bars N", minval = 2,
     tooltip = "Bars a run needs, anchor included, before it counts as a consolidation and its box is drawn.")
float capMult  = input.float(1.25, "Max Width (x ATR)", minval = 0.1, step = 0.25,
     tooltip = "A run whose high-to-low range grows past this many ATR before bar N is abandoned and a new run starts. ATR is frozen at the anchor bar. After confirmation the cap no longer applies.")
string trendMode = input.string("Monthly VWAP", "Trend Filter", options = ["Off", "EMA", "Monthly VWAP"], group = "Trade",
     tooltip = "Longs only when the close is above the line, shorts only when below. A blocked signal does nothing: no entry, no reversal, no stop tightening. Monthly VWAP = hlc3 VWAP anchored to the first session of each month. On a continuous futures chart (e.g. 1!), turn on back-adjustment (B-ADJ), or the roll gap distorts the VWAP for the rest of the roll month.")
int   trendLen = input.int(200, "Trend EMA Length", minval = 1, group = "Trade")
int   qty      = input.int(1, "Contracts", minval = 1, group = "Position",
     tooltip = "Position size for the simulated trades in the performance table, including the buy-and-hold rows.")
float stopMult = input.float(2.0, "Stop (x ATR)", minval = 0.1, step = 0.05, group = "Position",
     tooltip = "Initial stop: distance from the signal bar close, using the signal bar ATR. Used on entry and on reversal.")
bool  trailOn  = input.bool(true, "Tighten stop on repeat signals", group = "Position",
     tooltip = "A new signal in the trade's direction moves the stop to that bar's close -/+ 'Tighten to' x ATR, only if tighter.")
float trailMult = input.float(2.0, "Tighten to (x ATR)", minval = 0.1, step = 0.05, group = "Position",
     tooltip = "Distance used when a repeat signal tightens the stop: that bar's close -/+ this many ATR.")
float costRT   = input.float(0.0, "Cost per contract, round trip ($)", minval = 0.0, step = 0.01, group = "Position",
     tooltip = "Commission plus slippage deducted from every closed simulated trade, per contract. 0 = gross results. Example for MNQ: 1 tick of slippage each side ($0.50 x 2) plus your broker's round-trip commission.")
int   rollDays = input.int(8, "Roll warning (days before expiry)", minval = 0, group = "Futures Roll",
     tooltip = "Futures only. Marks the date this many days before the current contract's last trading day, and the 'Contract Roll' alert fires on the first bar on or after it. 8 days matches the usual CME equity index roll date (the Thursday before expiration week). The simulated position is not closed at the roll.")
bool  showRoll = input.bool(true, "Show roll date", group = "Futures Roll")
gD = "Display"
bool  showTrig = input.bool(true, "Show Trigger Lines", group = gD)
bool  showSig  = input.bool(true, "Show Signals", group = gD,
     tooltip = "Triangles on repeat signals (entries carry a label instead). With the Trend Filter on, a grey '✕ VWAP' or '✕ EMA' label marks a breakout the filter blocked.")
bool  showPos  = input.bool(true, "Show stop", group = gD)
bool   showLbl  = input.bool(true, "Show trade labels", group = gD,
     tooltip = "Entry, reversal and exit labels. Exit labels carry the simulated trade's net result.")
float  lblGap   = input.float(1.5, "Label distance (x ATR)", minval = 0.0, step = 0.25, group = gD,
     tooltip = "Gap between the bar and its label, so labels do not cover bars or lines. Longs enter below the bar and shorts above; a long's exit label sits below its exit bar and a short's above, so a reversal bar's exit and entry labels never stack.")
bool   showBox  = input.bool(true, "Show trade boxes", group = gD,
     tooltip = "While open: red risk box with a dashed outline from entry to the current stop, projected ahead and moved when the stop tightens; it disappears once the stop is past entry far enough that a stop-out cannot lose money after costs. At exit: green box from entry to the exit price for a winner, red box from entry to the exit (stop or gap fill) for a loser, with the net result in matching colour.")
int    boxLead  = input.int(5, "Box projection (bars ahead)", minval = 0, group = gD)
bool   showStats = input.bool(true, "Show performance table", group = gD,
     tooltip = "Hypothetical results of the simulated position on the loaded chart history: entry at the signal bar close, stop fills at the stop (or the bar's open if price gapped through), reversals at the signal close, less the cost input. No orders, no partial fills, no roll handling. Not indicative of future results.")
string statsPos = input.string("Top Right", "Table position", options = ["Top Left", "Top Right", "Top Center", "Middle Left", "Middle Right", "Bottom Left", "Bottom Right", "Bottom Center"], group = gD)
color colUp    = input.color(color.lime, "Long", inline = "c", group = "Color")
color colDn    = input.color(color.red, "Short", inline = "c", group = "Color")
color colBox   = input.color(color.gray, "Range", inline = "c", group = "Color")
color colTrend = input.color(color.orange, "Trend Line", inline = "t", group = "Color")
color colStop  = input.color(color.fuchsia, "Stop", inline = "t", group = "Color")
color colRoll  = input.color(color.yellow, "Roll", inline = "t", group = "Color")
 
float atr = ta.atr(atrLen)
 
// STATE
var float refHi      = na
var float refLo      = na
var float tol        = na
var float cap        = na
var float runHi      = na
var float runLo      = na
var int   count      = 0
var int   anchorIdx  = na
var line  upLine     = na
var line  dnLine     = na
var line  upTrigLine = na
var line  dnTrigLine = na
// Range locked on bar N, the dotted continuation of each side once a wick
// passes it, and the shading drawn as a borderless box.
var float boxHi      = na
var float boxLo      = na
var line  upDash     = na
var line  dnDash     = na
var box   fillBox    = na
 
bool longBreak  = false
bool shortBreak = false
 
if not na(atr)
    bool newAnchor = false
    if na(refHi)
        newAnchor := true
    else
        float upTrig = refHi + tol
        float dnTrig = refLo - tol
        if count >= minBars
            longBreak  := close > upTrig
            shortBreak := not longBreak and close < dnTrig
            newAnchor  := longBreak or shortBreak
        else
            bool tooWide = math.max(runHi, high) - math.min(runLo, low) > cap
            newAnchor := high > upTrig or low < dnTrig or tooWide
        if not newAnchor
            runHi := math.max(runHi, high)
            runLo := math.min(runLo, low)
            count += 1
            if count == minBars
                boxHi  := runHi
                boxLo  := runLo
                upLine := line.new(anchorIdx, boxHi, bar_index, boxHi, color = colBox, width = 2)
                dnLine := line.new(anchorIdx, boxLo, bar_index, boxLo, color = colBox, width = 2)
                fillBox := box.new(anchorIdx, boxHi, bar_index, boxLo, border_width = 0,
                     bgcolor = color.new(colBox, 85))
                if showTrig
                    upTrigLine := line.new(anchorIdx, upTrig, bar_index, upTrig, color = color.new(colUp, 40), style = line.style_dotted)
                    dnTrigLine := line.new(anchorIdx, dnTrig, bar_index, dnTrig, color = color.new(colDn, 40), style = line.style_dotted)
            else if count > minBars
                // The solid side stops at the last bar inside it; the dotted
                // side starts there, so the segment into the piercing bar is
                // already dotted and the switch shows even if the box ends on
                // the next bar.
                if na(upDash) and high > boxHi
                    upDash := line.new(bar_index - 1, boxHi, bar_index, boxHi, color = colBox, width = 2,
                         style = line.style_dotted)
                if na(dnDash) and low < boxLo
                    dnDash := line.new(bar_index - 1, boxLo, bar_index, boxLo, color = colBox, width = 2,
                         style = line.style_dotted)
                line.set_x2(na(upDash) ? upLine : upDash, bar_index)
                line.set_x2(na(dnDash) ? dnLine : dnDash, bar_index)
                box.set_right(fillBox, bar_index)
                if showTrig
                    line.set_x2(upTrigLine, bar_index)
                    line.set_x2(dnTrigLine, bar_index)
    if newAnchor
        refHi      := high
        refLo      := low
        tol        := mult * atr
        cap        := capMult * atr
        runHi      := high
        runLo      := low
        count      := 1
        anchorIdx  := bar_index
        upLine     := na
        dnLine     := na
        upTrigLine := na
        dnTrigLine := na
        boxHi      := na
        boxLo      := na
        upDash     := na
        dnDash     := na
        fillBox    := na
 
// SIGNALS (bar close only, so they do not repaint)
bool longRaw  = longBreak and barstate.isconfirmed
bool shortRaw = shortBreak and barstate.isconfirmed
 
// TREND FILTER: longs only above the trend line, shorts only below it.
// The line is the EMA or the monthly anchored VWAP. While it is na, the filter
// blocks every signal.
float trendEma  = ta.ema(close, trendLen)
float monthVwap = ta.vwap(hlc3, timeframe.change("1M"))
bool  useTrend  = trendMode != "Off"
float trendLine = trendMode == "EMA" ? trendEma : trendMode == "Monthly VWAP" ? monthVwap : na
bool  longSig   = longRaw and (not useTrend or close > trendLine)
bool  shortSig  = shortRaw and (not useTrend or close < trendLine)
 
// FUTURES ROLL: last trading day of the contract on the chart. On a single
// contract chart that is syminfo.expiration_date; on a continuous chart it is
// requested from the underlying contract. Only the current contract's date is
// known, so earlier rolls in the chart history are not marked.
string curContract = syminfo.current_contract
bool   isCont      = not na(curContract) and curContract != ""
string expTicker   = isCont ? (str.contains(curContract, ":") ? curContract : syminfo.prefix + ":" + curContract) : syminfo.tickerid
int    expiryT     = syminfo.type == "futures" ? request.security(expTicker, timeframe.period, syminfo.expiration_date, ignore_invalid_symbol = true) : na
int    rollT       = na(expiryT) ? na : expiryT - rollDays * 86400000
// First bar on or after the roll date.
bool   rollStart   = not na(rollT) and time >= rollT and (na(time[1]) or time[1] < rollT)
bool   inRollWin   = not na(rollT) and time >= rollT
string contractName = isCont ? curContract : syminfo.ticker
 
// POSITION TRACKING HELPERS
usd(float v) =>
    (v < 0 ? "−$" : "+$") + str.tostring(math.abs(v), "#,##0")
 
px(float p) =>
    str.tostring(p, format.mintick)
 
// up = label below the bar, pointing up at it; otherwise above, pointing down.
evLabel(string txt, color c, bool up) =>
    if showLbl
        label.new(bar_index, up ? low - lblGap * atr : high + lblGap * atr, txt, style = up ? label.style_label_up : label.style_label_down,
             color = c, textcolor = color.white, size = size.small)
 
posFromStr(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Right"     => position.top_right
        "Top Center"    => position.top_center
        "Middle Left"   => position.middle_left
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Right"  => position.bottom_right
        "Bottom Center" => position.bottom_center
        =>                 position.bottom_right
 
fPct(int w, int n) =>
    n > 0 ? str.tostring(100.0 * w / n, "#.#") + "%" : "—"
 
// Average net result per closed trade.
fExp(float net, int n) =>
    n > 0 ? usd(net / n) : "—"
 
fPF(float gp, float gl) =>
    gl > 0 ? str.tostring(gp / gl, "#.##") : gp > 0 ? "∞" : "—"
 
// varip so an intrabar stop exit latches across realtime ticks and is not
// rolled back; entries and stop changes happen on confirmed bars only.
varip int   posDir      = 0
varip float posStop     = na
varip float posEntryPx  = na
varip int   posEntryBar = -1
varip int   tradeNo     = 0
 
// Stop in force during this bar, latched on the bar's first tick so that an
// intrabar exit does not erase it from the plot. The trade number lets
// consecutive trades alternate between two plots, so their lines never join.
varip int   inForceBar   = -1
varip float inForceStop  = na
varip int   inForceTrade = 0
if inForceBar != bar_index
    inForceBar   := bar_index
    inForceStop  := posDir != 0 and bar_index > posEntryBar ? posStop : na
    inForceTrade := tradeNo
 
varip int   stopHitBar = -1
varip float stopHitPx  = na
 
// Closed-trade stats: varip because stop exits happen on intrabar ticks.
varip int   cntL = 0
varip int   cntS = 0
varip int   winL = 0
varip int   winS = 0
varip float gpL  = 0.0
varip float glL  = 0.0
varip float gpS  = 0.0
varip float glS  = 0.0
varip float eq   = 0.0
varip float eqPk = 0.0
varip float mdd  = 0.0
 
// Labels and box edits made on non-closing ticks are rolled back, so an
// intrabar exit buffers its label and box text here; both are drawn at the
// bar close.
varip string pendExitTxt = na
varip int    pendExitDir = 0
varip string pendBoxTxt  = na
varip float  pendBoxPnl  = 0.0
varip float  pendBoxExit = na
varip float  pendBoxEntry = na
var box slBox = na
 
// Buy and hold benchmark from the first trade's entry price (bar closes).
var float bhPx = na
var int   firstTradeT = na
var float bhPk = 0.0
var float bhDD = 0.0
 
// A trade closed on this execution, booked once below.
float  bookPnl = na
float  bookPx  = na
float  bookEnt = na
int    bookDir = 0
string bookWhy = ""
 
// 1) Stop: intrabar, from the bar after entry. The fill is the stop, or the
// bar's open if price gapped through it.
if posDir != 0 and bar_index > posEntryBar and (posDir == 1 ? low <= posStop : high >= posStop)
    float fill = posDir == 1 ? math.min(open, posStop) : math.max(open, posStop)
    bookPnl := (fill - posEntryPx) * posDir * syminfo.pointvalue * qty - costRT * qty
    bookPx  := fill
    bookEnt := posEntryPx
    bookDir := posDir
    bookWhy := "stop"
    stopHitBar := bar_index
    stopHitPx  := posStop
    posDir     := 0
    posStop    := na
 
// 2) Signals at bar close: open from flat, reverse, or tighten.
int  opened    = 0      // +1 / -1 when a trade opened on this bar
bool wasRev    = false
bool tightened = false
if longSig or shortSig
    int   dir     = longSig ? 1 : -1
    float newStop = close - dir * stopMult * atr
    if posDir == 0 or posDir == -dir
        if posDir == -dir
            bookPnl := (close - posEntryPx) * posDir * syminfo.pointvalue * qty - costRT * qty
            bookPx  := close
            bookEnt := posEntryPx
            bookDir := posDir
            bookWhy := "reverse"
            wasRev  := true
        posDir      := dir
        posStop     := newStop
        posEntryPx  := close
        posEntryBar := bar_index
        tradeNo     += 1
        opened      := dir
    else if trailOn
        float before = posStop
        float trailStop = close - dir * trailMult * atr
        posStop   := dir == 1 ? math.max(posStop, trailStop) : math.min(posStop, trailStop)
        tightened := posStop != before
 
// 3) Book the closed trade once.
if not na(bookPnl)
    if bookDir == 1
        cntL += 1
        if bookPnl > 0
            winL += 1
            gpL  += bookPnl
        else
            glL  += -bookPnl
    else
        cntS += 1
        if bookPnl > 0
            winS += 1
            gpS  += bookPnl
        else
            glS  += -bookPnl
    eq   += bookPnl
    eqPk := math.max(eqPk, eq)
    mdd  := math.max(mdd, eqPk - eq)
    pendExitTxt := "EXIT " + bookWhy + "  " + usd(bookPnl)
    pendExitDir := bookDir
    pendBoxTxt  := usd(bookPnl)
    pendBoxPnl  := bookPnl
    pendBoxExit := bookPx
    pendBoxEntry := bookEnt
 
// 4) At the bar close: draw the buffered exit label, then turn the trade's box
// into its result: green from entry to the exit price for a winner, red from
// entry to the exit (the stop, or the gap fill) for a loser, with the net
// result printed in the matching colour.
color winCol  = color.new(#00e676, 0)
color lossCol = color.new(#ff5252, 0)
if barstate.isconfirmed
    if not na(pendExitTxt)
        evLabel(pendExitTxt, pendBoxPnl > 0 ? color.new(color.green, 20) : color.new(color.red, 20), pendExitDir == 1)
        pendExitTxt := na
    if not na(pendBoxTxt) and not na(slBox)
        bool  won  = pendBoxPnl > 0
        box.set_right(slBox, bar_index)
        box.set_top(slBox, math.max(pendBoxEntry, pendBoxExit))
        box.set_bottom(slBox, math.min(pendBoxEntry, pendBoxExit))
        box.set_bgcolor(slBox, won ? color.new(color.green, 80) : color.new(color.red, 80))
        box.set_border_color(slBox, won ? color.new(color.green, 40) : color.new(color.red, 40))
        box.set_border_style(slBox, line.style_solid)
        box.set_text(slBox, pendBoxTxt)
        box.set_text_halign(slBox, text.align_center)
        // Longs print at the top of their box, shorts at the bottom.
        box.set_text_valign(slBox, pendExitDir == 1 ? text.align_top : text.align_bottom)
        box.set_text_color(slBox, won ? winCol : lossCol)
        box.set_text_size(slBox, size.small)
        slBox := na
    pendBoxTxt := na
 
// 5) New trade: label, a red risk box (entry to stop) with a dashed outline
// while open, benchmark anchor. The box turns green or red, outline solid, at exit.
// (Hidden early if the stop locks in a no-loss exit; see step 6.)
if opened != 0
    evLabel((wasRev ? "REV " : "") + (opened == 1 ? "▲ LONG " : "▼ SHORT ") + str.tostring(qty),
         opened == 1 ? color.new(color.teal, 0) : color.new(color.red, 0), opened == 1)
    if showBox
        slBox := box.new(bar_index, math.max(close, posStop), bar_index + boxLead, math.min(close, posStop),
             border_color = color.new(color.red, 50), bgcolor = color.new(color.red, 85),
             border_style = line.style_dashed)
    if na(bhPx)
        bhPx := close
        firstTradeT := time
 
// 6) Tightened stop: move the box edge (the stop line shows the new level).
// Once a fill at the stop would no longer lose money net of costs, there is
// no risk left to show, so the box goes invisible. It still turns into the
// green or red result box at exit, since step 4 sets its colours.
if tightened and not na(slBox)
    box.set_top(slBox, math.max(posEntryPx, posStop))
    box.set_bottom(slBox, math.min(posEntryPx, posStop))
    if (posStop - posEntryPx) * posDir * syminfo.pointvalue >= costRT
        box.set_bgcolor(slBox, color.new(color.red, 100))
        box.set_border_color(slBox, color.new(color.red, 100))
 
// 7) Keep the open trade's box projected ahead.
if barstate.isconfirmed and not na(slBox) and posDir != 0
    box.set_right(slBox, bar_index + boxLead)
 
if barstate.isconfirmed and not na(bhPx)
    float bhEqNow = (close - bhPx) * syminfo.pointvalue * qty
    bhPk := math.max(bhPk, bhEqNow)
    bhDD := math.max(bhDD, bhPk - bhEqNow)
 
// The stop line shows the stop in force on each bar, from the bar after entry
// through the bar it is hit. A tightened stop steps on the bar after the
// repeat signal. An X marks the level where a stop exit happened, so a trade
// stopped on its first bar is still visible.
plot(showPos and inForceTrade % 2 == 1 ? inForceStop : na, "Stop", colStop, 2, plot.style_steplinebr)
plot(showPos and inForceTrade % 2 == 0 ? inForceStop : na, "Stop (alternate trades)", colStop, 2, plot.style_steplinebr)
plot(showPos and stopHitBar == bar_index ? stopHitPx : na, "Stop Exit", colStop, 4, plot.style_cross)
 
// ROLL DATE: a vertical line at the roll date (ahead of the last bar until it
// passes) with the contract and its last trading day.
var line  rollLine = na
var label rollLbl  = na
if showRoll and barstate.islast and not na(rollT)
    line.delete(rollLine)
    label.delete(rollLbl)
    rollLine := line.new(rollT, high, rollT, low, xloc = xloc.bar_time, extend = extend.both, color = color.new(colRoll, 30),
         style = line.style_dashed)
    rollLbl := label.new(rollT, high + lblGap * atr, "Roll " + contractName + "\nexpires " + str.format_time(expiryT, "dd MMM", syminfo.timezone),
         xloc = xloc.bar_time, style = label.style_label_left, color = color.new(colRoll, 70), textcolor = color.white,
         size = size.small)
 
// PERFORMANCE TABLE: hypothetical, closed simulated trades net of the cost input.
var table statsTbl = na
if showStats and barstate.islast
    if not na(statsTbl)
        table.delete(statsTbl)
    statsTbl := table.new(posFromStr(statsPos), 4, 13, bgcolor = color.new(color.black, 20), border_width = 1,
         border_color = color.new(color.gray, 50))
    color hdrBg   = color.new(color.blue, 70)
    color lblBg   = color.new(color.black, 50)
    color txt     = color.white
    int   tot     = cntL + cntS
    int   wins    = winL + winS
    float netL    = gpL - glL
    float netS    = gpS - glS
    float openPnl = posDir != 0 ? (close - posEntryPx) * posDir * syminfo.pointvalue * qty : na
    float bhEq    = na(bhPx) ? na : (close - bhPx) * syminfo.pointvalue * qty
    table.cell(statsTbl, 0, 0, "Hypothetical results", text_color = txt, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 1, 0, "All",   text_color = txt, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 2, 0, "Long",  text_color = txt, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 3, 0, "Short", text_color = txt, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 0, 1, "Trades", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 1, str.tostring(tot),  text_color = txt, text_size = size.small)
    table.cell(statsTbl, 2, 1, str.tostring(cntL), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 3, 1, str.tostring(cntS), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 0, 2, "Win %", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 2, fPct(wins, tot),  text_color = txt, text_size = size.small)
    table.cell(statsTbl, 2, 2, fPct(winL, cntL), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 3, 2, fPct(winS, cntS), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 0, 3, "PF", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 3, fPF(gpL + gpS, glL + glS), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 2, 3, fPF(gpL, glL), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 3, 3, fPF(gpS, glS), text_color = txt, text_size = size.small)
    table.cell(statsTbl, 0, 4, "Expectancy", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 4, fExp(eq, tot),     text_color = eq >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 2, 4, fExp(netL, cntL),  text_color = netL >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 3, 4, fExp(netS, cntS),  text_color = netS >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 0, 5, "Net P&L", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 5, usd(eq),   text_color = eq >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 2, 5, usd(netL), text_color = netL >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 3, 5, usd(netS), text_color = netS >= 0 ? color.green : color.red, text_size = size.small)
    table.cell(statsTbl, 0, 6, "Max DD", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 6, "$" + str.tostring(mdd, "#,##0"), text_color = color.red, text_size = size.small)
    table.merge_cells(statsTbl, 1, 6, 3, 6)
    table.cell(statsTbl, 0, 7, "Open trade", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 7, na(openPnl) ? "flat" : (posDir == 1 ? "Long " : "Short ") + usd(openPnl) + "  (SL " + px(posStop) + ")",
         text_color = na(openPnl) ? txt : openPnl >= 0 ? color.green : color.red, text_size = size.small)
    table.merge_cells(statsTbl, 1, 7, 3, 7)
    table.cell(statsTbl, 0, 8, "B&H P&L", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 8, na(bhEq) ? "—" : usd(bhEq), text_color = na(bhEq) or bhEq >= 0 ? color.green : color.red,
         text_size = size.small)
    table.merge_cells(statsTbl, 1, 8, 3, 8)
    table.cell(statsTbl, 0, 9, "B&H Max DD", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 9, na(bhPx) ? "—" : "$" + str.tostring(bhDD, "#,##0"), text_color = color.red, text_size = size.small)
    table.merge_cells(statsTbl, 1, 9, 3, 9)
    table.cell(statsTbl, 0, 10, "First trade", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 10, na(firstTradeT) ? "—" : str.format_time(firstTradeT, "dd MMM yy HH:mm", syminfo.timezone),
         text_color = txt, text_size = size.small)
    table.merge_cells(statsTbl, 1, 10, 3, 10)
    table.cell(statsTbl, 0, 11, "Next roll", text_color = txt, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 11, na(rollT) ? "—" : contractName + "  roll " + str.format_time(rollT, "dd MMM yy", syminfo.timezone) +
         "  (exp " + str.format_time(expiryT, "dd MMM", syminfo.timezone) + ")",
         text_color = inRollWin ? colRoll : txt, text_size = size.small)
    table.merge_cells(statsTbl, 1, 11, 3, 11)
    table.cell(statsTbl, 0, 12, "Simulated: fills at signal close and stop, " + str.tostring(qty) + " contract(s), cost $" + str.tostring(costRT, "0.00") +
         " RT.\nNo orders placed. Past results do not predict future results.", text_color = color.new(color.gray, 0),
         text_size = size.tiny, text_halign = text.align_left)
    table.merge_cells(statsTbl, 0, 12, 3, 12)
plot(useTrend ? trendLine : na, "Trend Line", colTrend, 2)
// The entry label already marks a bar that opened or reversed a trade, so the
// triangle shows only on repeat signals (or on every signal if labels are off).
bool entryLbl = showLbl and opened != 0
plotshape(showSig and longSig and not entryLbl, "Long Breakout", shape.triangleup, location.belowbar, colUp, size = size.small)
plotshape(showSig and shortSig and not entryLbl, "Short Breakout", shape.triangledown, location.abovebar, colDn, size = size.small)
// A breakout the trend filter blocked: grey label where its triangle would be.
bool blockedL = longRaw and not longSig
bool blockedS = shortRaw and not shortSig
if showSig and (blockedL or blockedS)
    label.new(bar_index, close, "✕ " + (trendMode == "EMA" ? "EMA" : "VWAP"),
         yloc = blockedL ? yloc.belowbar : yloc.abovebar,
         style = blockedL ? label.style_label_up : label.style_label_down,
         color = color.new(color.gray, 30), textcolor = color.white, size = size.tiny)
 
alertcondition(longSig, "Long Breakout", "{{ticker}} consolidation breakout: long at {{close}}")
alertcondition(shortSig, "Short Breakout", "{{ticker}} consolidation breakout: short at {{close}}")
alertcondition(stopHitBar == bar_index, "Stop Exit", "{{ticker}} consolidation breakout: simulated stop hit")
alertcondition(rollStart, "Contract Roll", "{{ticker}}: contract roll date reached, expiry approaching. Roll or close open positions.")
 
// DATA WINDOW (Signal is the unfiltered breakout; Trade Signal is after the
// trend filter)
plot(atr, "ATR", display = display.data_window)
plot(longRaw ? 1 : shortRaw ? -1 : 0, "Signal", display = display.data_window)
plot(count, "Run Count", display = display.data_window)
plot(longSig ? 1 : shortSig ? -1 : 0, "Trade Signal", display = display.data_window)
plot(posDir, "Position", display = display.data_window)
plot(monthVwap, "Monthly VWAP", display = display.data_window)

← 返回列表