NQ/MNQ 1:1 Tri-Model Baseline

jimmyjames4684 · strategy · 386 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
// NQ/MNQ fixed 1:1 baseline — three entry models, identical exits
// A: Trend Pullback | B: VWAP Reclaim/Retest | C: Liquidity Sweep Reversal
// Not compiled or backtested by the author. No performance claim is made.
// Signals on confirmed bar close; market entry at next bar open.
// Stop and target are equal tick distances from the actual fill (exact 1:1).
// HTF and prior-day values use the previous completed bar (non-repainting).
// If stop and target fall inside one bar, TradingView guesses the path;
// enable Bar Magnifier in Properties to resolve it.
// Defaults: $0.62/contract/side, 1 tick slippage (MNQ-like). Edit in Properties.
strategy("NQ/MNQ 1:1 Tri-Model Baseline", shorttitle="NQ 1R ABC", overlay=true,
     initial_capital=50000, pyramiding=0,
     default_qty_type=strategy.fixed, default_qty_value=1,
     commission_type=strategy.commission.cash_per_contract, commission_value=0.62,
     slippage=1, margin_long=0, margin_short=0,
     process_orders_on_close=false, calc_on_every_tick=false, calc_on_order_fills=false,
     use_bar_magnifier=false)
 
// ───────────────────────────── Inputs ────────────────────────────────────────
string TZ = "America/New_York"
string M_A = "A: Trend Pullback"
string M_B = "B: VWAP Reclaim/Retest"
string M_C = "C: Liquidity Sweep Reversal"
 
string gM = "1 · Model"
model      = input.string(M_A, "Entry model", options=[M_A, M_B, M_C], group=gM)
allowLong  = input.bool(true, "Longs", group=gM)
allowShort = input.bool(true, "Shorts", group=gM)
 
string gS = "2 · Session (New York time)"
sessIn  = input.session("0930-1130", "Entry window", group=gS)
orIn    = input.session("0930-0945", "Opening range", group=gS)
blockOR = input.bool(true, "No entries during opening range", group=gS)
useFlat = input.bool(true, "Flatten open position in force-flat window", group=gS)
flatIn  = input.session("1550-1600", "Force-flat window", group=gS)
useDate = input.bool(false, "Limit to date range (for in-sample / out-of-sample splits)", group=gS)
startT  = input.time(timestamp("01 Jan 2025 00:00 -0500"), "From", group=gS)
endT    = input.time(timestamp("31 Dec 2025 23:59 -0500"), "To", group=gS)
 
string gT = "3 · Trend"
fastLen     = input.int(9, "Fast EMA", minval=1, group=gT)
slowLen     = input.int(21, "Slow EMA", minval=2, group=gT)
htfTf       = input.timeframe("15", "Higher timeframe", group=gT)
htfMode     = input.string("EMA", "HTF bias method", options=["EMA", "Structure", "EMA + Structure"], group=gT)
htfPiv      = input.int(2, "HTF pivot strength (Structure modes)", minval=1, group=gT)
useHTF      = input.bool(true, "Require HTF bias (models A and B)", group=gT)
cUseHTF     = input.bool(false, "Require HTF bias (model C)", group=gT)
useVwapSide = input.bool(true, "A: require close on trend side of VWAP", group=gT)
 
string gR = "4 · Regime filters"
useADX     = input.bool(true, "ADX above threshold", group=gR)
adxLen     = input.int(14, "ADX length", minval=2, group=gR)
adxMin     = input.float(20.0, "ADX threshold", step=1, group=gR)
adxRise    = input.bool(false, "ADX must be rising", group=gR)
adxLb      = input.int(3, "ADX rising lookback", minval=1, group=gR)
useAtrReg  = input.bool(false, "ATR ratio inside band", group=gR)
atrLen     = input.int(14, "ATR length", minval=2, group=gR)
atrRatMin  = input.float(0.7, "Min ATR / ATR 100-bar average", step=0.1, group=gR)
atrRatMax  = input.float(2.5, "Max ATR / ATR 100-bar average", step=0.1, group=gR)
useBBW     = input.bool(false, "Skip Bollinger compression", group=gR)
bbwPctMin  = input.float(20.0, "Min BB-width percentile (100 bars)", step=5, group=gR)
useExt     = input.bool(true, "Skip extended price (models A and B)", group=gR)
extMax     = input.float(1.5, "Max distance from slow EMA (ATR)", step=0.1, group=gR)
cUseRegime = input.bool(false, "Apply regime filters to model C", group=gR)
 
string gE = "5 · Entry details"
minCloseLoc = input.float(0.6, "Min close location in bar range (0-1)", minval=0, maxval=1, step=0.05, group=gE)
pbLb        = input.int(3, "A: pullback lookback (bars)", minval=1, group=gE)
pbDepth     = input.float(0.5, "A: max pierce beyond slow EMA (ATR)", step=0.1, group=gE)
needBreak   = input.bool(true, "A: close must clear prior bar's extreme", group=gE)
acceptBars  = input.int(2, "B: bars of acceptance after reclaim", minval=1, group=gE)
retestMax   = input.int(12, "B: max bars to wait for retest", minval=2, group=gE)
retestTol   = input.float(0.15, "B: retest tolerance around VWAP (ATR)", step=0.05, group=gE)
sweepLb     = input.int(20, "C: liquidity lookback (bars)", minval=3, group=gE)
sweepWin    = input.int(4, "C: max bars from sweep to structure shift", minval=0, group=gE)
mssLb       = input.int(3, "C: structure-shift lookback (bars)", minval=1, group=gE)
 
string gX = "6 · Stop / target (fixed 1:1)"
swingLb    = input.int(5, "Structural swing lookback (bars)", minval=1, group=gX)
bufTicks   = input.int(4, "Stop buffer (ticks)", minval=0, group=gX)
minStopATR = input.float(0.5, "Min stop distance (ATR)", step=0.1, group=gX)
maxStopATR = input.float(2.5, "Max stop distance (ATR)", step=0.1, group=gX)
useRoom    = input.bool(true, "Require room to prior-day and opening-range levels", group=gX)
roomMult   = input.float(1.0, "Required room (multiples of risk)", step=0.1, group=gX)
 
string gK = "7 · Risk"
riskUSD      = input.float(200.0, "Risk per trade ($)", minval=1, group=gK)
maxContracts = input.int(10, "Max contracts", minval=1, group=gK)
maxTradesIn  = input.int(3, "Max trades per day", minval=1, group=gK)
oneTrade     = input.bool(false, "Only one trade per day", group=gK)
maxConsec    = input.int(2, "Max consecutive losses per day", minval=1, group=gK)
dailyLoss    = input.float(400.0, "Daily loss limit ($)", minval=1, group=gK)
 
string gF = "8 · Optional filters (off by default)"
useRV    = input.bool(false, "Relative volume filter", group=gF)
rvLen    = input.int(20, "Relative volume length", minval=2, group=gF)
rvMin    = input.float(1.2, "Min relative volume", step=0.1, group=gF)
minScore = input.int(0, "Min confluence score (0 = disabled)", minval=0, maxval=100, group=gF)
 
string gD = "9 · Display"
showDash = input.bool(true, "Dashboard", group=gD)
showLvls = input.bool(true, "Plot EMAs, VWAP, opening range", group=gD)
 
bool isA = model == M_A
bool isB = model == M_B
bool isC = model == M_C
 
// ───────────────────────────── Time ──────────────────────────────────────────
bool inSess = not na(time(timeframe.period, sessIn, TZ))
bool inOR   = not na(time(timeframe.period, orIn, TZ))
bool inFlat = not na(time(timeframe.period, flatIn, TZ))
bool inDate = not useDate or (time >= startT and time <= endT)
int  dKey   = year(time, TZ) * 10000 + month(time, TZ) * 100 + dayofmonth(time, TZ)
bool newDay = dKey != dKey[1]
 
// ───────────────────────────── Core series ───────────────────────────────────
float emaF = ta.ema(close, fastLen)
float emaS = ta.ema(close, slowLen)
float vw   = ta.vwap(hlc3)
float atr  = ta.atr(atrLen)
float atrBase  = ta.sma(atr, 100)
float atrRatio = atrBase > 0 ? atr / atrBase : na
[diP, diM, adx] = ta.dmi(adxLen, adxLen)
bool  adxRising = adx > adx[adxLb]
float bbw     = ta.bbw(close, 20, 2.0)
float bbwRank = ta.percentrank(bbw, 100)
float volAvg  = ta.sma(volume, rvLen)
float relVol  = volAvg > 0 ? volume / volAvg : na
float rng  = high - low
float locL = rng > 0 ? (close - low) / rng : 0.5
float locS = rng > 0 ? (high - close) / rng : 0.5
bool  vwUp = vw > vw[3]
bool  vwDn = vw < vw[3]
 
// ───────────────────────────── Higher timeframe (non-repainting) ─────────────
f_htf() =>
    float eF = ta.ema(close, fastLen)
    float eS = ta.ema(close, slowLen)
    float ph = ta.pivothigh(high, htfPiv, htfPiv)
    float pl = ta.pivotlow(low, htfPiv, htfPiv)
    var float ph1 = na
    var float ph2 = na
    var float pl1 = na
    var float pl2 = na
    if not na(ph)
        ph2 := ph1
        ph1 := ph
    if not na(pl)
        pl2 := pl1
        pl1 := pl
    bool sUp = ph1 > ph2 and pl1 > pl2
    bool sDn = ph1 < ph2 and pl1 < pl2
    int bias = close > eS and eF > eS ? 1 : close < eS and eF < eS ? -1 : 0
    int strc = sUp ? 1 : sDn ? -1 : 0
    [bias[1], strc[1]]
 
[htfEma, htfStr] = request.security(syminfo.tickerid, htfTf, f_htf(), lookahead=barmerge.lookahead_on)
[pdh, pdl]       = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
 
bool htfUp = htfMode == "EMA" ? htfEma == 1 : htfMode == "Structure" ? htfStr == 1 : (htfEma == 1 and htfStr == 1)
bool htfDn = htfMode == "EMA" ? htfEma == -1 : htfMode == "Structure" ? htfStr == -1 : (htfEma == -1 and htfStr == -1)
 
// ───────────────────────────── Opening range ─────────────────────────────────
var float orH = na
var float orL = na
if newDay
    orH := na
    orL := na
if inOR
    orH := na(orH) ? high : math.max(orH, high)
    orL := na(orL) ? low : math.min(orL, low)
 
// ───────────────────────────── Regime ────────────────────────────────────────
bool adxOK    = not useADX or (adx > adxMin and (not adxRise or adxRising))
bool atrOK    = not useAtrReg or (atrRatio >= atrRatMin and atrRatio <= atrRatMax)
bool bbOK     = not useBBW or bbwRank >= bbwPctMin
bool regimeOK = adxOK and atrOK and bbOK
bool regUse   = isC and not cUseRegime ? true : regimeOK
 
// ───────────────────────────── Model A: trend pullback ───────────────────────
float touchLn = math.sum(low <= emaF ? 1.0 : 0.0, pbLb)
float touchSn = math.sum(high >= emaF ? 1.0 : 0.0, pbLb)
float lowPb   = ta.lowest(low, pbLb)
float highPb  = ta.highest(high, pbLb)
bool aLong  = emaF > emaS and (not useVwapSide or close > vw) and touchLn > 0 and lowPb >= emaS - pbDepth * atr and close > open and close > emaF and locL >= minCloseLoc and (not needBreak or close > high[1])
bool aShort = emaF < emaS and (not useVwapSide or close < vw) and touchSn > 0 and highPb <= emaS + pbDepth * atr and close < open and close < emaF and locS >= minCloseLoc and (not needBreak or close < low[1])
 
// ───────────────────────────── Model B: VWAP reclaim / retest ────────────────
bool xUp = ta.crossover(close, vw)
bool xDn = ta.crossunder(close, vw)
var int recL = na
var int recS = na
if xUp
    recL := bar_index
    recS := na
if xDn
    recS := bar_index
    recL := na
if not na(recL) and bar_index - recL > retestMax
    recL := na
if not na(recS) and bar_index - recS > retestMax
    recS := na
bool bLong  = not na(recL) and bar_index - recL >= acceptBars and low <= vw + retestTol * atr and close > vw and close > open and locL >= minCloseLoc
bool bShort = not na(recS) and bar_index - recS >= acceptBars and high >= vw - retestTol * atr and close < vw and close < open and locS >= minCloseLoc
 
// ───────────────────────────── Model C: liquidity sweep reversal ─────────────
float liqLo = ta.lowest(low, sweepLb)[1]
float liqHi = ta.highest(high, sweepLb)[1]
float mssHi = ta.highest(high, mssLb)[1]
float mssLo = ta.lowest(low, mssLb)[1]
var int   swBarL = na
var float swLvlL = na
var int   swBarS = na
var float swLvlS = na
if low < liqLo
    swBarL := bar_index
    swLvlL := liqLo
if high > liqHi
    swBarS := bar_index
    swLvlS := liqHi
if not na(swBarL) and bar_index - swBarL > sweepWin
    swBarL := na
if not na(swBarS) and bar_index - swBarS > sweepWin
    swBarS := na
bool cLong  = not na(swBarL) and close > swLvlL and close > mssHi and close > open
bool cShort = not na(swBarS) and close < swLvlS and close < mssLo and close < open
 
// ───────────────────────────── Structural stop, identical for all models ─────
float swLo  = ta.lowest(low, swingLb)
float swHi  = ta.highest(high, swingLb)
float stopL = swLo - bufTicks * syminfo.mintick
float stopS = swHi + bufTicks * syminfo.mintick
float distL = close - stopL
float distS = stopS - close
int ticksL  = int(math.round(distL / syminfo.mintick))
int ticksS  = int(math.round(distS / syminfo.mintick))
bool stopOKL = ticksL > 0 and distL >= minStopATR * atr and distL <= maxStopATR * atr
bool stopOKS = ticksS > 0 and distS >= minStopATR * atr and distS <= maxStopATR * atr
 
// Room: no opposing prior-day / opening-range level between entry and target
f_blockUp(float lvl, float d) =>
    not na(lvl) and lvl > close and lvl - close < d
f_blockDn(float lvl, float d) =>
    not na(lvl) and lvl < close and close - lvl < d
bool roomL = not useRoom or not (f_blockUp(pdh, roomMult * distL) or f_blockUp(orH, roomMult * distL))
bool roomS = not useRoom or not (f_blockDn(pdl, roomMult * distS) or f_blockDn(orL, roomMult * distS))
 
bool extOKL = isC or not useExt or (close - emaS) <= extMax * atr
bool extOKS = isC or not useExt or (emaS - close) <= extMax * atr
bool rvOK   = not useRV or relVol >= rvMin
 
// Confluence score (unvalidated; disabled unless Min score > 0)
int scoreL = (htfUp ? 25 : 0) + (adx > adxMin and adxRising ? 20 : 0) + (close > vw and vwUp ? 20 : 0) + (relVol >= rvMin ? 15 : 0) + (locL >= 0.7 ? 20 : 0)
int scoreS = (htfDn ? 25 : 0) + (adx > adxMin and adxRising ? 20 : 0) + (close < vw and vwDn ? 20 : 0) + (relVol >= rvMin ? 15 : 0) + (locS >= 0.7 ? 20 : 0)
 
bool rawL = isA ? aLong : isB ? bLong : cLong
bool rawS = isA ? aShort : isB ? bShort : cShort
bool htfOKL = isC ? (not cUseHTF or htfUp) : (not useHTF or htfUp)
bool htfOKS = isC ? (not cUseHTF or htfDn) : (not useHTF or htfDn)
 
bool longSig  = allowLong and rawL and htfOKL and regUse and extOKL and stopOKL and roomL and rvOK and scoreL >= minScore
bool shortSig = allowShort and rawS and htfOKS and regUse and extOKS and stopOKS and roomS and rvOK and scoreS >= minScore
 
// ───────────────────────────── Daily risk state ──────────────────────────────
var int   tradesToday = 0
var int   consecLoss  = 0
var float dayStartNet = 0.0
var int nLong  = 0
var int wLong  = 0
var int nShort = 0
var int wShort = 0
 
int newClosed = strategy.closedtrades - nz(strategy.closedtrades[1])
if newClosed > 0
    for i = strategy.closedtrades - newClosed to strategy.closedtrades - 1
        float p = strategy.closedtrades.profit(i)
        if strategy.closedtrades.size(i) > 0
            nLong += 1
            if p > 0
                wLong += 1
        else
            nShort += 1
            if p > 0
                wShort += 1
        if p < 0
            consecLoss += 1
        else
            consecLoss := 0
 
if newDay
    tradesToday := 0
    consecLoss  := 0
    dayStartNet := strategy.netprofit
 
float dayPnL  = strategy.netprofit - dayStartNet
int maxTrades = oneTrade ? 1 : maxTradesIn
 
f_qty(int ticks) =>
    float perContract = ticks * syminfo.mintick * syminfo.pointvalue
    float budget = math.min(riskUSD, dailyLoss + dayPnL)
    int q = perContract > 0 and budget > 0 ? int(math.floor(budget / perContract)) : 0
    math.min(q, maxContracts)
 
int qtyL = f_qty(ticksL)
int qtyS = f_qty(ticksS)
 
bool canTrade = barstate.isconfirmed and inSess and inDate and not (blockOR and inOR) and not inFlat and strategy.position_size == 0 and strategy.opentrades == 0 and tradesToday < maxTrades and consecLoss < maxConsec and dayPnL > -dailyLoss
 
// ───────────────────────────── Orders ────────────────────────────────────────
bool goL = false
bool goS = false
var int activeTicks = na
 
if canTrade and longSig and not shortSig and qtyL >= 1
    strategy.entry("L", strategy.long, qty=qtyL)
    strategy.exit("L exit", from_entry="L", loss=ticksL, profit=ticksL)
    tradesToday += 1
    activeTicks := ticksL
    goL := true
else if canTrade and shortSig and not longSig and qtyS >= 1
    strategy.entry("S", strategy.short, qty=qtyS)
    strategy.exit("S exit", from_entry="S", loss=ticksS, profit=ticksS)
    tradesToday += 1
    activeTicks := ticksS
    goS := true
 
// One signal per setup for the stateful models
if goL
    recL := na
    swBarL := na
if goS
    recS := na
    swBarS := na
 
if useFlat and inFlat and strategy.position_size != 0
    strategy.close_all(comment="Force flat")
 
// ───────────────────────────── Visuals ───────────────────────────────────────
var float slPx = na
var float tpPx = na
bool opened = strategy.position_size != 0 and strategy.position_size[1] == 0
if opened and not na(activeTicks)
    float r = activeTicks * syminfo.mintick
    float e = strategy.position_avg_price
    slPx := strategy.position_size > 0 ? e - r : e + r
    tpPx := strategy.position_size > 0 ? e + r : e - r
if strategy.position_size == 0
    slPx := na
    tpPx := na
 
plot(showLvls ? emaF : na, "Fast EMA", color=color.new(color.aqua, 0))
plot(showLvls ? emaS : na, "Slow EMA", color=color.new(color.orange, 0))
plot(showLvls ? vw : na, "VWAP", color=color.new(color.purple, 0), linewidth=2)
plot(showLvls ? orH : na, "OR high", color=color.new(color.gray, 30), style=plot.style_linebr)
plot(showLvls ? orL : na, "OR low", color=color.new(color.gray, 30), style=plot.style_linebr)
plot(slPx, "Stop", color=color.red, style=plot.style_linebr, linewidth=2)
plot(tpPx, "Target", color=color.green, style=plot.style_linebr, linewidth=2)
plotshape(goL, "Long signal", shape.triangleup, location.belowbar, color.green, size=size.small, text="L")
plotshape(goS, "Short signal", shape.triangledown, location.abovebar, color.red, size=size.small, text="S")
bgcolor(inSess and inDate ? color.new(color.blue, 94) : na, title="Entry window")
 
// ───────────────────────────── Dashboard ─────────────────────────────────────
var table dash = table.new(position.top_right, 2, 13, bgcolor=color.new(color.black, 15), border_width=1, border_color=color.new(color.gray, 60))
f_row(int r, string k, string v) =>
    table.cell(dash, 0, r, k, text_color=color.silver, text_halign=text.align_left, text_size=size.small)
    table.cell(dash, 1, r, v, text_color=color.white, text_halign=text.align_right, text_size=size.small)
f_pct(int w, int n) =>
    n > 0 ? str.tostring(100.0 * w / n, "#.0") + "%" : "-"
 
if showDash and barstate.islast
    int n = strategy.closedtrades
    string regime = adx > adxMin ? (adxRising ? "Trending (ADX rising)" : "Trending") : bbwRank < bbwPctMin ? "Compressed" : "Range / chop"
    string biasTx = htfUp ? "Bullish" : htfDn ? "Bearish" : "Neutral"
    f_row(0, "Model", str.substring(model, 0, 1) + (useDate ? " (date-limited)" : ""))
    f_row(1, "Total trades", str.tostring(n))
    f_row(2, "Win rate", f_pct(strategy.wintrades, n))
    f_row(3, "Profit factor", strategy.grossloss > 0 ? str.tostring(strategy.grossprofit / strategy.grossloss, "#.00") : "-")
    f_row(4, "Net profit after costs", str.tostring(strategy.netprofit, "#.00"))
    f_row(5, "Max drawdown", str.tostring(strategy.max_drawdown, "#.00"))
    f_row(6, "Expectancy / trade", n > 0 ? str.tostring(strategy.netprofit / n, "#.00") : "-")
    f_row(7, "Avg win", strategy.wintrades > 0 ? str.tostring(strategy.grossprofit / strategy.wintrades, "#.00") : "-")
    f_row(8, "Avg loss", strategy.losstrades > 0 ? str.tostring(-strategy.grossloss / strategy.losstrades, "#.00") : "-")
    f_row(9, "Long win rate", f_pct(wLong, nLong) + " (" + str.tostring(nLong) + ")")
    f_row(10, "Short win rate", f_pct(wShort, nShort) + " (" + str.tostring(nShort) + ")")
    f_row(11, "Regime", regime)
    f_row(12, htfTf + "m bias", biasTx)

← 返回列表