STA IFVG Entry Flashlight

lenorenagel · study · 628 行 · 点赞 77 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
// STA IFVG Entry Flashlight (indicator). A study and replay tool.
// Tracks one trade idea at a time from the IFVG engine:
//   fair value gap -> inversion on bar close -> limit entry at the broken edge
//   -> 2xATR stop -> TP1 1R / TP2 2R / TP3 3R -> stop to entry after +1R
//   -> flat at window end.
// Default window = 8:00-10:00 PM New York, Monday to Thursday.
// The table shows three direction reads (VWAP side, nearest 15m gap, 1H
// structure) as guidance only. They never block a trade. You decide.
// Intrabar order is unknown, so if a stop AND a target both sit inside one bar
// this indicator counts the stop first (the safe call). It acts on confirmed
// bars only, so prompts appear at the candle close.
//
// Developed and designed for members of the Sisterhood Trading Academy.
//
// For education and study. This script reports levels on a chart. It does not
// place orders, it is not financial advice, and nothing here is a claim about
// future results. Futures trading carries risk of loss.
// ============================================================================
indicator("STA IFVG Entry Flashlight", overlay=true, max_boxes_count=200, max_lines_count=400, max_labels_count=300)
 
// ───────────────────────── INPUTS ─────────────────────────
G1 = "Window"
// Four session windows. Tick the ones to trade; hours are editable (New York time; days 1=Sun..7=Sat).
sNYAM_on = input.bool(false, "NY AM", group=G1, inline="nyam")
sNYAM    = input.session("0930-1200:23456", "", group=G1, inline="nyam")
sNYPM_on = input.bool(false, "NY PM", group=G1, inline="nypm")
sNYPM    = input.session("1400-1530:23456", "", group=G1, inline="nypm")
sTK_on   = input.bool(true, "Tokyo", group=G1, inline="tk")
sTK      = input.session("2000-2200:2345", "", group=G1, inline="tk", tooltip="NY AM 9:30-12:00 Mon-Fri. NY PM 2:00-3:30 PM Mon-Fri. Tokyo 8-10 PM Mon-Thu. London 3:15-4:45 AM Mon-Fri. Tick any combination; a signal is taken if it falls inside any ticked window.")
sLDN_on  = input.bool(false, "London", group=G1, inline="ldn")
sLDN     = input.session("0315-0445:23456", "", group=G1, inline="ldn")
showShade = input.bool(true, "Shade the window", group=G1)
 
G2 = "IFVG engine (same as strategy)"
maxAge     = input.int(60, "Max hidden FVG age (bars)", minval=5, group=G2)
maxHidden  = input.int(120, "Hidden FVG memory", minval=10, group=G2)
atrLen     = input.int(14, "ATR length", minval=1, group=G2)
qMode      = input.string("Loose", "Quality filter", options=["Loose", "Balanced", "Strict"], group=G2)
dispCandle = input.string("Middle candle", "Displacement measured on", options=["Middle candle", "Third candle"], group=G2)
dirFilter  = input.string("Both", "Direction", options=["Both", "Long only", "Short only"], group=G2)
 
G3 = "Trade model (same as strategy)"
entryMode  = input.string("IFVG boundary (limit)", "Entry", options=["IFVG boundary (limit)", "Midpoint (limit)"], group=G3)
expiryBars = input.int(10, "Limit expiry (bars)", minval=1, group=G3)
slMult     = input.float(2.0, "Stop (x ATR)", minval=0.1, step=0.1, group=G3)
tpR        = input.float(3.0, "Target (R)", minval=0.25, step=0.25, group=G3)
useBE      = input.bool(false, "Breakeven rule (off by default)", group=G3, tooltip="Off by default: on gold 1m Tokyo, moving the stop to entry cost profit in testing. Turn it on to get a Move SL prompt after the trigger below.")
beTrigR    = input.float(1.0, "Breakeven trigger (R)", minval=0.1, step=0.1, group=G3)
 
G4 = "Display"
showFVGs    = input.bool(true, "Show live fair value gaps", group=G4)
maxFVGBoxes = input.int(6, "Max gaps shown", minval=1, maxval=30, group=G4)
keepTrades  = input.int(8, "Past trades kept on chart", minval=2, maxval=30, group=G4)
showStats   = input.bool(true, "Show info table", group=G4)
txtSize     = input.string("Normal", "Text size", options=["Small", "Normal", "Large"], group=G4)
tblPos      = input.string("Top right", "Table position", options=["Top right", "Top left", "Bottom right", "Bottom left"], group=G4)
showFVGText = input.bool(true, "Label gaps (timeframe + bull/bear bias)", group=G4)
keepPast    = input.bool(false, "Keep finished trades on chart (off = only the live trade shows)", group=G4)
showTPs     = input.bool(true, "Show TP1 / TP2 lines", group=G4)
tp1R        = input.float(1.0, "TP1 (R)", minval=0.1, step=0.25, group=G4)
tp2R        = input.float(2.0, "TP2 (R)", minval=0.1, step=0.25, group=G4)
 
G5 = "15m reference gap"
showRef   = input.bool(true, "Show 15m fair value gaps", group=G5)
refTF     = input.timeframe("15", "Reference timeframe", group=G5)
refMax    = input.int(4, "Max 15m gaps shown", minval=1, maxval=15, group=G5)
refLabel  = input.bool(true, "Label 15m gaps", group=G5)
 
G6 = "Direction guidance (display only)"
biasTF1H  = input.timeframe("60", "Structure timeframe", group=G6, tooltip="Shows whether this timeframe is making higher highs and lows (UP) or lower highs and lows (DOWN). Guidance only, it never blocks a trade.")
biasSw    = input.int(3, "Structure swing length (bars each side)", minval=1, group=G6)
 
G7 = "Alerts"
alertReady = input.bool(true, "Alert when READY BUY / READY SELL appears", group=G7, tooltip="To hear it: add ONE alert on this indicator (Alert button > Condition = this indicator > Any alert() function call), tick Play sound and pick a sound, then Create. Or pick READY BUY / READY SELL as separate conditions to give each its own sound. Alerts fire when the candle closes, same as the labels. They do not fire in replay.")
alertFill  = input.bool(false, "Alert when the limit fills (ENTRY)", group=G7)
alertMove  = input.bool(false, "Alert when it is time to move the stop to entry", group=G7)
 
// STA palette (same hex values as sta-fvg-locator.pine). Risk/reward boxes stay red/green on purpose.
color cOcean   = #18454E
color cMorning = #E08D2D
color cEvening = #E56F33
color cPaper   = #F6EDE7
color cBearB   = #F3492B
color cBearF   = #F1A3A4
color cGreen   = #2E6B4F
 
string lblSz = txtSize == "Small" ? size.tiny : txtSize == "Normal" ? size.small : size.normal
string tblSz = txtSize == "Small" ? size.small : txtSize == "Normal" ? size.normal : size.large
string beNote = useBE ? (beTrigR == tp1R ? "Move SL when TP1 hits" : "Move SL at " + str.tostring(beTrigR, "0.#") + "R") : ""
string tfTxt = timeframe.isminutes ? (timeframe.multiplier >= 60 ? str.tostring(timeframe.multiplier / 60) + "H" : str.tostring(timeframe.multiplier) + "m") : timeframe.period
// ───────────────────────── THRESHOLDS ─────────────────────────
float qGap   = qMode == "Loose" ? 0.15 : qMode == "Balanced" ? 0.25 : 0.40
float qBody  = qMode == "Loose" ? 0.40 : qMode == "Balanced" ? 0.50 : 0.60
float qRange = qMode == "Loose" ? 0.40 : qMode == "Balanced" ? 0.60 : 0.85
float qBuf   = qMode == "Loose" ? 0.00 : qMode == "Balanced" ? 0.05 : 0.10
 
float atrV    = ta.atr(atrLen)
float safeAtr = na(atrV) or atrV <= 0 ? syminfo.mintick : atrV
bool inNYAM = sNYAM_on and not na(time(timeframe.period, sNYAM, "America/New_York"))
bool inNYPM = sNYPM_on and not na(time(timeframe.period, sNYPM, "America/New_York"))
bool inTK   = sTK_on   and not na(time(timeframe.period, sTK,   "America/New_York"))
bool inLDN  = sLDN_on  and not na(time(timeframe.period, sLDN,  "America/New_York"))
bool inAny  = inNYAM or inNYPM or inTK or inLDN
bool inSess   = inAny
bool sessEnd  = not inSess and inSess[1]
float vw      = ta.vwap(hlc3)
int   biasNow = close >= vw ? 1 : -1
bgcolor(showShade and inSess ? color.new(cOcean, 92) : na)
 
f_qScore(float g, float b, float r) =>
    math.round(100.0 * (0.4 * math.min(g / 0.8, 1.0) + 0.3 * math.min(b, 1.0) + 0.3 * math.min(r / 1.5, 1.0)))
 
f_clean(line a, line b, line c, label d, label e, label f, line g, label h, label i) =>
    line.delete(a)
    line.delete(b)
    line.delete(c)
    label.delete(d)
    label.delete(e)
    label.delete(f)
    line.delete(g)
    label.delete(h)
    label.delete(i)
 
f_grade(int s) =>
    s >= 80 ? "A" : s >= 70 ? "B+" : s >= 60 ? "B" : "C"
 
// ───────────────────────── STATE ─────────────────────────
var array<float> rTop  = array.new_float()
var array<float> rBot  = array.new_float()
var array<int>   rDir  = array.new_int()
var array<int>   rAge  = array.new_int()
var array<int>   rBar  = array.new_int()
var array<float> rGap  = array.new_float()
var array<float> rBody = array.new_float()
var array<float> rRng  = array.new_float()
var array<box>   rBox  = array.new<box>()
var array<label> rLbl  = array.new<label>()
 
var array<line>  trLines  = array.new<line>()
var array<label> trLabels = array.new<label>()
var array<box>   trBoxes  = array.new<box>()
var int tradesDrawn = 0
 
var int   state = 0            // 0 none, 1 waiting for fill, 2 in trade
var int   dirT = 0
var int   biasSig = 0
var float entryPx = na
var float slPx0 = na
var float tpPx = na
var float tp1P = na
var float tp2P = na
var float riskV = na
var float curSL = na
var float invalLvl = na
var int   orderBar = na
var bool  beDone = false
var bool  closeNextOpen = false
var int   closeFlagBar = na
var line  eLine = na
var line  sLine = na
var line  tLine = na
var line  t1Line = na
var line  t2Line = na
var label sigLbl = na
var label eLbl = na
var label sLbl = na
var label tLbl = na
var label t1Lbl = na
var label t2Lbl = na
var box   riskBox = na
var box   rewBox = na
var string sigTxt = ""
var string lastTxt = "-"
var int   refNearSig = 0
var int   structSig = 0
 
var float netR = 0.0
var int nTrades = 0
var int nTP = 0
var int nSL = 0
var int nBE = 0
var int nWE = 0
var int nNoFill = 0
 
// displacement metrics for a gap that completes on THIS bar
float rng3 = math.max(high - low, syminfo.mintick)
float rng2 = math.max(high[1] - low[1], syminfo.mintick)
float body3 = math.abs(close - open) / rng3
float body2 = math.abs(close[1] - open[1]) / rng2
float dBody = dispCandle == "Middle candle" ? body2 : body3
float dRngAtr = (dispCandle == "Middle candle" ? rng2 : rng3) / safeAtr
bool bullFVG = low > high[2]
bool bearFVG = high < low[2]
 
// 15m reference gaps. Reads the LAST CLOSED 15m bar (no repaint): gap is bars [1],[2],[3] of the 15m series.
var array<float> fTop = array.new_float()
var array<float> fBot = array.new_float()
var array<int>   fDir = array.new_int()
var array<box>   fBox = array.new<box>()
var array<label> fLbl = array.new<label>()
string refTxt = timeframe.in_seconds(refTF) % 3600 == 0 ? str.tostring(timeframe.in_seconds(refTF) / 3600) + "H" : str.tostring(timeframe.in_seconds(refTF) / 60) + "m"
[rbi, rBull, rBear, rTopN, rBotN, rT0] = request.security(syminfo.tickerid, refTF, [bar_index[1], low[1] > high[3], high[1] < low[3], low[1] > high[3] ? low[1] : low[3], low[1] > high[3] ? high[3] : high[1], time[3]], lookahead=barmerge.lookahead_on)
bool newRef = rbi != rbi[1] and (rBull or rBear)
string biasTxt = timeframe.in_seconds(biasTF1H) % 3600 == 0 ? str.tostring(timeframe.in_seconds(biasTF1H) / 3600) + "H" : str.tostring(timeframe.in_seconds(biasTF1H) / 60) + "m"
 
// HH+HL = 1, LH+LL = -1, else 0. Read from the last CLOSED higher-timeframe bar only (no repaint).
f_bias(int len) =>
    float hp = ta.pivothigh(high, len, len)
    float lp = ta.pivotlow(low, len, len)
    var float sh1 = na
    var float sh0 = na
    var float sl1 = na
    var float sl0 = na
    if not na(hp)
        sh0 := sh1
        sh1 := hp
    if not na(lp)
        sl0 := sl1
        sl1 := lp
    int b = 0
    if not na(sh0) and not na(sl0)
        b := (sh1 > sh0 and sl1 > sl0) ? 1 : (sh1 < sh0 and sl1 < sl0) ? -1 : 0
    b
int struct1H = request.security(syminfo.tickerid, biasTF1H, f_bias(biasSw)[1], lookahead=barmerge.lookahead_on)
 
// Direction (1 bull, -1 bear, 0 none) of the live 15m gap whose middle is nearest to price.
f_nearDir(float px) =>
    int nd = 0
    float best = na
    if array.size(fTop) > 0
        for i = 0 to array.size(fTop) - 1
            float dm = math.abs(px - (array.get(fTop, i) + array.get(fBot, i)) / 2.0)
            if na(best) or dm < best
                best := dm
                nd := array.get(fDir, i)
    nd
 
bool readyBuyNow = false
bool readySellNow = false
bool fillNow = false
bool moveSLNow = false
 
if barstate.isconfirmed
    // ===================== 1) BROKER STEP (what the exchange would do on this bar) =====================
    bool closedNow = false
    float exitPx = na
    string resTxt = ""
    if state == 1 and bar_index > orderBar
        bool filledNow = dirT == 1 ? low <= entryPx : high >= entryPx
        if filledNow
            state := 2
            curSL := slPx0
            beDone := false
            fillNow := true
            if alertFill
                alert("🔔 ENTRY filled on " + syminfo.ticker + ". " + sigTxt + ". Stop " + str.tostring(slPx0, format.mintick) + ".", alert.freq_once_per_bar_close)
    if state == 2
        if closeNextOpen and bar_index > closeFlagBar
            closedNow := true
            exitPx := open
            resTxt := "WINDOW END"
        else
            bool hitSL = dirT == 1 ? low <= curSL : high >= curSL
            bool hitTP = dirT == 1 ? high >= tpPx : low <= tpPx
            if hitSL
                closedNow := true
                exitPx := curSL
                resTxt := beDone ? "BREAKEVEN" : "STOPPED"
            else if hitTP
                closedNow := true
                exitPx := tpPx
                resTxt := "TARGET"
    if closedNow
        float rM = (dirT == 1 ? exitPx - entryPx : entryPx - exitPx) / riskV
        netR += rM
        nTrades += 1
        if resTxt == "TARGET"
            nTP += 1
        else if resTxt == "STOPPED"
            nSL += 1
        else if resTxt == "BREAKEVEN"
            nBE += 1
        else
            nWE += 1
        color rc = rM > 0.05 ? color.new(color.green, 0) : rM < -0.05 ? color.new(color.red, 0) : color.new(color.gray, 0)
        lastTxt := sigTxt + "  " + resTxt + "  " + (rM >= 0 ? "+" : "") + str.tostring(rM, "0.0") + "R"
        f_clean(sLine, tLine, t1Line, sLbl, tLbl, sigLbl, t2Line, t1Lbl, t2Lbl)
        if keepPast
            label.set_text(eLbl, lastTxt)
            label.set_color(eLbl, rc)
            label.set_textcolor(eLbl, color.white)
            line.set_x2(eLine, bar_index)
            label.set_x(eLbl, bar_index + 1)
            box.set_right(riskBox, bar_index)
            box.set_right(rewBox, bar_index)
        else
            line.delete(eLine)
            label.delete(eLbl)
            box.delete(riskBox)
            box.delete(rewBox)
        state := 0
        closeNextOpen := false
 
    // ===================== 2) SCRIPT STEP (what the strategy decides at this bar close) =====================
    if sessEnd
        if state == 1
            f_clean(sLine, tLine, t1Line, sLbl, tLbl, sigLbl, t2Line, t1Lbl, t2Lbl)
            line.delete(eLine)
            label.delete(eLbl)
            box.delete(riskBox)
            box.delete(rewBox)
            nNoFill += 1
            state := 0
        else if state == 2
            closeNextOpen := true
            closeFlagBar := bar_index
 
    if state == 2 and useBE and not beDone
        bool beHit = dirT == 1 ? (high >= entryPx + riskV * beTrigR and close > entryPx) : (low <= entryPx - riskV * beTrigR and close < entryPx)
        if beHit
            curSL := entryPx
            beDone := true
            moveSLNow := true
            if alertMove
                alert("🔔 Move the stop to entry on " + syminfo.ticker + ". TP1 has closed. Entry " + str.tostring(entryPx, format.mintick) + ".", alert.freq_once_per_bar_close)
            line.set_y1(sLine, curSL)
            line.set_y2(sLine, curSL)
            line.set_color(sLine, cMorning)
            label.set_text(sLbl, "")
            label.set_color(sLbl, color.new(color.red, 100))
 
    if state == 1
        bool invalid = (dirT == 1 and close < invalLvl) or (dirT == -1 and close > invalLvl)
        if bar_index - orderBar >= expiryBars or invalid
            f_clean(sLine, tLine, t1Line, sLbl, tLbl, sigLbl, t2Line, t1Lbl, t2Lbl)
            line.delete(eLine)
            label.delete(eLbl)
            box.delete(riskBox)
            box.delete(rewBox)
            nNoFill += 1
            state := 0
 
    // ---- age / expire hidden gaps
    if array.size(rAge) > 0
        for i = 0 to array.size(rAge) - 1
            array.set(rAge, i, array.get(rAge, i) + 1)
        for i = array.size(rAge) - 1 to 0
            if array.get(rAge, i) > maxAge
                box bx0 = array.get(rBox, i)
                if not na(bx0)
                    box.delete(bx0)
                label lb0 = array.get(rLbl, i)
                if not na(lb0)
                    label.delete(lb0)
                array.remove(rTop, i)
                array.remove(rBot, i)
                array.remove(rDir, i)
                array.remove(rAge, i)
                array.remove(rBar, i)
                array.remove(rGap, i)
                array.remove(rBody, i)
                array.remove(rRng, i)
                array.remove(rBox, i)
                array.remove(rLbl, i)
 
    // ---- detect new gaps
    if bullFVG or bearFVG
        float gTop = bullFVG ? low : low[2]
        float gBot = bullFVG ? high[2] : high
        int   gDir = bullFVG ? 1 : -1
        color gc = gDir == 1 ? cOcean : cBearB
        color gf = gDir == 1 ? cOcean : cBearF
        box gb = showFVGs ? box.new(bar_index - 2, gTop, bar_index, gBot, xloc=xloc.bar_index, bgcolor=color.new(gf, 80), border_color=color.new(gc, 40), border_width=1) : na
        label gl = (showFVGs and showFVGText) ? label.new(bar_index + 1, (gTop + gBot) / 2.0, tfTxt + (gDir == 1 ? " BULL FVG" : " BEAR FVG"), xloc=xloc.bar_index, style=label.style_label_left, color=gf, textcolor=(gDir == 1 ? cPaper : cOcean), size=lblSz) : na
        array.push(rTop, gTop)
        array.push(rBot, gBot)
        array.push(rDir, gDir)
        array.push(rAge, 0)
        array.push(rBar, bar_index)
        array.push(rGap, (gTop - gBot) / safeAtr)
        array.push(rBody, dBody)
        array.push(rRng, dRngAtr)
        array.push(rBox, gb)
        array.push(rLbl, gl)
 
    while array.size(rTop) > maxHidden
        box bx1 = array.shift(rBox)
        if not na(bx1)
            box.delete(bx1)
        label lb1 = array.shift(rLbl)
        if not na(lb1)
            label.delete(lb1)
        array.shift(rTop)
        array.shift(rBot)
        array.shift(rDir)
        array.shift(rAge)
        array.shift(rBar)
        array.shift(rGap)
        array.shift(rBody)
        array.shift(rRng)
 
    // cap visible gap boxes, extend the rest
    int shown = 0
    if array.size(rBox) > 0
        for i = array.size(rBox) - 1 to 0
            box bx2 = array.get(rBox, i)
            if not na(bx2)
                shown += 1
                if shown > maxFVGBoxes
                    box.delete(bx2)
                    array.set(rBox, i, na)
                    label lb2 = array.get(rLbl, i)
                    if not na(lb2)
                        label.delete(lb2)
                        array.set(rLbl, i, na)
                else
                    box.set_right(bx2, bar_index)
                    label lb3 = array.get(rLbl, i)
                    if not na(lb3)
                        label.set_x(lb3, bar_index + 1)
 
    // ---- 15m reference gaps: add new, retire mitigated (close through the far edge), cap, extend
    if newRef
        color rc0 = rBull ? cOcean : cBearB
        color rf0 = rBull ? cOcean : cBearF
        box rb = showRef ? box.new(rT0, rTopN, time, rBotN, xloc=xloc.bar_time, bgcolor=color.new(rf0, 72), border_color=rc0, border_width=2, border_style=line.style_dashed) : na
        label rl = (showRef and refLabel) ? label.new(time, (rTopN + rBotN) / 2.0, refTxt + (rBull ? " BULL FVG" : " BEAR FVG"), xloc=xloc.bar_time, style=label.style_label_left, color=cMorning, textcolor=cOcean, size=lblSz) : na
        array.push(fTop, rTopN)
        array.push(fBot, rBotN)
        array.push(fDir, rBull ? 1 : -1)
        array.push(fBox, rb)
        array.push(fLbl, rl)
    if array.size(fTop) > 0
        for i = array.size(fTop) - 1 to 0
            bool gone = array.get(fDir, i) == 1 ? close < array.get(fBot, i) : close > array.get(fTop, i)
            bool over = array.size(fTop) - i > refMax
            if gone or over
                box fb0 = array.get(fBox, i)
                if not na(fb0)
                    box.delete(fb0)
                label fl0 = array.get(fLbl, i)
                if not na(fl0)
                    label.delete(fl0)
                array.remove(fTop, i)
                array.remove(fBot, i)
                array.remove(fDir, i)
                array.remove(fBox, i)
                array.remove(fLbl, i)
            else
                box fb1 = array.get(fBox, i)
                if not na(fb1)
                    box.set_right(fb1, time)
                label fl1 = array.get(fLbl, i)
                if not na(fl1)
                    label.set_x(fl1, time)
 
    // ---- inversion (newest first, every inverted gap is consumed)
    int   sigDir = 0
    float sigTop = na
    float sigBot = na
    int   sigQ = 0
    int   sigBar = na
    box   sigBox = na
    float buf = safeAtr * qBuf
    if array.size(rTop) > 0
        for i = array.size(rTop) - 1 to 0
            float t = array.get(rTop, i)
            float b = array.get(rBot, i)
            int   d = array.get(rDir, i)
            bool bullInv = d == -1 and close > t + buf
            bool bearInv = d == 1 and close < b - buf
            if bullInv or bearInv
                float g = array.get(rGap, i)
                float bd = array.get(rBody, i)
                float rg = array.get(rRng, i)
                bool pass = g >= qGap and bd >= qBody and rg >= qRange
                box bxi = array.get(rBox, i)
                if pass and sigDir == 0
                    sigDir := bullInv ? 1 : -1
                    sigTop := t
                    sigBot := b
                    sigBar := array.get(rBar, i)
                    sigQ := int(f_qScore(g, bd, rg))
                    sigBox := bxi
                else
                    if not na(bxi)
                        box.delete(bxi)
                label lbi = array.get(rLbl, i)
                if not na(lbi)
                    label.delete(lbi)
                array.remove(rTop, i)
                array.remove(rBot, i)
                array.remove(rDir, i)
                array.remove(rAge, i)
                array.remove(rBar, i)
                array.remove(rGap, i)
                array.remove(rBody, i)
                array.remove(rRng, i)
                array.remove(rBox, i)
                array.remove(rLbl, i)
 
    // ---- new order (only when flat, inside the window, direction allowed)
    bool dirOK = dirFilter == "Both" or (dirFilter == "Long only" and sigDir == 1) or (dirFilter == "Short only" and sigDir == -1)
    bool placed = false
    if sigDir != 0 and state == 0 and inSess and dirOK
        placed := true
        refNearSig := f_nearDir(close)
        structSig := struct1H
        dirT := sigDir
        entryPx := entryMode == "IFVG boundary (limit)" ? (sigDir == 1 ? sigTop : sigBot) : (sigTop + sigBot) / 2.0
        riskV := safeAtr * slMult
        slPx0 := sigDir == 1 ? entryPx - riskV : entryPx + riskV
        tpPx := sigDir == 1 ? entryPx + riskV * tpR : entryPx - riskV * tpR
        invalLvl := sigDir == 1 ? sigBot : sigTop
        curSL := slPx0
        orderBar := bar_index
        beDone := false
        closeNextOpen := false
        state := 1
        biasSig := biasNow
        float tp1Px = sigDir == 1 ? entryPx + riskV * tp1R : entryPx - riskV * tp1R
        float tp2Px = sigDir == 1 ? entryPx + riskV * tp2R : entryPx - riskV * tp2R
        tp1P := tp1Px
        tp2P := tp2Px
        color tpc = showTPs ? color.new(color.green, 30) : color.new(color.white, 100)
        color tpt = showTPs ? color.white : color.new(color.white, 100)
        color dc = cEvening
        riskBox := box.new(bar_index, math.max(entryPx, slPx0), bar_index + 1, math.min(entryPx, slPx0), xloc=xloc.bar_index, bgcolor=color.new(color.red, 85), border_color=color.new(color.red, 45), border_width=1)
        rewBox := box.new(bar_index, math.max(entryPx, tpPx), bar_index + 1, math.min(entryPx, tpPx), xloc=xloc.bar_index, bgcolor=color.new(color.green, 88), border_color=color.new(color.green, 45), border_width=1)
        eLine := line.new(bar_index, entryPx, bar_index + 1, entryPx, xloc=xloc.bar_index, color=cOcean, width=2)
        sLine := line.new(bar_index, slPx0, bar_index + 1, slPx0, xloc=xloc.bar_index, color=color.new(color.red, 0), width=2)
        tLine := line.new(bar_index, tpPx, bar_index + 1, tpPx, xloc=xloc.bar_index, color=color.new(color.green, 0), width=2)
        t1Line := line.new(bar_index, tp1Px, bar_index + 1, tp1Px, xloc=xloc.bar_index, color=tpc, style=line.style_dashed, width=1)
        t2Line := line.new(bar_index, tp2Px, bar_index + 1, tp2Px, xloc=xloc.bar_index, color=tpc, style=line.style_dashed, width=1)
        sigTxt := (sigDir == 1 ? "LONG " : "SHORT ") + str.tostring(entryPx, format.mintick) + " (" + f_grade(sigQ) + str.tostring(sigQ) + ")"
        sigLbl := label.new(bar_index, sigDir == 1 ? low : high, sigDir == 1 ? "READY BUY" : "READY SELL", xloc=xloc.bar_index, style=sigDir == 1 ? label.style_label_up : label.style_label_down, color=dc, textcolor=color.white, size=lblSz)
        readyBuyNow := sigDir == 1
        readySellNow := sigDir == -1
        if alertReady
            alert("🔔 READY " + (sigDir == 1 ? "BUY" : "SELL") + " on " + syminfo.ticker + ". Limit " + str.tostring(entryPx, format.mintick) + ", stop " + str.tostring(slPx0, format.mintick) + ". Check the table.", alert.freq_once_per_bar_close)
        eLbl := label.new(bar_index + 1, entryPx, "ENTRY" + (beNote != "" ? " - " + beNote : ""), xloc=xloc.bar_index, style=label.style_label_left, color=cPaper, textcolor=cOcean, size=lblSz)
        sLbl := label.new(bar_index + 1, slPx0, "SL", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.red, 0), textcolor=color.white, size=lblSz)
        t1Lbl := label.new(bar_index + 1, tp1Px, "TP1 " + str.tostring(tp1R, "0.#") + "R", xloc=xloc.bar_index, style=label.style_label_left, color=tpc, textcolor=tpt, size=lblSz)
        t2Lbl := label.new(bar_index + 1, tp2Px, "TP2 " + str.tostring(tp2R, "0.#") + "R", xloc=xloc.bar_index, style=label.style_label_left, color=tpc, textcolor=tpt, size=lblSz)
        tLbl := label.new(bar_index + 1, tpPx, "TP3 " + str.tostring(tpR, "0.#") + "R", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.green, 0), textcolor=color.white, size=lblSz)
        array.push(trLines, eLine)
        array.push(trLines, sLine)
        array.push(trLines, tLine)
        array.push(trLines, t1Line)
        array.push(trLines, t2Line)
        array.push(trBoxes, riskBox)
        array.push(trBoxes, rewBox)
        array.push(trLabels, sigLbl)
        array.push(trLabels, eLbl)
        array.push(trLabels, sLbl)
        array.push(trLabels, tLbl)
        array.push(trLabels, t1Lbl)
        array.push(trLabels, t2Lbl)
        tradesDrawn += 1
        if tradesDrawn > keepTrades
            for k = 0 to 4
                line.delete(array.shift(trLines))
            for k = 0 to 5
                label.delete(array.shift(trLabels))
            for k = 0 to 1
                box.delete(array.shift(trBoxes))
            tradesDrawn -= 1
    if sigDir != 0
        if not na(sigBox)
            box.delete(sigBox)
 
    // ---- keep the live trade drawn to the current bar
    if state != 0
        box.set_right(riskBox, bar_index)
        box.set_right(rewBox, bar_index)
        line.set_x2(eLine, bar_index)
        line.set_x2(sLine, bar_index)
        line.set_x2(tLine, bar_index)
        line.set_x2(t1Line, bar_index)
        line.set_x2(t2Line, bar_index)
        label.set_x(eLbl, bar_index + 1)
        label.set_x(sLbl, bar_index + 1)
        label.set_x(tLbl, bar_index + 1)
        label.set_x(t1Lbl, bar_index + 1)
        label.set_x(t2Lbl, bar_index + 1)
        if state == 1
            label.set_text(eLbl, "ENTRY" + (beNote != "" ? " - " + beNote : ""))
        else
            label.set_text(eLbl, "ENTRY" + (beDone ? " - MOVE SL" : (beNote != "" ? " - " + beNote : "")))
            label.set_color(eLbl, cMorning)
            label.set_textcolor(eLbl, cOcean)
 
// ───────────────────────── ALERT CONDITIONS (pick these instead of "Any alert() function call" for per-signal sounds) ─────────────────────────
alertcondition(readyBuyNow, "READY BUY", "🔔 READY BUY on {{ticker}}. Check the table.")
alertcondition(readySellNow, "READY SELL", "🔔 READY SELL on {{ticker}}. Check the table.")
alertcondition(fillNow, "ENTRY filled", "🔔 ENTRY filled on {{ticker}}.")
alertcondition(moveSLNow, "Move stop to entry", "🔔 Move the stop to entry on {{ticker}}. TP1 has closed.")
 
// ───────────────────────── INFO TABLE ─────────────────────────
tblP = tblPos == "Top right" ? position.top_right : tblPos == "Top left" ? position.top_left : tblPos == "Bottom right" ? position.bottom_right : position.bottom_left
if showStats and barstate.islast
    table info = table.new(tblP, 2, 10, border_width=1)
    color bg = color.new(cOcean, 5)
    string stTxt = state == 0 ? "NO TRADE" : state == 1 ? "WAITING FOR RETEST" : (beDone ? "IN PLAY (stop at BE)" : "IN PLAY")
    int nearNow = f_nearDir(close)
    int agree = (biasSig == dirT ? 1 : 0) + (refNearSig == dirT ? 1 : 0) + (structSig == dirT ? 1 : 0)
    table.cell(info, 0, 0, "ENTRY FLASHLIGHT", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 0, inSess ? "IN WINDOW" : "OUT OF WINDOW", bgcolor=inSess ? cMorning : bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 1, "State", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 1, stTxt, bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 2, "Direction", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 2, state == 0 ? "-" : dirT == 1 ? "LONG" : "SHORT", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 3, "Entry / SL", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 3, state == 0 ? "-" : str.tostring(entryPx, format.mintick) + " / " + str.tostring(curSL, format.mintick), bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 4, "TP1 / TP2", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 5, "TP3 (target)", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 4, state == 0 ? "-" : str.tostring(tp1P, format.mintick) + " / " + str.tostring(tp2P, format.mintick), bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 5, state == 0 ? "-" : str.tostring(tpPx, format.mintick), bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 6, "VWAP side", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 6, biasNow == 1 ? "BULL (above VWAP)" : "BEAR (below VWAP)", bgcolor=biasNow == 1 ? cGreen : cBearB, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 7, "Nearest " + refTxt + " gap", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 7, nearNow == 1 ? "BULL" : nearNow == -1 ? "BEAR" : "none", bgcolor=nearNow == 1 ? cGreen : nearNow == -1 ? cBearB : bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 8, biasTxt + " structure", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 8, struct1H == 1 ? "UP (HH+HL)" : struct1H == -1 ? "DOWN (LH+LL)" : "MIXED", bgcolor=struct1H == 1 ? cGreen : struct1H == -1 ? cBearB : bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 0, 9, "Strength", bgcolor=bg, text_color=cPaper, text_size=tblSz)
    table.cell(info, 1, 9, state == 0 ? "-" : (agree == 3 ? "HIGH" : agree == 2 ? "MEDIUM" : "LOW"), bgcolor=state == 0 ? bg : (agree == 3 ? cGreen : agree == 2 ? cMorning : bg), text_color=cPaper, text_size=tblSz)

← 返回列表