NQ Scalper Lab Strategy Tester Edition

jimmyjames4684 · strategy · 616 行 · 点赞 16 · TradingView 原页

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

Pine Script

//@version=6
// ════════════════════════════════════════════════════════════════════════════════
//  NQ Scalper Lab — Strategy Tester edition (NQ / MNQ, 1-minute)
//  Engines: Adaptive (v1) / Trend pullback (v2) / Both. HTF filter, open-window
//  filter, halt flatten, costs. Red box = entry→initial stop, green = entry→price.
//  Orders processed on bar close; stops fill intrabar. No repainting.
// ════════════════════════════════════════════════════════════════════════════════
strategy("NQ Scalper Lab — Strategy Tester Edition", shorttitle = "NQ ScLab", overlay = true, initial_capital = 25000, default_qty_type = strategy.fixed, default_qty_value = 1, commission_type = strategy.commission.cash_per_contract, commission_value = 0.62, slippage = 1, process_orders_on_close = true, pyramiding = 0, margin_long = 0, margin_short = 0, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 1000)
 
const string G_ENG  = "1 · Entry engine & shared"
const string G_V1   = "2 · Adaptive engine (v1)"
const string G_V2   = "3 · Trend pullback engine (v2)"
const string G_HTF  = "4 · Higher-timeframe filter"
const string G_TIME = "5 · Time filters (HHMM, exchange tz)"
const string G_RISK = "6 · Stops & exits"
const string G_BT   = "7 · Backtest"
const string G_BOX  = "8 · Position boxes"
const string G_VIS  = "9 · Display"
 
engine   = input.string("Adaptive (v1)", "Entry engine", options = ["Adaptive (v1)", "Trend pullback (v2)", "Both"], group = G_ENG)
fastLen  = input.int(9, "EMAs: fast / mid / slow", minval = 2, group = G_ENG, inline = "e")
midLen   = input.int(21, "", minval = 3, group = G_ENG, inline = "e")
slowLen  = input.int(50, "", minval = 5, group = G_ENG, inline = "e")
atrLen   = input.int(14, "ATR length", minval = 2, group = G_ENG)
slopeLen = input.int(3, "Slope lookback (bars)", minval = 1, group = G_ENG)
adxLen   = input.int(14, "ADX / DMI length", minval = 2, group = G_ENG)
rsiLen   = input.int(7, "RSI length", minval = 2, group = G_ENG)
 
sens       = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G_V1)
useTrendSt = input.bool(true, "Trend pullback setups", group = G_V1)
useBreak   = input.bool(true, "Structure-break / squeeze ignition setups", group = G_V1)
useMR      = input.bool(true, "Range exhaustion setups", group = G_V1)
adxTrendTh = input.float(22, "ADX trending ≥ / ranging <", group = G_V1, inline = "adx")
adxRangeTh = input.float(17, "", group = G_V1, inline = "adx")
slopeTh    = input.float(0.10, "Regime slope threshold (ATR)", step = 0.01, group = G_V1)
vwapStr    = input.float(1.8, "VWAP stretch for exhaustion (ATR)", minval = 0.5, step = 0.1, group = G_V1)
maxExtAtr  = input.float(2.5, "Don't chase beyond fast EMA (ATR)", minval = 0.5, step = 0.1, group = G_V1)
useVol     = input.bool(true, "Score volume surges ×", group = G_V1, inline = "vol")
volMult    = input.float(1.3, "", minval = 1.0, step = 0.1, group = G_V1, inline = "vol")
 
persist   = input.int(3, "Trend must persist (bars)", minval = 1, group = G_V2)
useSep    = input.bool(true, "Min 21/50 separation (× ATR)", group = G_V2, inline = "sep")
minSep    = input.float(0.10, "", minval = 0, step = 0.05, group = G_V2, inline = "sep")
useSlope  = input.bool(true, "Min 21 EMA slope (× ATR)", group = G_V2, inline = "slp")
minSlope  = input.float(0.05, "", minval = 0, step = 0.01, group = G_V2, inline = "slp")
useAdx    = input.bool(true, "ADX filter (min)", group = G_V2, inline = "ax")
adxMin    = input.float(16, "", minval = 0, group = G_V2, inline = "ax")
cooldown2 = input.int(3, "Cooldown between entries (bars)", minval = 0, group = G_V2)
impLook   = input.int(10, "Swing lookback for pullback", minval = 3, group = G_V2)
minDepth  = input.float(0.5, "Min pullback depth (ATR)", minval = 0, step = 0.05, group = G_V2)
pbTol     = input.float(0.15, "Pullback zone: within X ATR of fast EMA", minval = 0, step = 0.05, group = G_V2)
pbExpire  = input.int(8, "Pullback valid for (bars)", minval = 1, group = G_V2)
reqBreak  = input.bool(true, "Trigger: close beyond prior bar high/low", group = G_V2)
reqHH     = input.bool(true, "Require new HH / LL between entries", group = G_V2)
momMode   = input.string("Candle", "Momentum confirmation", options = ["None", "Candle", "RSI", "Candle + RSI"], group = G_V2)
minClv    = input.float(0.55, "Candle: min close location", minval = 0, maxval = 1, step = 0.05, group = G_V2)
rsiMid    = input.float(50, "RSI threshold", minval = 0, maxval = 100, group = G_V2)
maxChase  = input.float(1.0, "Don't chase beyond fast EMA (ATR)", minval = 0.1, step = 0.1, group = G_V2)
 
htfMode = input.string("Must agree", "HTF filter", options = ["Off", "Block counter-trend", "Must agree"], group = G_HTF, tooltip = "Block counter-trend: no longs while HTF is bearish, no shorts while bullish.\nMust agree: longs only when HTF bullish, shorts only when bearish.\nUses the last CLOSED HTF bar (no repainting).")
htfTf   = input.timeframe("5", "HTF timeframe", group = G_HTF)
 
tz        = input.string("America/Chicago", "Timezone", group = G_TIME)
useBlock  = input.bool(true, "No entries from / to (HHMM)", group = G_TIME, inline = "b")
blockS    = input.int(825, "", minval = 0, maxval = 2359, group = G_TIME, inline = "b")
blockE    = input.int(840, "", minval = 0, maxval = 2359, group = G_TIME, inline = "b")
flatBlock = input.bool(true, "Flatten before the no-entry window", group = G_TIME)
useSess   = input.bool(true, "Trade only in session from / to", group = G_TIME, inline = "s")
sessS     = input.int(830, "", minval = 0, maxval = 2359, group = G_TIME, inline = "s")
sessE     = input.int(1500, "", minval = 0, maxval = 2359, group = G_TIME, inline = "s")
flatEOS   = input.bool(true, "Flatten at session end", group = G_TIME)
flatHalt  = input.bool(true, "Flatten before 16:00 daily halt", group = G_TIME)
 
stopMode    = input.string("Structure + ATR clamp", "Initial stop", options = ["Structure + ATR clamp", "ATR only"], group = G_RISK, tooltip = "Structure = recent swing (v1) or the pullback's extreme (v2), clamped between min and max ATR.")
stopAtrMult = input.float(1.25, "ATR-only stop distance", minval = 0.1, step = 0.05, group = G_RISK)
swingLook   = input.int(6, "Swing stop lookback (v1)", minval = 2, group = G_RISK)
minStopAtr  = input.float(0.6, "Stop clamp min / max (ATR)", minval = 0.1, step = 0.05, group = G_RISK, inline = "cl")
maxStopAtr  = input.float(2.0, "", minval = 0.2, step = 0.05, group = G_RISK, inline = "cl")
bufTicks    = input.int(2, "Stop buffer (ticks)", minval = 0, group = G_RISK)
beR         = input.float(0.5, "Break-even at R (0 = off) / + ticks", minval = 0, step = 0.25, group = G_RISK, inline = "be")
beOffTicks  = input.int(8, "", minval = 0, group = G_RISK, inline = "be")
trailMode   = input.string("Hybrid", "Trailing stop", options = ["Off", "ATR chandelier", "Swing structure", "Hybrid"], group = G_RISK)
trailStartR = input.float(1.0, "Trail activates at (R)", minval = 0, step = 0.25, group = G_RISK)
trailAtr    = input.float(2.0, "Chandelier distance (ATR)", minval = 0.5, step = 0.1, group = G_RISK)
pivL        = input.int(3, "Swing pivot left / right", minval = 1, group = G_RISK, inline = "pv")
pivR        = input.int(2, "", minval = 1, group = G_RISK, inline = "pv")
trendExit   = input.string("Off", "Close on 21/50 trend change", options = ["Off", "Opposite trend", "Opposite or neutral"], group = G_RISK)
exitMom     = input.bool(true, "Exit on momentum failure", group = G_RISK)
exitOpp     = input.bool(true, "Reverse on opposite signal", group = G_RISK)
maxBarsIn   = input.int(0, "Time stop: max bars (0 = off)", minval = 0, group = G_RISK)
 
qty       = input.int(1, "Contracts", minval = 1, group = G_BT, tooltip = "Commission and slippage are set in the Properties tab (defaults: $0.62/contract/side for MNQ, 1 tick slippage). Use about $2.25/side for NQ.")
useDate   = input.bool(false, "Only trade from start date", group = G_BT, inline = "d")
startDate = input.time(1767225600000, "", group = G_BT, inline = "d")
 
showBoxes = input.bool(true, "Show position boxes", group = G_BOX)
profCol   = input.color(color.new(#089981, 70), "Profit / Risk / Entry", group = G_BOX, inline = "c")
riskCol   = input.color(color.new(#F23645, 70), "", group = G_BOX, inline = "c")
entryCol  = input.color(color.new(#D1D4DC, 0), "", group = G_BOX, inline = "c")
closedTr  = input.int(85, "Closed-trade transparency", minval = 0, maxval = 100, group = G_BOX)
projBars  = input.int(8, "Project active box right (bars)", minval = 0, maxval = 100, group = G_BOX)
maxTrades = input.int(120, "Historical trades kept on chart", minval = 1, maxval = 240, group = G_BOX)
showTrLbl = input.bool(true, "Trade labels (live P/L, exit R)", group = G_BOX)
 
showSig  = input.bool(true, "BUY / SELL markers", group = G_VIS)
showStop = input.bool(true, "Active stop line", group = G_VIS)
showEMAs = input.bool(true, "EMAs + ribbon", group = G_VIS)
showVWAP = input.bool(false, "VWAP", group = G_VIS)
showBg   = input.bool(true, "Regime / trend background", group = G_VIS)
showDash = input.bool(true, "Dashboard", group = G_VIS)
dashPos  = input.string("Top right", "Dashboard position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_VIS)
 
float tick = syminfo.mintick
atr  = ta.atr(atrLen)
emaF = ta.ema(close, fastLen)
emaM = ta.ema(close, midLen)
emaS = ta.ema(close, slowLen)
[diP, diM, adx] = ta.dmi(adxLen, adxLen)
rsi    = ta.rsi(close, rsiLen)
vw     = ta.vwap(hlc3)
osc    = (ta.ema(close, 5) - ta.ema(close, 13)) / atr
oscSig = ta.ema(osc, 4)
hist   = osc - oscSig
slope  = (emaM - emaM[slopeLen]) / atr
sep    = (emaM - emaS) / atr
 
bbBasis   = ta.sma(close, 20)
bbDev     = 2.0 * ta.stdev(close, 20)
bbU       = bbBasis + bbDev
bbL       = bbBasis - bbDev
squeeze   = bbDev < 1.5 * ta.atr(20)
sqzBars   = ta.barssince(squeeze)
sqzRecent = not na(sqzBars) and sqzBars > 0 and sqzBars <= 6
bbUpX     = ta.crossover(close, bbU)
bbDnX     = ta.crossunder(close, bbL)
 
rng   = math.max(high - low, tick)
clv   = (close - low) / rng
bodyR = math.abs(close - open) / rng
upW   = (high - math.max(open, close)) / rng
loW   = (math.min(open, close) - low) / rng
v     = nz(volume)
vSma  = ta.sma(v, 20)
volOk = useVol and vSma > 0 and v > vSma * volMult
 
lo5   = ta.lowest(low, 5)
hi5   = ta.highest(high, 5)
swLo  = ta.lowest(low, swingLook)
swHi  = ta.highest(high, swingLook)
rsiLo = ta.lowest(rsi, 3)
rsiHi = ta.highest(rsi, 3)
impHi = ta.highest(high, impLook)
impLo = ta.lowest(low, impLook)
 
ph = ta.pivothigh(high, pivL, pivR)
pl = ta.pivotlow(low, pivL, pivR)
var float lastSH    = na
var float lastSL    = na
var int   lastSHBar = na
var int   lastSLBar = na
if not na(ph)
    lastSH    := ph
    lastSHBar := bar_index - pivR
if not na(pl)
    lastSL    := pl
    lastSLBar := bar_index - pivR
bosUp = ta.crossover(close, lastSH)
bosDn = ta.crossunder(close, lastSL)
 
ready = bar_index > math.max(slowLen, 60) and not na(atr) and atr > 0 and not na(adx)
 
f_min(int hhmm) =>
    math.floor(hhmm / 100) * 60 + hhmm % 100
f_barMin(int t) =>
    hour(t, tz) * 60 + minute(t, tz)
f_inWin(int t, int s, int e) =>
    int m = f_barMin(t)
    m >= f_min(s) and m < f_min(e)
 
inBlock   = useBlock and f_inWin(time, blockS, blockE)
blockNext = useBlock and f_inWin(time_close, blockS, blockE)
sessNow   = f_inWin(time, sessS, sessE)
sessNext  = f_inWin(time_close, sessS, sessE)
haltNext  = f_barMin(time_close) == 16 * 60
inDate    = not useDate or time >= startDate
 
flattenNow  = (useBlock and flatBlock and blockNext and not inBlock) or (useSess and flatEOS and sessNow and not sessNext) or (flatHalt and haltNext)
entryTimeOk = not inBlock and not blockNext and (not useSess or (sessNow and sessNext)) and not (flatHalt and haltNext) and inDate
 
f_htfTrend() =>
    float m  = ta.ema(close, midLen)
    float s  = ta.ema(close, slowLen)
    float a  = ta.atr(atrLen)
    float sl = (m - m[slopeLen]) / a
    int   t  = m > s and sl > 0 and close > s ? 1 : m < s and sl < 0 and close < s ? -1 : 0
    t[1]
htfRaw = request.security(syminfo.tickerid, htfTf, f_htfTrend(), lookahead = barmerge.lookahead_on)
int htfTrend = na(htfRaw) ? 0 : htfRaw
htfOkL = htfMode == "Off" or (htfMode == "Block counter-trend" ? htfTrend != -1 : htfTrend == 1)
htfOkS = htfMode == "Off" or (htfMode == "Block counter-trend" ? htfTrend != 1 : htfTrend == -1)
 
bool  isAgg    = sens == "Aggressive"
bool  isCon    = sens == "Conservative"
int   minScore = isAgg ? 0 : isCon ? 2 : 1
int   cool1    = isAgg ? 0 : isCon ? 4 : 2
float rsiOS    = isAgg ? 30.0 : isCon ? 20.0 : 25.0
float rsiOB    = 100.0 - rsiOS
float ignBody  = isAgg ? 0.45 : isCon ? 0.60 : 0.50
 
bullDir = emaF > emaM and diP > diM
bearDir = emaF < emaM and diM > diP
int regime = 2
if adx >= adxTrendTh and bullDir and slope > slopeTh
    regime := 1
else if adx >= adxTrendTh and bearDir and slope < -slopeTh
    regime := -1
else if adx < adxRangeTh
    regime := 0
 
momUp = ta.crossover(osc, oscSig) or (hist > hist[1] and hist[1] <= hist[2] and hist[1] < 0)
momDn = ta.crossunder(osc, oscSig) or (hist < hist[1] and hist[1] >= hist[2] and hist[1] > 0)
extL  = (close - emaF) / atr > maxExtAtr
extS  = (emaF - close) / atr > maxExtAtr
 
upCtx  = regime == 1 or (regime == 2 and isAgg and bullDir and close > emaS)
dnCtx  = regime == -1 or (regime == 2 and isAgg and bearDir and close < emaS)
pullL1 = lo5 <= emaF + 0.2 * atr and lo5 >= emaS - 0.5 * atr
pullS1 = hi5 >= emaF - 0.2 * atr and hi5 <= emaS + 0.5 * atr
trendL = useTrendSt and upCtx and pullL1 and close > emaF and momUp and close > open and clv >= 0.55 and not extL
trendS = useTrendSt and dnCtx and pullS1 and close < emaF and momDn and close < open and clv <= 0.45 and not extS
 
ignL = useBreak and (bosUp or (sqzRecent and bbUpX)) and osc > 0 and hist > 0 and close > open and bodyR >= ignBody and clv >= 0.65 and rng >= 0.7 * atr and not extL
ignS = useBreak and (bosDn or (sqzRecent and bbDnX)) and osc < 0 and hist < 0 and close < open and bodyR >= ignBody and clv <= 0.35 and rng >= 0.7 * atr and not extS
 
stretchL = low <= bbL or (vw - low) >= vwapStr * atr
stretchS = high >= bbU or (high - vw) >= vwapStr * atr
mrL = useMR and regime != -1 and (stretchL or stretchL[1]) and rsiLo <= rsiOS and loW >= 0.30 and clv >= 0.60 and hist > hist[1]
mrS = useMR and regime != 1 and (stretchS or stretchS[1]) and rsiHi >= rsiOB and upW >= 0.30 and clv <= 0.40 and hist < hist[1]
 
ctxL   = (trendL or ignL) ? close > vw : rsi - rsi[1] >= 3
ctxS   = (trendS or ignS) ? close < vw : rsi[1] - rsi >= 3
scoreL = (volOk ? 1 : 0) + (clv >= 0.80 ? 1 : 0) + (osc - osc[1] >= 0.08 ? 1 : 0) + (ctxL ? 1 : 0)
scoreS = (volOk ? 1 : 0) + (clv <= 0.20 ? 1 : 0) + (osc[1] - osc >= 0.08 ? 1 : 0) + (ctxS ? 1 : 0)
needL  = minScore + (ignL and not trendL and not mrL and regime == -1 ? 1 : 0)
needS  = minScore + (ignS and not trendS and not mrS and regime == 1 ? 1 : 0)
candL1 = ready and (trendL or ignL or mrL) and scoreL >= needL
candS1 = ready and (trendS or ignS or mrS) and scoreS >= needS
string setupL1 = trendL ? "Trend" : ignL ? (bosUp ? "BOS" : "Squeeze") : "Exhaust"
string setupS1 = trendS ? "Trend" : ignS ? (bosDn ? "BOS" : "Squeeze") : "Exhaust"
 
adxOk   = not useAdx or adx >= adxMin
bullRaw = ready and emaM > emaS and (useSlope ? slope >= minSlope : slope > 0) and close > emaS and (not useSep or sep >= minSep) and adxOk
bearRaw = ready and emaM < emaS and (useSlope ? slope <= -minSlope : slope < 0) and close < emaS and (not useSep or sep <= -minSep) and adxOk
var int bullN = 0
var int bearN = 0
bullN := bullRaw ? bullN + 1 : 0
bearN := bearRaw ? bearN + 1 : 0
int trend1 = bullN >= persist ? 1 : bearN >= persist ? -1 : 0
 
var bool  armL = false
var float pbLowL = na
var float legHiL = na
var int   touchBarL = na
var float prevLegHiL = na
var bool  armS = false
var float pbHighS = na
var float legLoS = na
var int   touchBarS = na
var float prevLegLoS = na
 
touchL = low <= emaF + pbTol * atr
touchS = high >= emaF - pbTol * atr
deepL  = (impHi - low) >= minDepth * atr and high < impHi
deepS  = (high - impLo) >= minDepth * atr and low > impLo
 
if trend1 != 1
    armL := false
    prevLegHiL := na
else
    if not armL and touchL and deepL
        armL      := true
        pbLowL    := low
        legHiL    := impHi
        touchBarL := bar_index
    else if armL
        pbLowL := math.min(pbLowL, low)
        if touchL
            touchBarL := bar_index
        if close < emaS or bar_index - touchBarL > pbExpire
            armL := false
 
if trend1 != -1
    armS := false
    prevLegLoS := na
else
    if not armS and touchS and deepS
        armS      := true
        pbHighS   := high
        legLoS    := impLo
        touchBarS := bar_index
    else if armS
        pbHighS := math.max(pbHighS, high)
        if touchS
            touchBarS := bar_index
        if close > emaS or bar_index - touchBarS > pbExpire
            armS := false
 
candUp = close > open and clv >= minClv
candDn = close < open and clv <= 1 - minClv
rsiUp  = rsi > rsiMid and rsi > rsi[1]
rsiDn  = rsi < 100 - rsiMid and rsi < rsi[1]
momL2  = momMode == "None" ? true : momMode == "Candle" ? candUp : momMode == "RSI" ? rsiUp : candUp and rsiUp
momS2  = momMode == "None" ? true : momMode == "Candle" ? candDn : momMode == "RSI" ? rsiDn : candDn and rsiDn
hhOkL  = not reqHH or na(prevLegHiL) or legHiL > prevLegHiL
llOkS  = not reqHH or na(prevLegLoS) or legLoS < prevLegLoS
 
rawL2 = trend1 == 1 and armL and close > emaF and (not reqBreak or close > high[1]) and momL2 and close - emaF <= maxChase * atr and hhOkL
rawS2 = trend1 == -1 and armS and close < emaF and (not reqBreak or close < low[1]) and momS2 and emaF - close <= maxChase * atr and llOkS
 
useV1 = engine != "Trend pullback (v2)"
useV2 = engine != "Adaptive (v1)"
var int lastEntryBar = -100000
int barsSince = bar_index - lastEntryBar
 
sigL1 = useV1 and candL1 and not candS1 and barsSince > cool1
sigS1 = useV1 and candS1 and not candL1 and barsSince > cool1
sigL2 = useV2 and rawL2 and barsSince > cooldown2
sigS2 = useV2 and rawS2 and barsSince > cooldown2
wantL = (sigL1 or sigL2) and htfOkL
wantS = (sigS1 or sigS2) and htfOkS
gate  = barstate.isconfirmed and entryTimeOk
longSig  = gate and wantL and not wantS
shortSig = gate and wantS and not wantL
 
type Trade
    int    dir
    float  entry
    float  stop
    float  initStop
    float  risk
    int    entryBar
    float  hi
    float  lo
    string setup
    string stopType
    box    riskBox
    box    profBox
    line   entryLn
    label  lbl
 
var Trade tr = na
var float netR = 0.0
var array<box>   boxQ = array.new<box>()
var array<line>  lnQ  = array.new<line>()
var array<label> lbQ  = array.new<label>()
 
f_fmtR(float r) =>
    (r >= 0 ? "+" : "") + str.tostring(r, "#.##") + "R"
 
f_fmtPts(float p) =>
    (p >= 0 ? "+" : "") + str.tostring(p, "#.##")
 
f_open(int d, float anchor, string setup) =>
    float entry = close
    float dist  = 0.0
    if stopMode == "ATR only" or na(anchor)
        dist := stopAtrMult * atr
    else
        float sw = d == 1 ? entry - (anchor - bufTicks * tick) : (anchor + bufTicks * tick) - entry
        dist := math.max(math.min(sw, maxStopAtr * atr), minStopAtr * atr)
    dist := math.max(dist, 2 * tick)
    float stp  = math.round_to_mintick(entry - d * dist)
    float risk = math.max(math.abs(entry - stp), tick)
    Trade t = Trade.new(d, entry, stp, stp, risk, bar_index, entry, entry, setup, "SL")
    if showBoxes
        t.riskBox := box.new(bar_index, d == 1 ? entry : stp, bar_index + projBars, d == 1 ? stp : entry, border_color = color.new(riskCol, 50), border_width = 1, bgcolor = riskCol)
        t.profBox := box.new(bar_index, entry, bar_index + projBars, entry, border_color = color.new(profCol, 50), border_width = 1, bgcolor = profCol)
        t.entryLn := line.new(bar_index, entry, bar_index + projBars, entry, color = entryCol, width = 2)
        array.push(boxQ, t.riskBox)
        array.push(boxQ, t.profBox)
        array.push(lnQ, t.entryLn)
        while array.size(boxQ) > maxTrades * 2
            box.delete(array.shift(boxQ))
        while array.size(lnQ) > maxTrades
            line.delete(array.shift(lnQ))
    if showTrLbl
        t.lbl := label.new(bar_index + projBars, entry, "", style = label.style_label_left, textcolor = color.white, size = size.small)
        array.push(lbQ, t.lbl)
        while array.size(lbQ) > maxTrades
            label.delete(array.shift(lbQ))
    t
 
f_close(Trade t, float px, string why) =>
    float r = (px - t.entry) * t.dir / t.risk
    if not na(t.profBox)
        box.set_right(t.profBox, bar_index)
        box.set_right(t.riskBox, bar_index)
        line.set_x2(t.entryLn, bar_index)
        box.set_top(t.profBox, t.dir == 1 ? math.max(px, t.entry) : t.entry)
        box.set_bottom(t.profBox, t.dir == 1 ? t.entry : math.min(px, t.entry))
        box.set_bgcolor(t.profBox, color.new(profCol, closedTr))
        box.set_bgcolor(t.riskBox, color.new(riskCol, closedTr))
        box.set_border_color(t.profBox, color.new(profCol, math.min(closedTr + 5, 100)))
        box.set_border_color(t.riskBox, color.new(riskCol, math.min(closedTr + 5, 100)))
        line.set_color(t.entryLn, color.new(entryCol, 50))
        line.set_width(t.entryLn, 1)
    if not na(t.lbl)
        label.set_xy(t.lbl, bar_index, px)
        label.set_text(t.lbl, f_fmtR(r) + " · " + why)
        label.set_color(t.lbl, r >= 0 ? color.new(#089981, 25) : color.new(#F23645, 25))
        label.set_size(t.lbl, size.tiny)
    r
 
float  plotStop   = na
float  exitMark   = na
color  exitCol    = na
bool   longEntry  = false
bool   shortEntry = false
string exitMsg    = ""
 
if not na(tr)
    plotStop := tr.stop
 
if barstate.isconfirmed and not na(tr) and bar_index > tr.entryBar
    int    d       = tr.dir
    float  exitPx  = na
    string why     = ""
    bool   viaStop = false
    bool   trendFlip = trendExit == "Opposite trend" ? trend1 == -d : trendExit == "Opposite or neutral" ? trend1 != d : false
    if d == 1 ? low <= tr.stop : high >= tr.stop
        exitPx  := d == 1 ? math.min(open, tr.stop) : math.max(open, tr.stop)
        why     := tr.stopType
        viaStop := true
    else if flattenNow
        exitPx := close
        why    := "Flat"
    else if trendFlip
        exitPx := close
        why    := "Trend"
    else if exitMom and bar_index - tr.entryBar >= 2 and (d == 1 ? (close < emaM and osc < oscSig and osc < 0 and clv < 0.35) : (close > emaM and osc > oscSig and osc > 0 and clv > 0.65))
        exitPx := close
        why    := "MomFail"
    else if maxBarsIn > 0 and bar_index - tr.entryBar >= maxBarsIn
        exitPx := close
        why    := "Time"
 
    if not na(exitPx)
        float r = f_close(tr, exitPx, why)
        netR += r
        if not viaStop
            strategy.close(d == 1 ? "Long" : "Short", comment = why)
        exitMark := exitPx
        exitCol  := r >= 0 ? #089981 : #F23645
        exitMsg  := (d == 1 ? "LONG" : "SHORT") + " exit (" + why + ") @ " + str.tostring(exitPx, format.mintick) + "  " + f_fmtR(r)
        tr := na
    else
        tr.hi := math.max(tr.hi, high)
        tr.lo := math.min(tr.lo, low)
        float  mfeR    = d == 1 ? (tr.hi - tr.entry) / tr.risk : (tr.entry - tr.lo) / tr.risk
        float  newStop = tr.stop
        string newType = tr.stopType
        if beR > 0 and mfeR >= beR
            float be = tr.entry + d * beOffTicks * tick
            if d == 1 ? be > newStop : be < newStop
                newStop := be
                newType := "BE"
        if trailMode != "Off" and mfeR >= trailStartR
            float ch = d == 1 ? tr.hi - trailAtr * atr : tr.lo + trailAtr * atr
            float st = na
            if d == 1 and not na(lastSLBar) and lastSLBar > tr.entryBar
                st := lastSL - bufTicks * tick
            if d == -1 and not na(lastSHBar) and lastSHBar > tr.entryBar
                st := lastSH + bufTicks * tick
            float cand = trailMode == "ATR chandelier" ? ch : trailMode == "Swing structure" ? st : na(st) ? ch : d == 1 ? math.max(ch, st) : math.min(ch, st)
            if not na(cand)
                cand := d == 1 ? math.min(cand, close - tick) : math.max(cand, close + tick)
                if d == 1 ? cand > newStop : cand < newStop
                    newStop := cand
                    newType := "Trail"
        tr.stop     := math.round_to_mintick(newStop)
        tr.stopType := newType
 
if barstate.isconfirmed and not na(tr) and bar_index > tr.entryBar and strategy.position_size == 0
    float r = f_close(tr, close, "Sync")
    netR += r
    tr := na
 
if longSig or shortSig
    int    nd     = longSig ? 1 : -1
    bool   fromV1 = nd == 1 ? sigL1 : sigS1
    string setup  = fromV1 ? (nd == 1 ? setupL1 : setupS1) : "Pullback"
    float  anchor = fromV1 ? (nd == 1 ? swLo : swHi) : (nd == 1 ? pbLowL : pbHighS)
    if nd == 1 and sigL2
        armL       := false
        prevLegHiL := legHiL
    if nd == -1 and sigS2
        armS       := false
        prevLegLoS := legLoS
    if not na(tr) and tr.dir == -nd and exitOpp
        int   od = tr.dir
        float r  = f_close(tr, close, "Reverse")
        netR += r
        strategy.close(od == 1 ? "Long" : "Short", comment = "Reverse")
        exitMark := close
        exitCol  := r >= 0 ? #089981 : #F23645
        exitMsg  := (od == 1 ? "LONG" : "SHORT") + " exit (Reverse) @ " + str.tostring(close, format.mintick) + "  " + f_fmtR(r)
        tr := na
    if na(tr)
        tr := f_open(nd, anchor, setup)
        lastEntryBar := bar_index
        if nd == 1
            strategy.entry("Long", strategy.long, qty = qty, comment = "L " + setup)
            longEntry := true
        else
            strategy.entry("Short", strategy.short, qty = qty, comment = "S " + setup)
            shortEntry := true
 
if barstate.isconfirmed and not na(tr)
    if tr.dir == 1
        strategy.exit("L-Stop", from_entry = "Long", stop = tr.stop, comment = tr.stopType)
    else
        strategy.exit("S-Stop", from_entry = "Short", stop = tr.stop, comment = tr.stopType)
 
if na(plotStop) and not na(tr)
    plotStop := tr.stop
 
if not na(tr)
    float pnl    = (close - tr.entry) * tr.dir
    float rNow   = pnl / tr.risk
    int   rightX = bar_index + projBars
    if not na(tr.profBox)
        box.set_right(tr.profBox, rightX)
        box.set_right(tr.riskBox, rightX)
        line.set_x2(tr.entryLn, rightX)
        box.set_top(tr.profBox, tr.dir == 1 ? math.max(close, tr.entry) : tr.entry)
        box.set_bottom(tr.profBox, tr.dir == 1 ? tr.entry : math.min(close, tr.entry))
    if not na(tr.lbl)
        label.set_xy(tr.lbl, rightX, close)
        label.set_text(tr.lbl, (tr.dir == 1 ? "LONG" : "SHORT") + " · " + tr.setup + "\n" + f_fmtPts(pnl) + " pts  " + f_fmtR(rNow) + "\n$" + str.tostring(pnl * syminfo.pointvalue * qty, "#,##0"))
        label.set_color(tr.lbl, pnl >= 0 ? color.new(#089981, 15) : color.new(#F23645, 15))
 
color tCol = trend1 == 1 ? #089981 : trend1 == -1 ? #F23645 : #787B86
plot(showEMAs ? emaF : na, "Fast EMA", color.new(#2962FF, 10), 1)
pM = plot(showEMAs ? emaM : na, "Mid EMA", color.new(tCol, 0), 2)
pS = plot(showEMAs ? emaS : na, "Slow EMA", color.new(tCol, 40), 2)
fill(pM, pS, color.new(tCol, 85), "Trend ribbon")
plot(showVWAP ? vw : na, "VWAP", color.new(#B2B5BE, 30), 2, plot.style_circles)
plot(showStop ? plotStop : na, "Active stop", color.new(#FF5252, 0), 2, plot.style_linebr)
plot(exitMark, "Exit", exitCol, 5, plot.style_circles)
plotshape(showSig and longEntry, "BUY", shape.labelup, location.belowbar, color.new(#089981, 0), text = "BUY", textcolor = color.white, size = size.small)
plotshape(showSig and shortEntry, "SELL", shape.labeldown, location.abovebar, color.new(#F23645, 0), text = "SELL", textcolor = color.white, size = size.small)
 
int bgState = useV2 and not useV1 ? trend1 : regime
color bgCol = inBlock ? color.new(#787B86, 88) : bgState == 1 ? color.new(#089981, 94) : bgState == -1 ? color.new(#F23645, 94) : na
bgcolor(showBg and ready ? bgCol : na, title = "Regime / trend / blocked window")
 
f_pos(string p) =>
    switch p
        "Top left"     => position.top_left
        "Bottom right" => position.bottom_right
        "Bottom left"  => position.bottom_left
        => position.top_right
 
f_tTxt(int t) =>
    t == 1 ? "BULLISH" : t == -1 ? "BEARISH" : "NEUTRAL"
 
f_tCol(int t) =>
    t == 1 ? #089981 : t == -1 ? #F23645 : #B2B5BE
 
f_row(table t, int row, string k, string val, color vc) =>
    table.cell(t, 0, row, k, text_color = color.new(#B2B5BE, 0), text_size = size.small, text_halign = text.align_left)
    table.cell(t, 1, row, val, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
var table dash = table.new(f_pos(dashPos), 2, 16, bgcolor = color.new(#131722, 10), border_color = color.new(#2A2E39, 0), border_width = 1, frame_color = color.new(#2A2E39, 0), frame_width = 1)
 
if showDash and barstate.islast
    color white = color.white
    color grn   = #089981
    color red   = #F23645
    bool canL = htfOkL and (useV1 or trend1 == 1)
    bool canS = htfOkS and (useV1 or trend1 == -1)
    string allowed = not entryTimeOk ? "NONE (time filter)" : canL and canS ? "LONG + SHORT" : canL ? "LONG ONLY" : canS ? "SHORT ONLY" : "NONE"
    string regTxt  = regime == 1 ? "Trend ▲" : regime == -1 ? "Trend ▼" : regime == 0 ? "Range" : "Transition"
    f_row(dash, 0, "NQ Scalper Lab", engine, white)
    f_row(dash, 1, "21/50 trend", f_tTxt(trend1), f_tCol(trend1))
    f_row(dash, 2, "HTF (" + htfTf + ")", htfMode == "Off" ? "filter off" : f_tTxt(htfTrend), f_tCol(htfTrend))
    f_row(dash, 3, "v1 regime", regTxt + "  ADX " + str.tostring(adx, "#"), white)
    f_row(dash, 4, "Allowed trades", allowed, white)
    if na(tr)
        f_row(dash, 5, "Position", "FLAT", white)
        f_row(dash, 6, "Active stop", "—", white)
        f_row(dash, 7, "Unrealized P&L", "—", white)
        f_row(dash, 8, "R multiple", "—", white)
    else
        float pnl = (close - tr.entry) * tr.dir
        float rr  = pnl / tr.risk
        f_row(dash, 5, "Position", (tr.dir == 1 ? "LONG · " : "SHORT · ") + tr.setup + " @ " + str.tostring(tr.entry, format.mintick), tr.dir == 1 ? grn : red)
        f_row(dash, 6, "Active stop (" + tr.stopType + ")", str.tostring(tr.stop, format.mintick), #FF5252)
        f_row(dash, 7, "Unrealized P&L", f_fmtPts(pnl) + " pts  $" + str.tostring(pnl * syminfo.pointvalue * qty, "#,##0"), pnl >= 0 ? grn : red)
        f_row(dash, 8, "R multiple", f_fmtR(rr), rr >= 0 ? grn : red)
    int   nT = strategy.closedtrades
    float wr = nT > 0 ? float(strategy.wintrades) / nT * 100 : 0.0
    float pf = strategy.grossloss > 0 ? strategy.grossprofit / strategy.grossloss : na
    float av = nT > 0 ? strategy.netprofit / nT : 0.0
    f_row(dash, 9, "Closed trades", str.tostring(nT), white)
    f_row(dash, 10, "Win rate", str.tostring(wr, "#.0") + "%", white)
    f_row(dash, 11, "Net P&L (after costs)", "$" + str.tostring(strategy.netprofit, "#,##0"), strategy.netprofit >= 0 ? grn : red)
    f_row(dash, 12, "Avg trade", "$" + str.tostring(av, "#,##0.00"), av >= 0 ? grn : red)
    f_row(dash, 13, "Profit factor", na(pf) ? "—" : str.tostring(pf, "#.00"), na(pf) ? white : pf >= 1 ? grn : red)
    f_row(dash, 14, "Max drawdown", "$" + str.tostring(strategy.max_drawdown, "#,##0"), red)
    f_row(dash, 15, "Net R (before costs)", f_fmtR(netR), netR >= 0 ? grn : red)
 
if exitMsg != ""
    alert("NQ Scalper Lab " + syminfo.ticker + ": " + exitMsg, alert.freq_once_per_bar_close)
if longEntry or shortEntry
    alert("NQ Scalper Lab " + syminfo.ticker + ": " + (longEntry ? "BUY " : "SELL ") + tr.setup + " @ " + str.tostring(tr.entry, format.mintick) + "  stop " + str.tostring(tr.stop, format.mintick) + "  risk " + str.tostring(tr.risk, "#.##") + " pts", alert.freq_once_per_bar_close)

← 返回列表