Xiznit Noise Band Momentum

Xiznit · strategy · 226 行 · 点赞 32 · TradingView 原页

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

Pine Script

//@version=6
strategy("Xiznit Noise Band Momentum", overlay = true,
     initial_capital = 50000, default_qty_type = strategy.fixed, default_qty_value = 1,
     commission_type = strategy.commission.cash_per_contract, commission_value = 0.75, slippage = 1,
     margin_long = 0, margin_short = 0, pyramiding = 0, calc_on_every_tick = false,
     process_orders_on_close = false, close_entries_rule = "ANY", max_bars_back = 500)
 
// ============================================================================
// Intraday momentum on the RTH session (09:30-16:00 New York).
// Each day a "noise band" is built around max/min(today's RTH open, prior RTH close).
// Band width = average absolute move from the open at the same time of day over the
// last N sessions. A close outside the band at a scheduled check time signals that the
// day is trending; the strategy trades in that direction (only with the 20-day trend),
// takes a quick profit sized off daily ATR, and re-enters on the next check while the
// move persists. Flat every day before the close. No request.security, no lookahead.
// ============================================================================
 
// ---------- Inputs ----------
gP = "Preset"
preset     = input.string("Prop Safe", "Settings preset", options = ["Prop Safe", "Higher Output", "Custom"], group = gP, tooltip = "Prop Safe: 1.0 band, 14 lookback, 30-min checks, 20-day trend, 14 ATR, TP 0.08 / SL 0.15 (~8 trades/week, lowest drawdown).\nHigher Output: 1.0 band, 20 lookback, 15-min checks, 20-day trend, 14 ATR, TP 0.10 / SL 0.15 (~10 trades/week, more profit, slightly deeper drawdowns).\nCustom: uses the Signal and Exits inputs below.")
 
gS = "Signal (Custom preset)"
vmIn       = input.float(1.0, "Noise band multiplier", minval = 0.1, step = 0.05, group = gS, tooltip = "Width of the no-trade band in multiples of the average move from the open at this time of day.")
lookbackIn = input.int(14, "Noise lookback (sessions)", minval = 5, maxval = 60, group = gS, tooltip = "Number of prior RTH sessions averaged for each time-of-day slot.")
checkIn    = input.int(30, "Check interval (minutes)", options = [15, 30, 60], group = gS, tooltip = "Entries and band exits are only evaluated on bars that close on this grid (e.g. 10:00, 10:30, ...).")
trendIn    = input.int(20, "Daily trend filter (SMA of RTH closes, 0 = off)", minval = 0, group = gS, tooltip = "Longs only above, shorts only below, the simple average of the last N completed RTH closes.")
 
gR = "Exits (Custom preset)"
datrIn     = input.int(14, "Daily ATR length", minval = 2, group = gR, tooltip = "ATR of completed RTH sessions (RMA).")
tgtIn      = input.float(0.08, "Take profit (x daily ATR)", minval = 0.01, step = 0.01, group = gR)
stopIn     = input.float(0.15, "Stop loss (x daily ATR)", minval = 0.01, step = 0.01, group = gR)
 
isSafe = preset == "Prop Safe"
isHigh = preset == "Higher Output"
vm         = isSafe ? 1.0  : isHigh ? 1.0  : vmIn
lookback   = isSafe ? 14   : isHigh ? 20   : lookbackIn
checkEvery = isSafe ? 30   : isHigh ? 15   : checkIn
trendLen   = isSafe ? 20   : isHigh ? 20   : trendIn
datrLen    = isSafe ? 14   : isHigh ? 14   : datrIn
tgtMult    = isSafe ? 0.08 : isHigh ? 0.10 : tgtIn
stopMult   = isSafe ? 0.15 : isHigh ? 0.15 : stopIn
 
gT = "Session & sizing"
qty        = input.int(1, "Contracts", minval = 1, group = gT)
firstHHMM  = input.int(1000, "First check (HHMM, New York)", minval = 935, maxval = 1555, group = gT)
lastHHMM   = input.int(1500, "Last entry check (HHMM, New York)", minval = 935, maxval = 1555, group = gT)
flatHHMM   = input.int(1555, "Flatten at (HHMM, New York)", minval = 935, maxval = 1600, group = gT, tooltip = "Positions are closed at the close of the first bar that closes at or after this time.")
maxTrades  = input.int(12, "Max entries per day", minval = 1, group = gT)
useHoliday = input.bool(true, "Early flatten on US holiday half-days", group = gT, tooltip = "On MLK, Presidents, Memorial, Juneteenth, July 3/4, Labor, Thanksgiving + day after and Christmas Eve sessions: no entries after 11:00 and flat by 11:25.")
 
gA = "Automation (Xiznit Bot JSON)"
tickerIn   = input.string("", "Webhook ticker (blank = chart ticker)", group = gA)
sendBrkt   = input.bool(true, "Send SL / TP1 in entry JSON", group = gA, tooltip = "When on, entry payloads carry sl, tp1 and tp1_qty so the bot can place a broker-side bracket. Exits (band, end-of-day, TP/SL fills) always send {\"action\":\"exit\"}.")
 
gV = "Display"
showBands  = input.bool(true, "Show noise band and VWAP", group = gV)
showTable  = input.bool(true, "Show info table", group = gV)
 
// Works on any minute chart that divides 30 (1, 2, 3, 5, 6, 10, 15, 30). The check interval must be a multiple of it.
tfm = timeframe.isminutes ? timeframe.multiplier : 0
if tfm == 0 or 30 % tfm != 0
    runtime.error("Use a 1, 2, 3, 5, 6, 10, 15 or 30-minute chart.")
if checkEvery % tfm != 0
    runtime.error("Check interval must be a multiple of the chart timeframe.")
nSlots = tfm > 0 ? int(390 / tfm) : 78
 
// ---------- Time helpers ----------
const string TZ = "America/New_York"
toMin(int hhmm) => int(hhmm / 100) * 60 + hhmm % 100
barMod   = hour(time, TZ) * 60 + minute(time, TZ)        // bar open, minutes after midnight NY
inRTH    = barMod >= 570 and barMod < 960
closeMod = barMod + tfm                                  // bar close time
dayKey   = year(time, TZ) * 10000 + month(time, TZ) * 100 + dayofmonth(time, TZ)
 
// US holiday / half-day sessions (CME equity futures close early ~13:00 ET or earlier).
// On these days: last entry check 11:00, flat by 11:25, so nothing is ever carried past the early close.
earlyClose() =>
    y   = year(time, TZ)
    mo  = month(time, TZ)
    d   = dayofmonth(time, TZ)
    dw  = dayofweek(time, TZ)               // 1 = Sunday ... 7 = Saturday
    wk  = dw >= dayofweek.monday and dw <= dayofweek.friday
    mon = dw == dayofweek.monday
    r = false
    r := r or (mo == 1 and mon and d >= 15 and d <= 21)                                    // MLK Day
    r := r or (mo == 2 and mon and d >= 15 and d <= 21)                                    // Presidents Day
    r := r or (mo == 5 and mon and d >= 25)                                                // Memorial Day
    r := r or (mo == 6 and y >= 2022 and ((d == 19 and wk) or (d == 18 and dw == dayofweek.friday) or (d == 20 and mon)))  // Juneteenth
    r := r or (mo == 7 and (((d == 3 or d == 4) and wk) or (d == 5 and mon)))              // July 3 / 4 / observed
    r := r or (mo == 9 and mon and d <= 7)                                                 // Labor Day
    r := r or (mo == 11 and ((dw == dayofweek.thursday and d >= 22 and d <= 28) or (dw == dayofweek.friday and d >= 23 and d <= 29)))  // Thanksgiving + day after
    r := r or (mo == 12 and d == 24 and wk)                                                // Christmas Eve
    r
isEarly  = useHoliday and earlyClose()
firstMod = toMin(firstHHMM)
lastMod  = isEarly ? 660 : toMin(lastHHMM)                // last check (bar close time) allowed to enter
flatMod  = isEarly ? 685 : toMin(flatHHMM)                // flatten on bar closing at/after this
 
// ---------- Daily state (RTH only) ----------
var float dOpen     = na
var float pc        = na      // prior RTH close
var float dHigh     = na
var float dLow      = na
var float dClose    = na
var float prevClose = na
var float datr      = na
var float cumPV     = 0.0
var float cumV      = 0.0
var int   lastKey   = 0
var int   tradesDay = 0
var array<float> dCloses = array.new_float()
 
// ---------- Time-of-day noise memory: one slot per chart bar of the RTH session x lookback sessions ----------
var matrix<float> mv  = matrix.new<float>(nSlots, lookback, na)
var array<int>    cnt = array.new_int(nSlots, 0)
var array<int>    ptr = array.new_int(nSlots, 0)
minObs = math.max(1, math.round(lookback * 10.0 / 14.0))
 
float sigma = na
if inRTH
    if dayKey != lastKey
        if not na(dClose)
            tr = na(prevClose) ? dHigh - dLow : math.max(dHigh - dLow, math.abs(dHigh - prevClose), math.abs(dLow - prevClose))
            datr := na(datr) ? tr : datr + (tr - datr) / datrLen
            prevClose := dClose
            pc := dClose
            dCloses.push(dClose)
            if dCloses.size() > 300
                dCloses.shift()
        dOpen     := open
        dHigh     := high
        dLow      := low
        cumPV     := 0.0
        cumV      := 0.0
        tradesDay := 0
        lastKey   := dayKey
    dHigh  := math.max(dHigh, high)
    dLow   := math.min(dLow, low)
    dClose := close
    cumPV  += hlc3 * volume
    cumV   += volume
    slot = int((barMod - 570) / tfm)
    // average of prior sessions for this slot (computed before storing today's value)
    n = cnt.get(slot)
    if n >= minObs
        s = 0.0
        for j = 0 to lookback - 1
            v = mv.get(slot, j)
            if not na(v)
                s += v
        sigma := s / n
    p = ptr.get(slot)
    mv.set(slot, p, math.abs(close / dOpen - 1))
    ptr.set(slot, (p + 1) % lookback)
    cnt.set(slot, math.min(n + 1, lookback))
 
vwapR = cumV > 0 ? cumPV / cumV : na
refHi = math.max(dOpen, nz(pc, dOpen))
refLo = math.min(dOpen, nz(pc, dOpen))
ub    = inRTH and not na(sigma) ? refHi * (1 + vm * sigma) : na
lb    = inRTH and not na(sigma) ? refLo * (1 - vm * sigma) : na
 
float dsma = na
if trendLen > 0 and dCloses.size() >= trendLen
    s2 = 0.0
    for k = dCloses.size() - trendLen to dCloses.size() - 1
        s2 += dCloses.get(k)
    dsma := s2 / trendLen
trendUp = trendLen == 0 or (not na(dsma) and close > dsma)
trendDn = trendLen == 0 or (not na(dsma) and close < dsma)
 
// ---------- Signals (evaluated on bar close only) ----------
isCheck  = inRTH and closeMod % checkEvery == 0 and closeMod >= firstMod
canEnter = isCheck and closeMod <= lastMod and closeMod < flatMod and not na(ub) and not na(datr) and tradesDay < maxTrades
longSig  = canEnter and close > ub and trendUp
shortSig = canEnter and close < lb and trendDn
exitLong  = isCheck and strategy.position_size > 0 and not na(ub) and close < math.max(ub, vwapR)
exitShort = isCheck and strategy.position_size < 0 and not na(lb) and close > math.min(lb, vwapR)
isFlatBar = (inRTH and closeMod >= flatMod) or not inRTH   // safety: never hold outside RTH
 
// ---------- JSON payloads (Universal ORB contract) ----------
tkr = tickerIn == "" ? syminfo.ticker : tickerIn
f(float x) => str.tostring(x, format.mintick)
entryJson(string act, float px, float sl, float tp) =>
    base = '{"ticker":"' + tkr + '","action":"' + act + '","price":' + f(px) + ',"qty":' + str.tostring(qty)
    sendBrkt ? base + ',"sl":' + f(sl) + ',"tp1":' + f(tp) + ',"tp1_qty":' + str.tostring(qty) + '}' : base + '}'
exitJson = '{"ticker":"' + tkr + '","action":"exit"}'
 
// ---------- Orders ----------
if isFlatBar and strategy.position_size != 0
    strategy.close_all(comment = "EOD flat", alert_message = exitJson, immediately = true)
else if exitLong
    strategy.close("Long", comment = "Band exit", alert_message = exitJson)
else if exitShort
    strategy.close("Short", comment = "Band exit", alert_message = exitJson)
else if strategy.position_size == 0 and (longSig or shortSig)
    tpTicks = math.max(1, math.round(tgtMult * datr / syminfo.mintick))
    slTicks = math.max(1, math.round(stopMult * datr / syminfo.mintick))
    tpDist  = tpTicks * syminfo.mintick
    slDist  = slTicks * syminfo.mintick
    tradesDay += 1
    if longSig
        strategy.entry("Long", strategy.long, qty = qty, alert_message = entryJson("buy", close, close - slDist, close + tpDist))
        strategy.exit("Long TP/SL", "Long", profit = tpTicks, loss = slTicks, comment_profit = "TP", comment_loss = "SL", alert_profit = exitJson, alert_loss = exitJson)
    else
        strategy.entry("Short", strategy.short, qty = qty, alert_message = entryJson("sell", close, close + slDist, close - tpDist))
        strategy.exit("Short TP/SL", "Short", profit = tpTicks, loss = slTicks, comment_profit = "TP", comment_loss = "SL", alert_profit = exitJson, alert_loss = exitJson)
 
// ---------- Visuals ----------
plot(showBands ? ub : na, "Upper noise band", color.new(color.teal, 0), 1, plot.style_linebr)
plot(showBands ? lb : na, "Lower noise band", color.new(color.maroon, 0), 1, plot.style_linebr)
plot(showBands and inRTH ? vwapR : na, "RTH VWAP", color.new(color.orange, 20), 1, plot.style_linebr)
plotshape(isCheck and showBands, "Check bar", shape.circle, location.bottom, color.new(color.gray, 60), size = size.tiny)
 
var table info = table.new(position.top_right, 2, 5, bgcolor = color.new(color.black, 80), border_width = 1)
if showTable and barstate.islast
    table.cell(info, 0, 0, "Daily ATR", text_color = color.white, text_size = size.small)
    table.cell(info, 1, 0, na(datr) ? "-" : str.tostring(datr, "#.##"), text_color = color.white, text_size = size.small)
    table.cell(info, 0, 1, "TP / SL (pts)", text_color = color.white, text_size = size.small)
    table.cell(info, 1, 1, na(datr) ? "-" : str.tostring(tgtMult * datr, "#.##") + " / " + str.tostring(stopMult * datr, "#.##"), text_color = color.white, text_size = size.small)
    table.cell(info, 0, 2, "Trend filter", text_color = color.white, text_size = size.small)
    table.cell(info, 1, 2, trendLen == 0 ? "off" : na(dsma) ? "warming up" : close > dsma ? "longs only" : "shorts only", text_color = color.white, text_size = size.small)
    table.cell(info, 0, 3, "Entries today", text_color = color.white, text_size = size.small)
    table.cell(info, 1, 3, str.tostring(tradesDay) + " / " + str.tostring(maxTrades), text_color = color.white, text_size = size.small)
    table.cell(info, 0, 4, "Band ready", text_color = color.white, text_size = size.small)
    table.cell(info, 1, 4, na(sigma) ? "no (needs history)" : "yes", text_color = color.white, text_size = size.small)

← 返回列表