15m FVG Displacement (1 min chart ONLY) (55% Win Rate)

everevolving365 · study · 474 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
indicator("55% WR: 15m FVG Displacement 1 to 1 (1 min chart ONLY)", shorttitle="55% WR: 15m FVG Displacement 1 to 1 (1 min chart ONLY)", overlay=true, max_bars_back=500, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// 15-minute fair value gap with displacement, 1 to 1, on a 1-minute chart, Chicago time. Built for 2 MNQ. No orders, no stats.
// 15-minute candles are counted from the 5:00 PM open. Three candles in a row on the same trading day: candle one, two and three.
// Bullish gap: candle three's low is above candle one's high, and candle two closed up.
// Bearish gap: candle three's high is below candle one's low, and candle two closed down.
// The gap must be at least 0.05% of candle three's close, and candle two's body (open to close) at least 1.5 x the average
// high-to-low range of the 20 candles before candle three.
// Trade in the gap's direction only when the last finished 1-hour candle closed on the same side of its 50 EMA
// (bullish gap: above the EMA, bearish gap: below it).
// Entry at the next 1-minute open, from 8:30 AM to 2:59 PM, first trade of the trading day (5:00 PM to 4:00 PM).
// Stop and target 0.2 x yesterday's 14-day daily ATR each. If neither hits, close at the end of the trade's 240th 1-minute bar
// (the entry bar is bar 1) or at the end of the 3:09 PM bar, whichever comes first.
// A bar that touches both the stop and the target counts as the stop. A stop gapped through after the entry bar fills at the open.
// The backtest computes the 1-hour EMA and the ATR on back-adjusted prices, so the chart's B-ADJ button on matches it exactly.
// With it off (TradingView's default) the results are the same, and some stops differ by a tick or a few after each quarterly roll.
//
// TWO KINDS OF ALERT. Each one fires once per trade, and only for a trade the indicator takes.
// 1) ROBOT ALERT, for a dynamic account: condition "Any alert() function call". Do not type a message. On the first tick of
//    every entry bar the indicator writes and sends its own message, with that trade's own stop and target distance in points:
//      {"account":"mainB","action":"buy","contract":"MNQ","size":4,"stop_points":116.00,"target_points":116.00}
//    The robot multiplies the points by 4 to get MNQ ticks. "account" is the name your robot knows the dynamic account by.
//    Set it in the inputs BEFORE creating the alert.
// 2) NORMAL ALERTS, for an account that uses the broker's fixed stop and target: condition "Normal LONG signal" or
//    "Normal SHORT signal", trigger "Once per bar", and type your own message, for example
//      {"account":"mainA","action":"buy","contract":"MNQ","size":4}
//    They fire the moment the arrow appears. The stop and target then come from the broker's settings, not from this strategy.
 
// ─────────────── inputs ───────────────
G1 = "15m FVG with displacement 1 to 1 (55.0% win rate, 4 MNQ)"
gapPct    = input.float(0.05, "Minimum gap (% of candle three's close)", minval=0.0, step=0.01, group=G1)
dispMin   = input.float(1.5, "Minimum displacement (candle two's body / average range)", minval=0.0, step=0.1, group=G1)
avgLen    = input.int(20, "Average range length (15-minute candles before candle three)", minval=1, group=G1)
h1Len     = input.int(50, "1-hour trend EMA length", minval=1, group=G1)
atrLen    = input.int(14, "Daily ATR length (days)", minval=1, group=G1)
atrMult   = input.float(0.2, "Stop and target (x daily ATR)", minval=0.01, step=0.05, group=G1)
startHHMM = input.int(830, "First entry bar (HHMM CT)", group=G1)
lastHHMM  = input.int(1459, "Last entry bar (HHMM CT)", group=G1)
barLimit  = input.int(240, "Bar limit (out at the close of this bar of the trade, the entry bar is bar 1)", minval=1, group=G1)
exitHHMM  = input.int(1509, "Time exit (HHMM CT, at the close of this bar)", group=G1)
qty       = input.int(2, "Size (MNQ): on the label and sent to the robot", minval=1, group=G1)
 
G0 = "Robot alert"
acctName = input.string("mainB", "Account name sent to the robot (must match the robot's name for the dynamic account)", group=G0)
secretIn = input.string("", "Webhook secret (only if your robot uses one, otherwise leave empty)", group=G0)
 
G2 = "Display"
showLevels = input.bool(true, "Draw take profit and stop loss lines", group=G2)
showBox    = input.bool(true, "Draw the fair value gap box", group=G2)
showH1     = input.bool(true, "Plot the 1-hour 50 EMA", group=G2)
showTrend  = input.bool(false, "Tint the background by the 1-hour trend", group=G2)
 
tz = "America/Chicago"
if not (timeframe.isminutes and timeframe.multiplier == 1)
    runtime.error("Use a 1-minute chart. The strategy fills and exits on 1-minute bars.")
 
gapMin = gapPct / 100
toMin(int hhmm) => math.floor(hhmm / 100) * 60 + hhmm % 100
// the trading day runs 5:00 PM to 4:00 PM CT, so a bar's trading date is the calendar date 7 hours after it opens
tradeDate(int t) =>
    int t7 = t + 7 * 3600000
    year(t7, tz) * 10000 + month(t7, tz) * 100 + dayofmonth(t7, tz)
openMin  = hour(time, tz) * 60 + minute(time, tz)
closeMin = hour(time_close, tz) * 60 + minute(time_close, tz)
newDay   = bar_index == 0 or tradeDate(time) != tradeDate(time[1])
exitMin  = toMin(exitHHMM)
startMin = toMin(startHHMM)
lastMin  = toMin(lastHHMM)
var int dayKey = 0
if newDay
    dayKey += 1
// 15-minute and 1-hour candles counted from the 5:00 PM open, on the quarter hour and the hour
bucket15 = dayKey * 100 + math.floor(((openMin - 1020 + 1440) % 1440) / 15)
bucket60 = dayKey * 100 + math.floor(((openMin - 1020 + 1440) % 1440) / 60)
// an entry bar must open inside the entry window (8:30 AM to 2:59 PM by default)
entryOK(int m) => m >= startMin and m <= lastMin
 
// yesterday's daily ATR as a share of yesterday's close, fixed for the whole trading day so nothing repaints
dAtrF = request.security(syminfo.tickerid, "D", ta.atr(atrLen)[1] / close[1], lookahead=barmerge.lookahead_on)
atrF  = na(dAtrF) ? 0.015 : math.max(0.004, math.min(0.06, dAtrF))
 
// target and stop rounded outward to the tick grid, so a touch triggers exactly where the ATR distance is reached
tickUp(float x) => math.ceil(x / syminfo.mintick - 1e-9) * syminfo.mintick
tickDn(float x) => math.floor(x / syminfo.mintick + 1e-9) * syminfo.mintick
// the take profit and stop loss for a trade in direction dir entered at px: the lines on the chart and the robot message both use these two
tpAt(int dir, float px) =>
    float d = atrMult * atrF
    dir == 1 ? tickUp(px * (1 + d)) : tickDn(px * (1 - d))
slAt(int dir, float px) =>
    float d = atrMult * atrF
    dir == 1 ? tickDn(px * (1 - d)) : tickUp(px * (1 + d))
fmtPx(float p) => str.tostring(p, format.mintick)
fmtPts(float v) => (v >= 0 ? "+" : "") + str.tostring(v, "0.00")
exitH    = math.floor(exitHHMM / 100)
exitM    = exitHHMM % 100
exitText = str.tostring(exitH > 12 ? exitH - 12 : exitH) + ":" + (exitM < 10 ? "0" : "") + str.tostring(exitM) + (exitH >= 12 ? " PM" : " AM")
 
// ─────────────── types ───────────────
// the 15-minute candle being built
type Bar15
    int   bk = na
    bool  closed = true
    int   dk = na
    int   t0 = na
    float o = na
    float h = na
    float l = na
    float c = na
 
// the two finished candles before the next candle three (fields ending in 1: candle two, ending in 2: candle one),
// the high-to-low ranges of the last finished candles, and the box of the last gap found
type Fvg
    bool  has1 = false
    int   dk1 = na
    int   t1 = na
    float o1 = na
    float h1 = na
    float l1 = na
    float c1 = na
    bool  has2 = false
    int   dk2 = na
    int   t2 = na
    float h2 = na
    float l2 = na
    array<float> rngs
    float gTop = na
    float gBot = na
    int   gLeft = na
 
type Bar60
    int   bk = na
    bool  closed = true
    float c = na
    float e = na
    int   trend = 0
 
// used twice: S holds a signal waiting for its fill, T holds the open trade
type Trade
    int   dir = 0
    bool  pending = false
    bool  live = false
    float entry = na
    float tp = na
    float sl = na
    int   entryBar = na
    float gTop = na
    float gBot = na
    int   gLeft = na
    label arrow = na
    label info = na
    line  tpLine = na
    line  slLine = na
    line  eLine = na
    box   gBox = na
 
// candle three (c3) has finished: +1 bullish gap with displacement, -1 bearish, 0 none, and the gap's top, bottom and left edge
fvgCheck(Fvg st, Bar15 c3) =>
    int   x   = 0
    float top = na
    float bot = na
    int   lft = na
    if st.has1 and st.has2 and st.dk2 == c3.dk
        float tot = 0.0
        for v in st.rngs
            tot += v
        int   n    = array.size(st.rngs)
        float avg  = n > 0 ? tot / n : c3.h - c3.l
        float disp = avg > 0 ? math.abs(st.c1 - st.o1) / avg : 0.0
        if c3.l > st.h2 and st.c1 > st.o1
            if (c3.l - st.h2) / c3.c >= gapMin and disp >= dispMin
                x   := 1
                top := c3.l
                bot := st.h2
                lft := st.t2
        else if c3.h < st.l2 and st.c1 < st.o1
            if (st.l2 - c3.h) / c3.c >= gapMin and disp >= dispMin
                x   := -1
                top := st.l2
                bot := c3.h
                lft := st.t2
    [x, top, bot, lft]
 
// a 15-minute candle has finished: check it as candle three, then it becomes candle two (and candle two becomes candle one)
finalize15(Fvg st, Bar15 b) =>
    [x, top, bot, lft] = fvgCheck(st, b)
    array.push(st.rngs, b.h - b.l)
    if array.size(st.rngs) > avgLen
        array.shift(st.rngs)
    st.has2  := st.has1
    st.dk2   := st.dk1
    st.t2    := st.t1
    st.h2    := st.h1
    st.l2    := st.l1
    st.has1  := true
    st.dk1   := b.dk
    st.t1    := b.t0
    st.o1    := b.o
    st.h1    := b.h
    st.l1    := b.l
    st.c1    := b.c
    st.gTop  := top
    st.gBot  := bot
    st.gLeft := lft
    b.closed := true
    x
 
// the gap finalize15() will report for a candle that still has to be finished, worked out without changing anything
peekGap(Fvg st, Bar15 c3) =>
    [x, top, bot, lft] = fvgCheck(st, c3)
    x
 
// a 1-hour candle has finished: its 50 EMA and the trend (+1 closed above the EMA, -1 below)
finalize60(Bar60 b) =>
    b.e      := na(b.e) ? b.c : b.e + 2.0 / (h1Len + 1) * (b.c - b.e)
    b.trend  := int(math.sign(b.c - b.e))
    b.closed := true
    b.trend
 
// the trend finalize60() will report for an hour that still has to be finished, worked out without changing anything
peekTrend(Bar60 b) =>
    float e2 = na(b.e) ? b.c : b.e + 2.0 / (h1Len + 1) * (b.c - b.e)
    int(math.sign(b.c - e2))
 
setLevels(Trade t, float px) =>
    t.tp := tpAt(t.dir, px)
    t.sl := slAt(t.dir, px)
    true
 
infoText(Trade t, float px, bool exact) =>
    string s = t.dir == 1 ? "LONG" : "SHORT"
    string head = s + " " + str.tostring(qty) + " MNQ " + (exact ? "@ " + fmtPx(px) : "at the next open, about " + fmtPx(px))
    head + "\nTP " + fmtPx(t.tp) + " (" + fmtPts(math.abs(t.tp - px)) + ")" + "\nSL " + fmtPx(t.sl) + " (-" + str.tostring(math.abs(px - t.sl), "0.00") + ")" + "\nTime exit " + exitText + " or bar " + str.tostring(barLimit)
 
// the message the robot reads: buy or sell, the size, and this trade's own stop and target distance in points from the entry at px
robotText(int dir, float px) =>
    string act = dir == 1 ? "buy" : "sell"
    string stopPts = str.tostring(math.abs(px - slAt(dir, px)), "0.00")
    string tgtPts  = str.tostring(math.abs(tpAt(dir, px) - px), "0.00")
    string sec = secretIn == "" ? "" : ',"secret":"' + secretIn + '"'
    '{"account":"' + acctName + '","action":"' + act + '","contract":"MNQ","size":' + str.tostring(qty) + ',"stop_points":' + stopPts + ',"target_points":' + tgtPts + sec + '}'
 
// the signal: arrow, gap box, take profit line, stop loss line and the trade label, drawn on the bar where the conditions are met
markSignal(Trade s, float px) =>
    setLevels(s, px)
    s.arrow := label.new(time, close, "", xloc=xloc.bar_time, yloc=s.dir == 1 ? yloc.belowbar : yloc.abovebar, style=s.dir == 1 ? label.style_triangleup : label.style_triangledown, color=s.dir == 1 ? color.lime : color.red, size=size.normal)
    if showBox and not na(s.gTop)
        s.gBox := box.new(s.gLeft, s.gTop, time_close, s.gBot, xloc=xloc.bar_time, border_color=s.dir == 1 ? color.new(color.blue, 30) : color.new(color.maroon, 30), bgcolor=s.dir == 1 ? color.new(color.blue, 82) : color.new(color.maroon, 82))
    if showLevels
        s.tpLine := line.new(time, s.tp, time_close, s.tp, xloc=xloc.bar_time, color=color.new(color.green, 0), width=2)
        s.slLine := line.new(time, s.sl, time_close, s.sl, xloc=xloc.bar_time, color=color.new(color.red, 0), width=2)
        s.eLine  := line.new(time, px, time_close, px, xloc=xloc.bar_time, color=color.new(color.white, 30), width=1, style=line.style_dotted)
    s.info := label.new(time, s.sl, infoText(s, px, false), xloc=xloc.bar_time, style=s.dir == 1 ? label.style_label_up : label.style_label_down, color=s.dir == 1 ? color.new(color.blue, 0) : color.new(color.maroon, 0), textcolor=color.white, size=size.small)
    true
 
clearRefs(Trade t) =>
    t.pending := false
    t.dir     := 0
    t.gTop    := na
    t.gBot    := na
    t.gLeft   := na
    t.arrow   := na
    t.info    := na
    t.tpLine  := na
    t.slLine  := na
    t.eLine   := na
    t.gBox    := na
    true
 
// a signal that did not become a trade (the day already traded, a trade is open, outside the entry window, or a new trading
// day started before the fill): remove its drawings
discardSignal(Trade s) =>
    if not na(s.arrow)
        label.delete(s.arrow)
    if not na(s.info)
        label.delete(s.info)
    if not na(s.tpLine)
        line.delete(s.tpLine)
    if not na(s.slLine)
        line.delete(s.slLine)
    if not na(s.eLine)
        line.delete(s.eLine)
    if not na(s.gBox)
        box.delete(s.gBox)
    clearRefs(s)
 
// the fill at this bar's open: the signal's drawings become the trade's, and take profit and stop loss move to the exact entry price
fillTrade(Trade s, Trade t) =>
    t.dir      := s.dir
    t.arrow    := s.arrow
    t.info     := s.info
    t.tpLine   := s.tpLine
    t.slLine   := s.slLine
    t.eLine    := s.eLine
    t.gBox     := s.gBox
    clearRefs(s)
    t.live     := true
    t.entry    := open
    t.entryBar := bar_index
    setLevels(t, t.entry)
    if not na(t.tpLine)
        line.set_y1(t.tpLine, t.tp)
        line.set_y2(t.tpLine, t.tp)
        line.set_x2(t.tpLine, time_close)
    if not na(t.slLine)
        line.set_y1(t.slLine, t.sl)
        line.set_y2(t.slLine, t.sl)
        line.set_x2(t.slLine, time_close)
    if not na(t.eLine)
        line.set_y1(t.eLine, t.entry)
        line.set_y2(t.eLine, t.entry)
        line.set_x2(t.eLine, time_close)
        line.set_style(t.eLine, line.style_solid)
    if not na(t.info)
        label.set_text(t.info, infoText(t, t.entry, true))
        label.set_y(t.info, t.sl)
    true
 
closeTrade(Trade t, float px, string why, int xTime) =>
    pts = (px - t.entry) * t.dir
    if not na(t.tpLine)
        line.set_x2(t.tpLine, xTime)
    if not na(t.slLine)
        line.set_x2(t.slLine, xTime)
    if not na(t.eLine)
        line.set_x2(t.eLine, xTime)
    label.new(xTime, px, why + "\n" + fmtPts(pts) + " pts", xloc=xloc.bar_time, style=label.style_label_left, color=pts > 0 ? color.new(color.green, 0) : color.new(color.red, 0), textcolor=color.white, size=size.small)
    t.live := false
    clearRefs(t)
 
// stop first (a bar that touches both counts as the stop), then target, then the time exit at the close of the exit bar
// or of the trade's last allowed bar, whichever comes first
manage(Trade t) =>
    bool done  = false
    bool after = bar_index > t.entryBar
    if t.dir == 1
        if low <= t.sl
            closeTrade(t, after and open <= t.sl ? open : t.sl, "Stop loss", time_close)
            done := true
        else if high >= t.tp
            closeTrade(t, t.tp, "Take profit", time_close)
            done := true
    else
        if high >= t.sl
            closeTrade(t, after and open >= t.sl ? open : t.sl, "Stop loss", time_close)
            done := true
        else if low <= t.tp
            closeTrade(t, t.tp, "Take profit", time_close)
            done := true
    if not done and (openMin == exitMin or bar_index - t.entryBar + 1 >= barLimit)
        closeTrade(t, close, openMin == exitMin ? "Time exit" : "Bar limit", time_close)
        done := true
    if not done
        if not na(t.tpLine)
            line.set_x2(t.tpLine, time_close)
        if not na(t.slLine)
            line.set_x2(t.slLine, time_close)
        if not na(t.eLine)
            line.set_x2(t.eLine, time_close)
    done
 
// ─────────────── engine state ───────────────
var Bar15 K  = Bar15.new()
var Fvg   F  = Fvg.new(rngs = array.new<float>())
var Bar60 Hh = Bar60.new()
var Trade S  = Trade.new()
var Trade T  = Trade.new()
var bool  doneToday = false
 
bool longSig  = false
bool shortSig = false
 
// ─────────────── robot alert ───────────────
// Decided on the first tick of a bar, before the engine below touches anything, from what the last finished bar left behind:
// the waiting signal, a candle about to be finished late, the time, and whether the day has traded. These lines repeat steps
// 1 to 4 of the engine without changing anything, so the alert fires on exactly the bar where the engine takes the trade, at its open.
bool late60   = not na(Hh.bk) and bucket60 != Hh.bk and not Hh.closed
bool late15   = not na(K.bk) and bucket15 != K.bk and not K.closed
int  trendK   = late60 ? peekTrend(Hh) : Hh.trend
int  lateX    = late15 ? peekGap(F, K) : 0
int  lateDir  = lateX != 0 and trendK == lateX ? lateX : 0
bool pendNow  = S.pending or lateDir != 0
int  dirNow   = S.pending ? S.dir : lateDir
bool liveNow  = T.live and not newDay and not (openMin > exitMin and openMin < 17 * 60)
bool doneNow  = not newDay and doneToday
bool enterNow = pendNow and entryOK(openMin) and not newDay and not doneNow and not liveNow
// the same entry for the normal alerts below, when no arrow at the signal candle's close carries it:
// a candle whose last minute never printed, or a signal whose next bar opened later than the minute after
bool lateEntry = enterNow and (lateDir != 0 or na(S.arrow))
if enterNow
    alert(robotText(dirNow, open), alert.freq_once_per_bar)
 
// ─────────────── engine ───────────────
if barstate.isconfirmed
    // 1) a new trading day at 5:00 PM: a trade still open (only after an early holiday close) ends at the last session's final close
    if newDay
        if T.live
            closeTrade(T, close[1], "Session end", time_close[1])
        doneToday := false
    // 2) the time exit when no bar printed at the exit minute: out at the close of the last bar before it
    if T.live and not newDay and openMin > exitMin and openMin < 17 * 60
        closeTrade(T, close[1], "Time exit", time_close[1])
    // 3) candles whose last minute never printed are finished here, the hour first: the signal fills at this bar's open
    if not na(Hh.bk) and bucket60 != Hh.bk and not Hh.closed
        finalize60(Hh)
    if not na(K.bk) and bucket15 != K.bk and not K.closed
        int xl = finalize15(F, K)
        if xl != 0 and Hh.trend == xl and not S.pending
            S.pending := true
            S.dir     := xl
            S.gTop    := F.gTop
            S.gBot    := F.gBot
            S.gLeft   := F.gLeft
    if na(Hh.bk) or bucket60 != Hh.bk
        Hh.bk     := bucket60
        Hh.c      := close
        Hh.closed := false
    else
        Hh.c := close
    if na(K.bk) or bucket15 != K.bk
        K.bk     := bucket15
        K.dk     := dayKey
        K.t0     := time
        K.o      := open
        K.h      := high
        K.l      := low
        K.c      := close
        K.closed := false
    else
        K.h := math.max(K.h, high)
        K.l := math.min(K.l, low)
        K.c := close
    // 4) the fill at this bar's open: inside the entry window, the same trading day as the signal, the day's first trade, no open trade
    if S.pending
        if entryOK(openMin) and not newDay and not doneToday and not T.live
            if na(S.arrow)
                markSignal(S, open)
                longSig  := S.dir == 1
                shortSig := S.dir == -1
            fillTrade(S, T)
            doneToday := true
        else
            discardSignal(S)
    // 5) exits on this bar
    if T.live
        manage(T)
    // 6) candles close on this bar, the hour first: the signal shows now and fills at the next bar's open
    if not Hh.closed and closeMin % 60 == 0
        finalize60(Hh)
    if not K.closed and closeMin % 15 == 0
        int x = finalize15(F, K)
        if x != 0 and Hh.trend == x and not S.pending
            S.pending := true
            S.dir     := x
            S.gTop    := F.gTop
            S.gBot    := F.gBot
            S.gLeft   := F.gLeft
            if entryOK(closeMin) and not doneToday and not T.live
                markSignal(S, close)
                longSig  := S.dir == 1
                shortSig := S.dir == -1
 
// ─────────────── visuals ───────────────
plot(showH1 ? Hh.e : na, "1h 50 EMA", color=color.new(color.orange, 0), linewidth=2, style=plot.style_stepline)
bgcolor(showTrend and Hh.trend == 1 ? color.new(color.green, 94) : showTrend and Hh.trend == -1 ? color.new(color.red, 94) : na, title="1-hour trend")
 
// ─────────────── normal alerts ───────────────
// For an account that uses the broker's fixed stop and target: pick "Normal LONG signal" or "Normal SHORT signal" as the condition,
// set the trigger to "Once per bar", and type your own message. They fire the moment the arrow appears (the close of candle three,
// the same moment as the entry bar's open). When the entry is decided at a bar's open instead, they fire on that bar's first tick.
bool longAlert  = longSig  or (lateEntry and dirNow == 1)
bool shortAlert = shortSig or (lateEntry and dirNow == -1)
alertcondition(longAlert,  "Normal LONG signal",  "15m FVG displacement: LONG signal")
alertcondition(shortAlert, "Normal SHORT signal", "15m FVG displacement: SHORT signal")

← 返回列表