Time Sniper V1

LiquidityhunterOfficial · study · 546 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
indicator("Time Sniper V1", shorttitle="Time Sniper V1", overlay=true, max_boxes_count=300, max_lines_count=400, max_labels_count=400)
 
// ═══════════════════════════════════════════════════════════════════════════
//  TIME SNIPER V1  ·  XAUUSD  (formerly LD Zone / Nitin Gold Time)
//  1) At each session time (IST) the zone candle is marked: its full High → Low.
//     Default zone candle = the CHART timeframe (5m chart → the 5m candle, 3m chart → the 3m candle).
//     A fixed zone timeframe (1 … 60 min) can be chosen instead (then it is the same on every lower chart).
//  2) A chart candle CLOSES above the zone → BUY, below → SELL (entry at that close)
//  3) SL: the other side of the zone (price)  —  or the original rule: a candle CLOSE on the other side → exit + reverse
//  4) Three positions: TP1 / TP2 / TP3 = zone size × 1 / × 1.5 / × 2 (or fixed pips) · after TP1 the rest goes to break-even
//  5) Entries only within the window after the zone · max attempts per session
//  Up to 4 sessions (name, on/off, time). Times are India time (IST). Dashboard: per session + last N trades.
// ═══════════════════════════════════════════════════════════════════════════
 
// ───────── inputs ─────────
string TZ = "Asia/Kolkata"           // India time, fixed
 
gZ = "Sessions (India time · IST)"
s1On = input.bool(true,  "", inline="s1", group=gZ)
s1N  = input.string("Asia", "", inline="s1", group=gZ)
s1H  = input.int(5,  "", minval=0, maxval=23, inline="s1", group=gZ)
s1M  = input.int(30, ":", minval=0, maxval=59, inline="s1", group=gZ)
s2On = input.bool(true,  "", inline="s2", group=gZ)
s2N  = input.string("London", "", inline="s2", group=gZ)
s2H  = input.int(12, "", minval=0, maxval=23, inline="s2", group=gZ)
s2M  = input.int(30, ":", minval=0, maxval=59, inline="s2", group=gZ)
s3On = input.bool(true,  "", inline="s3", group=gZ)
s3N  = input.string("NY", "", inline="s3", group=gZ)
s3H  = input.int(18, "", minval=0, maxval=23, inline="s3", group=gZ)
s3M  = input.int(45, ":", minval=0, maxval=59, inline="s3", group=gZ)
s4On = input.bool(false, "", inline="s4", group=gZ)
s4N  = input.string("Session 4", "", inline="s4", group=gZ)
s4H  = input.int(22, "", minval=0, maxval=23, inline="s4", group=gZ)
s4M  = input.int(30, ":", minval=0, maxval=59, inline="s4", group=gZ, tooltip="Tick = session on · name · start time (hour : minute, India time).")
 
gT = "Zone & entry"
zoneTf    = input.string("Chart", "Zone candle", options=["Chart", "1", "3", "5", "15", "30", "45", "60"], group=gT,
     tooltip="Chart = the candle of the chart's own timeframe at the session time (5m chart → 5m candle; switch to 3m → the 3m candle).\nA number = that fixed timeframe in minutes; then the zone stays the same on every lower chart.")
zoneAlign = input.string("Candle that contains the session time", "Zone candle position", options=["Candle that contains the session time", "Starts exactly at the session time"], group=gT,
     tooltip="Contains: the real candle around the session time. Starts exactly: a window of that length starting at the session time.")
winMin    = input.int(60, "Entry window after the zone (min)", minval=3, maxval=1440, group=gT, tooltip="New entries only inside this time. After it, open trades still run to TP / break-even / SL.")
maxTries  = input.int(3, "Max attempts per session", minval=1, maxval=10, group=gT)
pipSize   = input.float(0.10, "Pip size (gold = 0.10)", minval=0.00001, group=gT)
 
gS = "Stop loss"
slMode  = input.string("Other side of the zone (price)", "Stop loss", options=["Other side of the zone (price)", "Candle close on the other side (exit + reverse)"], group=gS,
     tooltip="Price: BUY → SL at the zone low, SELL → SL at the zone high. After an SL a new breakout close (either side) can give the next attempt.\nClose: the original rule — a candle closing on the other side closes the trade and opens the opposite one.")
slBuf   = input.float(0, "SL buffer beyond the zone (pips)", minval=0, step=1, group=gS)
revLate = input.bool(false, "Close rule: allow reversal after the window", group=gS)
 
gP = "Target projection"
showTg   = input.bool(true, "Show Targets on Breakout", group=gP, tooltip="Draw the TP1 / TP2 / TP3 lines on the chart when a trade opens. OFF hides the lines only; the trades are the same.")
tgCol    = input.color(color.new(#0E8FA8, 0), "Target Lines Color", group=gP)
 
gPX = "Targets × zone range"
useX     = input.bool(true, "Use targets × zone range", group=gPX, tooltip="ON: target = zone range (high − low) × the number, measured from the entry.\nTurn this ON or the pips switch below, not both (if both are ON, pips are used).")
tp1X     = input.float(1.0, "Target 1 (x Range)", minval=0.1, step=0.1, group=gPX)
tp2X     = input.float(1.5, "Target 2 (x Range)", minval=0.1, step=0.1, group=gPX)
tp3X     = input.float(2.0, "Target 3 (x Range)", minval=0.1, step=0.1, group=gPX)
 
gPP = "Targets in pips"
usePips  = input.bool(false, "Use targets in pips", group=gPP, tooltip="ON: fixed targets in pips from the entry. If both switches are ON, pips are used.")
tp1Pips  = input.float(50,  "Target 1 (pips)", minval=1, group=gPP)
tp2Pips  = input.float(100, "Target 2 (pips)", minval=1, group=gPP)
tp3Pips  = input.float(150, "Target 3 (pips)", minval=1, group=gPP)
// pips win when both are ON; if both are OFF the zone multiples are used
bool tpByZone = not usePips
 
gV = "Look"
upCol    = input.color(color.new(#21C17A, 0), "Buy", inline="c", group=gV)
dnCol    = input.color(color.new(#F2545B, 0), "Sell", inline="c", group=gV)
c1       = input.color(color.new(#38CDF4, 82), "S1", inline="z", group=gV)
c2       = input.color(color.new(#B07CFF, 82), "S2", inline="z", group=gV)
c3       = input.color(color.new(#F2C14E, 82), "S3", inline="z", group=gV)
c4       = input.color(color.new(#FF8A5B, 82), "S4", inline="z", group=gV)
showPan  = input.bool(true, "Show results panel", group=gV)
 
gB = "Backtest & dashboard"
btStart = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Backtest Start", group=gB, tooltip="Trades and the panel start from this date.")
lastN   = input.int(100, "Summary from the last N trades", minval=5, maxval=500, group=gB)
calcLot = input.float(0.10, "Pip calculator: lot per position", minval=0.01, step=0.01, group=gB)
pipVal  = input.float(10, "Money per pip for 1 lot", minval=0.01, group=gB, tooltip="Gold standard account: 1 lot = 10 per pip (pip = 0.10).")
 
gA = "Alerts & Automation"
alertMode  = input.string("Phone notifications", "Alert Mode", options=["Phone notifications", "Automation (webhook)"], group=gA,
     tooltip="Phone notifications = readable messages. Automation (webhook) = Chart Funded algo messages (use a separate copy with its own alert).")
stratCode  = input.string("NITIN", "Strategy code (Admin → Algo Strategies)", group=gA)
webhookKey = input.string("", "Webhook Key (TV_WEBHOOK_SECRET)", group=gA, tooltip="Only for Automation mode. Never share a chart layout with the key filled in.")
autoSymbol = input.string("XAUUSD", "Symbol name sent to the server", group=gA)
eslPips    = input.float(150, "Close rule: emergency SL on the broker (pips)", minval=20, group=gA, tooltip="Only for the candle-close SL rule (the broker SL is a safety net).")
aZone = input.bool(true, "Notify: zone marked", group=gA)
aTrade = input.bool(true, "Notify: entries, TP, break-even, SL", group=gA)
bool jsonMode = alertMode == "Automation (webhook)"
 
// ───────── helpers ─────────
P = pipSize
tfMin = timeframe.isminutes ? timeframe.multiplier : 0
int ZTF = zoneTf == "Chart" ? math.max(1, tfMin) : int(nz(str.tonumber(zoneTf), 3))
tfOk  = tfMin >= 1 and tfMin <= ZTF
bool priceSL = slMode == "Other side of the zone (price)"
f_zStart(int s0) =>
    if zoneAlign == "Starts exactly at the session time"
        s0
    else
        int u  = (s0 - 330 + 1440) % 1440          // IST → UTC minute of the day (candles are cut on UTC)
        int zu = u - u % ZTF
        (zu + 330) % 1440
string CODE = str.upper(str.replace_all(stratCode, " ", ""))
 
f_sOn(int k) => k == 0 ? s1On : k == 1 ? s2On : k == 2 ? s3On : s4On
f_sName(int k) => k == 0 ? s1N : k == 1 ? s2N : k == 2 ? s3N : s4N
f_sStart(int k) => k == 0 ? s1H * 60 + s1M : k == 1 ? s2H * 60 + s2M : k == 2 ? s3H * 60 + s3M : s4H * 60 + s4M
f_sCol(int k) => k == 0 ? c1 : k == 1 ? c2 : k == 2 ? c3 : c4
f_sLine(int k) => color.new(f_sCol(k), 40)
 
// finished 1-minute candles inside this chart candle (to build the zone exactly on any chart)
[iH, iL, iT] = request.security_lower_tf(syminfo.tickerid, "1", [high, low, time])
 
// ───────── state ─────────
type St
    float  zHi = na
    float  zLo = na
    int    wEnd = na
    int    k = 0
    bool   done = true
    int    tries = 0
    int    dir = 0
    float  ent = na
    float  sl = na
    float  tp1 = na
    float  tp2 = na
    float  tp3 = na
    bool   p1 = false
    bool   p2 = false
    bool   p3 = false
    float  x1 = na          // exit price of each position
    float  x2 = na
    float  x3 = na
    bool   be = false
    int    beBar = na
    bool   hit1 = false
    bool   hit2 = false
    bool   hit3 = false
    float  acc = 0.0        // pips of this trade so far (both positions)
    float  riskP = 0.0      // entry → SL in pips (1R per position)
    line   lEnt = na
    line   lTp1 = na
    line   lTp2 = na
    line   lTp3 = na
    line   lSl = na
    string gid = ""
    int    bk = -1
    float  bHi = na
    float  bLo = na
    int    bT0 = na
    int    lastM = na
 
var St st = St.new()
string jmsg = ""
string msg = ""
 
// stats per session
var array<int>   sTrades = array.from(0, 0, 0, 0)
var array<int>   sTp1    = array.from(0, 0, 0, 0)
var array<int>   sTp2    = array.from(0, 0, 0, 0)
var array<int>   sTp3    = array.from(0, 0, 0, 0)
var array<int>   sBe     = array.from(0, 0, 0, 0)
var array<int>   sSl     = array.from(0, 0, 0, 0)
var array<float> sPips   = array.from(0.0, 0.0, 0.0, 0.0)
var array<int>   sSess   = array.from(0, 0, 0, 0)
var int firstT = na
// last N closed trades (all sessions)
var array<float> rPips = array.new<float>()
var array<float> rR    = array.new<float>()
var array<int>   rWin  = array.new<int>()
 
f_add(array<int> a, int i) => a.set(i, a.get(i) + 1)
f_mark(int t, float y, string txt, color c, bool below, string tip) =>
    label.new(t, y, txt, xloc=xloc.bar_time, yloc=yloc.price, style=below ? label.style_label_up : label.style_label_down,
              color=c, textcolor=color.white, size=size.small, tooltip=tip)
 
// a part of the trade closes at price px (n positions) → pips added to the trade and the session
f_book(St s, float px, int n) =>
    float pp = (px - s.ent) * s.dir / P * n
    s.acc += pp
    sPips.set(s.k, sPips.get(s.k) + pp)
 
f_nOpen(St s) => (s.p1 ? 1 : 0) + (s.p2 ? 1 : 0) + (s.p3 ? 1 : 0)
// close every open position at px (records its exit price)
f_closeAll(St s, float px) =>
    f_book(s, px, f_nOpen(s))
    if s.p1
        s.x1 := px
    if s.p2
        s.x2 := px
    if s.p3
        s.x3 := px
    s.p1 := false
    s.p2 := false
    s.p3 := false
 
// the trade is over → store it for the last-N summary
f_rec(St s) =>
    rPips.push(s.acc)
    rR.push(s.riskP > 0 ? s.acc / (3 * s.riskP) : 0.0)
    rWin.push(s.hit1 ? 1 : 0)
    if rPips.size() > lastN
        rPips.shift()
        rR.shift()
        rWin.shift()
 
// open a new attempt at the close of this candle → returns the alert text
f_open(St s, int d) =>
    float zr = s.zHi - s.zLo
    s.dir := d
    s.ent := close
    s.sl  := priceSL ? (d == 1 ? s.zLo - slBuf * P : s.zHi + slBuf * P) : (d == 1 ? s.zLo : s.zHi)
    s.tp1 := tpByZone ? close + d * tp1X * zr : close + d * tp1Pips * P
    s.tp2 := tpByZone ? close + d * tp2X * zr : close + d * tp2Pips * P
    s.tp3 := tpByZone ? close + d * tp3X * zr : close + d * tp3Pips * P
    s.p1 := true
    s.p2 := true
    s.p3 := true
    s.x1 := na
    s.x2 := na
    s.x3 := na
    s.be := false
    s.beBar := na
    s.hit1 := false
    s.hit2 := false
    s.hit3 := false
    s.acc := 0.0
    s.riskP := math.abs(close - s.sl) / P
    s.gid := str.replace_all(CODE, "_", "") + "-" + (d == 1 ? "B" : "S") + "-" + str.tostring(time)
    s.tries += 1
    f_add(sTrades, s.k)
    if s.tries == 1
        f_add(sSess, s.k)
    c = d == 1 ? upCol : dnCol
    s.lEnt := line.new(time, s.ent, time + 60 * 60000, s.ent, xloc=xloc.bar_time, color=color.new(c, 30), width=1)
    color tc = showTg ? tgCol : na
    s.lTp1 := line.new(time, s.tp1, time + 60 * 60000, s.tp1, xloc=xloc.bar_time, color=tc, style=line.style_dashed)
    s.lTp2 := line.new(time, s.tp2, time + 60 * 60000, s.tp2, xloc=xloc.bar_time, color=tc, style=line.style_dashed)
    s.lTp3 := line.new(time, s.tp3, time + 60 * 60000, s.tp3, xloc=xloc.bar_time, color=tc, style=line.style_dashed, width=2)
    s.lSl  := line.new(time, s.sl, time + 60 * 60000, s.sl, xloc=xloc.bar_time, color=priceSL ? color.new(#F2545B, 20) : na, style=line.style_dashed)
    side = d == 1 ? "BUY" : "SELL"
    f_mark(time, d == 1 ? low : high, side + " #" + str.tostring(s.tries), c, d == 1,
           f_sName(s.k) + " attempt " + str.tostring(s.tries) + "\nEntry " + str.tostring(s.ent, format.mintick) +
           "\nTP1 " + str.tostring(s.tp1, format.mintick) + "   TP2 " + str.tostring(s.tp2, format.mintick) + "   TP3 " + str.tostring(s.tp3, format.mintick) +
           (priceSL ? "\nSL " + str.tostring(s.sl, format.mintick) : "\nSL: a candle close on the other side of the zone"))
    side + " entry #" + str.tostring(s.tries) + " at " + str.tostring(s.ent, format.mintick) +
      " (SL " + (priceSL ? str.tostring(s.sl, format.mintick) : "zone close") + ", TP1 " + str.tostring(s.tp1, format.mintick) + ", TP2 " + str.tostring(s.tp2, format.mintick) + ", TP3 " + str.tostring(s.tp3, format.mintick) + ")"
 
f_flat(St s) =>
    if not na(s.lEnt)
        s.lEnt.set_x2(time)
        s.lTp1.set_x2(time)
        s.lTp2.set_x2(time)
        s.lTp3.set_x2(time)
        s.lSl.set_x2(time)
    s.dir := 0
    s.p1 := false
    s.p2 := false
    s.p3 := false
    s.be := false
 
// ───────── automation messages (Chart Funded webhook v2, market orders) ─────────
f_n(float v) => str.tostring(v, "#.##")
f_head(St s, string ev) =>
    "{\"v\":2,\"key\":\"" + webhookKey + "\",\"strat\":\"" + CODE + "\",\"tf\":\"M" + str.tostring(tfMin) +
      "\",\"ev\":\"" + ev + "\",\"gid\":\"" + s.gid + "\",\"side\":\"" + (s.dir == 1 ? "BUY" : "SELL") +
      "\",\"sym\":\"" + autoSymbol + "\",\"ts\":" + str.tostring(time)
f_jCreate(St s) =>
    sl = f_n(priceSL ? s.sl : s.ent - s.dir * eslPips * P)
    f_head(s, "create") + ",\"mkt\":1,\"legs\":[{\"n\":1,\"e\":" + f_n(s.ent) + ",\"sl\":" + sl + ",\"tp\":" + f_n(s.tp1) +
      "},{\"n\":2,\"e\":" + f_n(s.ent) + ",\"sl\":" + sl + ",\"tp\":" + f_n(s.tp2) +
      "},{\"n\":3,\"e\":" + f_n(s.ent) + ",\"sl\":" + sl + ",\"tp\":" + f_n(s.tp3) + "}]}\n"
f_jTp1(St s) => f_head(s, "tp1") + "}\n"
f_jResult(St s) =>
    string res = s.hit3 ? "tp" : s.hit1 ? "be" : "sl"
    f_head(s, "result") + ",\"res\":\"" + res + "\",\"legs\":[{\"n\":1,\"f\":1,\"x\":" + f_n(s.x1) + "},{\"n\":2,\"f\":1,\"x\":" + f_n(s.x2) +
      "},{\"n\":3,\"f\":1,\"x\":" + f_n(s.x3) + "}]}\n"
f_jClose(St s, string reason) => f_head(s, "cancel") + ",\"reason\":\"" + reason + "\"}\n"
 
// ───────── engine (closed candles only) ─────────
if tfOk and barstate.isconfirmed and time >= btStart
    if na(firstT)
        firstT := time
 
    // 1) zones from the 1-minute candles of this chart candle
    bool zoneEvent = false
    if not na(iT) and iT.size() > 0
        for j = 0 to iT.size() - 1
            int t1 = iT.get(j)
            if na(st.lastM) or t1 > st.lastM
                st.lastM := t1
                int md = hour(t1, TZ) * 60 + minute(t1, TZ)
                for k = 0 to 3
                    int s0 = f_zStart(f_sStart(k))
                    int dm = (md - s0 + 1440) % 1440
                    if f_sOn(k) and dm < ZTF
                        zoneEvent := true
                        if dm == 0
                            // a new zone starts: a trade still open from before is closed here (at this close)
                            if st.dir != 0
                                jmsg += f_jClose(st, "expired")
                                f_closeAll(st, close)
                                f_rec(st)
                                f_flat(st)
                            st.done := true
                            st.bk := k
                            st.bHi := iH.get(j)
                            st.bLo := iL.get(j)
                            st.bT0 := t1
                        else if st.bk == k
                            st.bHi := math.max(st.bHi, iH.get(j))
                            st.bLo := math.min(st.bLo, iL.get(j))
                        if dm == ZTF - 1 and st.bk == k and not na(st.bT0)
                            st.k := k
                            st.zHi := st.bHi
                            st.zLo := st.bLo
                            st.wEnd := st.bT0 + ZTF * 60000 + winMin * 60000
                            st.tries := 0
                            st.done := false
                            st.bk := -1
                            box.new(st.bT0, st.zHi, st.wEnd, st.zLo, xloc=xloc.bar_time, bgcolor=f_sCol(k),
                                      border_color=f_sLine(k), text=f_sName(k) + " zone · " + str.tostring(ZTF) + "m",
                                      text_color=color.new(color.white, 30), text_size=size.small, text_halign=text.align_left, text_valign=text.align_top)
                            if aZone
                                msg += "Time Sniper: " + f_sName(k) + " zone marked " + str.tostring(st.zLo, format.mintick) + " - " + str.tostring(st.zHi, format.mintick) + "\n"
 
    // 2) after the zone
    if not zoneEvent and not st.done and not na(st.zHi)
        inWin = time_close <= st.wEnd
        i = st.k
        if st.dir != 0
            bool longT = st.dir == 1
            // a) price SL before TP1 (checked first: safe side) → all three positions
            bool closedNow = false
            if priceSL and st.p1 and (longT ? low <= st.sl : high >= st.sl)
                f_closeAll(st, st.sl)
                f_add(sSl, i)
                f_mark(time, longT ? low : high, "SL", color.new(#F2545B, 0), longT, "SL " + str.tostring(st.sl, format.mintick) + " (" + str.tostring(st.acc, "#.#") + " pips)")
                if aTrade
                    msg += "Time Sniper: " + f_sName(i) + " SL hit\n"
                closedNow := true
            // b) after TP1: the rest has its SL at the entry (break-even), active from the candle after TP1
            if not closedNow and not st.p1 and (st.p2 or st.p3) and st.be and bar_index > st.beBar and (longT ? low <= st.ent : high >= st.ent)
                f_closeAll(st, st.ent)
                f_add(sBe, i)
                f_mark(time, longT ? low : high, "BE", color.new(#93A6C4, 0), longT, "Rest closed at break-even")
                if aTrade
                    msg += "Time Sniper: " + f_sName(i) + " rest closed at break-even\n"
                closedNow := true
            if not closedNow
                // c) TP1 → position 1 closed, the rest to break-even
                if st.p1 and (longT ? high >= st.tp1 : low <= st.tp1)
                    st.p1 := false
                    st.x1 := st.tp1
                    st.hit1 := true
                    st.be := true
                    st.beBar := bar_index
                    f_book(st, st.tp1, 1)
                    jmsg += f_jTp1(st)
                    f_add(sTp1, i)
                    f_mark(time, longT ? high : low, "TP1", tgCol, not longT, "TP1 " + str.tostring(st.tp1, format.mintick) + ". Rest SL to break-even")
                    if aTrade
                        msg += "Time Sniper: " + f_sName(i) + " TP1 hit. Move the rest SL to " + str.tostring(st.ent, format.mintick) + "\n"
                // d) TP2
                if st.p2 and not st.p1 and (longT ? high >= st.tp2 : low <= st.tp2)
                    st.p2 := false
                    st.x2 := st.tp2
                    st.hit2 := true
                    f_book(st, st.tp2, 1)
                    f_add(sTp2, i)
                    f_mark(time, longT ? high : low, "TP2", tgCol, not longT, "TP2 " + str.tostring(st.tp2, format.mintick))
                    if aTrade
                        msg += "Time Sniper: " + f_sName(i) + " TP2 hit\n"
                // e) TP3
                if st.p3 and not st.p1 and not st.p2 and (longT ? high >= st.tp3 : low <= st.tp3)
                    st.p3 := false
                    st.x3 := st.tp3
                    st.hit3 := true
                    f_book(st, st.tp3, 1)
                    f_add(sTp3, i)
                    f_mark(time, longT ? high : low, "TP3", color.new(#21C17A, 0), not longT, "TP3 " + str.tostring(st.tp3, format.mintick))
                    if aTrade
                        msg += "Time Sniper: " + f_sName(i) + " TP3 hit\n"
                if not st.p1 and not st.p2 and not st.p3
                    closedNow := true
            if closedNow
                jmsg += f_jResult(st)
                f_rec(st)
                f_flat(st)
                // a winning trade ends the session; after a loss a new breakout close may give the next attempt
                if st.hit1 or st.tries >= maxTries
                    st.done := true
            else if not priceSL and (longT ? close < st.zLo : close > st.zHi)
                // close rule: candle closed on the other side of the zone → close now, maybe reverse
                bool hadTp1 = st.hit1
                f_closeAll(st, close)
                f_add(sSl, i)
                f_mark(time, longT ? low : high, "SL", color.new(#F2545B, 0), longT, "Closed at " + str.tostring(close, format.mintick) + " (" + str.tostring(st.acc, "#.#") + " pips)")
                jmsg += f_jClose(st, "flip")
                f_rec(st)
                f_flat(st)
                if not hadTp1 and st.tries < maxTries and (inWin or revLate)
                    t = f_open(st, longT ? -1 : 1)
                    jmsg += f_jCreate(st)
                    if aTrade
                        msg += "Time Sniper: " + f_sName(i) + " SL. Closed and reversed: " + t + "\n"
                else
                    st.done := true
                    if aTrade
                        msg += "Time Sniper: " + f_sName(i) + " SL. Session closed (no more attempts)\n"
        // 3) waiting for a breakout close, only inside the window
        else if st.tries < maxTries
            if inWin and close > st.zHi
                t = f_open(st, 1)
                jmsg += f_jCreate(st)
                if aTrade
                    msg += "Time Sniper: " + f_sName(i) + " " + t + "\n"
            else if inWin and close < st.zLo
                t = f_open(st, -1)
                jmsg += f_jCreate(st)
                if aTrade
                    msg += "Time Sniper: " + f_sName(i) + " " + t + "\n"
            else if not inWin
                st.done := true
        else
            st.done := true
 
// ───────── alerts (one alert: "Any alert() function call") ─────────
if jsonMode
    if str.length(jmsg) > 0 and str.length(webhookKey) >= 24
        alert(jmsg, alert.freq_once_per_bar_close)
else if str.length(msg) > 0
    alert(msg, alert.freq_once_per_bar_close)
 
// ───────── panel: per session (same as before) + last N trades ─────────
var table pan = table.new(position.top_right, 5, 26, bgcolor=color.new(#000000, 15), border_color=color.new(#C9A227, 60), border_width=1, frame_color=color.new(#C9A227, 20), frame_width=1)
f_cell(table tb, int c, int r, string t, color tc) =>
    table.cell(tb, c, r, t, text_color=tc, text_size=size.small, text_halign=c == 0 ? text.align_left : text.align_right)
f_line(table tb, int r, string k, string v, color vc, int lastC) =>
    table.cell(tb, 0, r, k, text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(tb, 1, r, v, text_color=vc, text_size=size.small, text_halign=text.align_right)
    if lastC > 1
        table.merge_cells(tb, 1, r, lastC, r)
if barstate.islast and showPan
    gold = color.new(#C9A227, 0)
    cG = color.new(#43D9A0, 0)
    cR = color.new(#F2545B, 0)
    table.clear(pan, 0, 0, 4, 25)
    // only the sessions that are ON get a column
    array<int> vis = array.new<int>()
    for k = 0 to 3
        if f_sOn(k)
            vis.push(k)
    int lastC = math.max(1, vis.size())
    table.cell(pan, 0, 0, "◆ CHART LOGIX", text_color=gold, text_size=size.small, text_halign=text.align_left)
    table.cell(pan, 1, 0, "TIME SNIPER V1 · " + str.tostring(ZTF) + "m zone · " + str.tostring(tfMin) + "m entries", text_color=color.white, text_size=size.small)
    if lastC > 1
        table.merge_cells(pan, 1, 0, lastC, 0)
    if not tfOk
        table.cell(pan, 0, 1, "Zone = " + str.tostring(ZTF) + "m: use a chart from 1m up to " + str.tostring(ZTF) + "m", text_color=cR, text_size=size.small)
        table.merge_cells(pan, 0, 1, lastC, 1)
    else if vis.size() == 0
        table.cell(pan, 0, 1, "All sessions are OFF: switch one ON in the settings", text_color=cR, text_size=size.small)
        table.merge_cells(pan, 0, 1, 1, 1)
    else
        f_cell(pan, 0, 1, "Since " + str.format_time(math.max(btStart, nz(firstT, btStart)), "dd MMM yy", TZ), color.new(color.white, 40))
        for c = 0 to vis.size() - 1
            int k = vis.get(c)
            f_cell(pan, c + 1, 1, f_sName(k), color.new(f_sCol(k), 0))
        rows = array.from("Sessions traded", "Trades (attempts)", "TP1 hit", "TP2 hit", "TP3 hit", "Break-even", "SL", "Net pips", "Win rate")
        for r = 0 to 8
            f_cell(pan, 0, r + 2, rows.get(r), color.white)
        for c = 0 to vis.size() - 1
            int i = vis.get(c)
            tr = sTrades.get(i)
            wr = tr > 0 ? sTp1.get(i) * 100.0 / tr : 0.0
            f_cell(pan, c + 1, 2, str.tostring(sSess.get(i)), color.white)
            f_cell(pan, c + 1, 3, str.tostring(tr), color.white)
            f_cell(pan, c + 1, 4, str.tostring(sTp1.get(i)), cG)
            f_cell(pan, c + 1, 5, str.tostring(sTp2.get(i)), color.new(#21C17A, 0))
            f_cell(pan, c + 1, 6, str.tostring(sTp3.get(i)), color.new(#21C17A, 0))
            f_cell(pan, c + 1, 7, str.tostring(sBe.get(i)), color.new(#93A6C4, 0))
            f_cell(pan, c + 1, 8, str.tostring(sSl.get(i)), cR)
            pp = sPips.get(i)
            f_cell(pan, c + 1, 9, (pp >= 0 ? "+" : "") + str.tostring(pp, "#.#"), pp >= 0 ? cG : cR)
            f_cell(pan, c + 1, 10, str.tostring(wr, "#.#") + "%", gold)
 
        // ── last N trades (all sessions) ──
        int   n = rPips.size()
        int   wins = 0
        float won = 0.0
        float lost = 0.0
        float rSum = 0.0
        float rWinS = 0.0
        int   rWinN = 0
        float rLossS = 0.0
        int   rLossN = 0
        int   curW = 0
        int   curL = 0
        int   bestW = 0
        int   bestL = 0
        if n > 0
            for x = 0 to n - 1
                float p  = rPips.get(x)
                float rv = rR.get(x)
                bool  w  = rWin.get(x) == 1
                wins += w ? 1 : 0
                won  += p > 0 ? p : 0.0
                lost += p < 0 ? -p : 0.0
                rSum += rv
                if rv > 0
                    rWinS += rv
                    rWinN += 1
                else if rv < 0
                    rLossS += -rv
                    rLossN += 1
                curW := w ? curW + 1 : 0
                curL := w ? 0 : curL + 1
                bestW := math.max(bestW, curW)
                bestL := math.max(bestL, curL)
        float wrAll  = n > 0 ? wins * 100.0 / n : na
        float net    = won - lost
        float perPip = calcLot * pipVal
        float avgWin = rWinN > 0 ? rWinS / rWinN : na
        float avgLos = rLossN > 0 ? rLossS / rLossN : na
        string avgRR = na(avgWin) ? "—" : na(avgLos) ? "1 : ∞" : "1 : " + str.tostring(avgWin / avgLos, "#.##")
        table.cell(pan, 0, 11, "LAST " + str.tostring(n) + " TRADES · all sessions", text_color=gold, text_size=size.small, text_halign=text.align_left)
        table.merge_cells(pan, 0, 11, lastC, 11)
        f_line(pan, 12, "Win rate (TP1 reached)", na(wrAll) ? "—" : str.tostring(wrAll, "#.#") + "%", gold, lastC)
        f_line(pan, 13, "Winning streak", str.tostring(bestW), cG, lastC)
        f_line(pan, 14, "Losing streak", str.tostring(bestL), cR, lastC)
        f_line(pan, 15, "Average RR (avg win ÷ avg loss)", avgRR, color.white, lastC)
        f_line(pan, 16, "Average result per trade", n > 0 ? (rSum >= 0 ? "+" : "−") + str.tostring(math.abs(rSum / n), "#.##") + "R" : "—", rSum >= 0 ? cG : cR, lastC)
        f_line(pan, 17, "Net RR", (rSum >= 0 ? "+" : "−") + str.tostring(math.abs(rSum), "#.#") + "R", rSum >= 0 ? cG : cR, lastC)
        f_line(pan, 18, "Profit factor", lost > 0 ? str.tostring(won / lost, "#.##") : won > 0 ? "∞" : "—", color.white, lastC)
        f_line(pan, 19, "Net pips", (net >= 0 ? "+" : "−") + str.tostring(math.abs(net), "#,##0.0"), net >= 0 ? cG : cR, lastC)
        f_line(pan, 20, "Net result (" + str.tostring(calcLot, "#.##") + " lot × 3 positions)", (net >= 0 ? "+" : "−") + str.tostring(math.abs(net) * perPip, "#,##0.00"), net >= 0 ? cG : cR, lastC)
        f_line(pan, 21, "SL · Targets" + (usePips and useX ? " (⚠ both ON → pips)" : not usePips and not useX ? " (⚠ both OFF → × range)" : ""), (priceSL ? "zone side" : "close rule") + " · " + (tpByZone ? str.tostring(tp1X) + "× / " + str.tostring(tp2X) + "× / " + str.tostring(tp3X) + "× zone" : str.tostring(tp1Pips) + " / " + str.tostring(tp2Pips) + " / " + str.tostring(tp3Pips) + " pips"), color.new(color.white, 40), lastC)
        table.cell(pan, 0, 22, "Win = TP1 reached. Pips = all 3 positions. R = result ÷ (3 × risk). Times = India (IST).", text_color=color.new(color.white, 50), text_size=size.tiny, text_halign=text.align_left)
        table.merge_cells(pan, 0, 22, lastC, 22)

← 返回列表