本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// POST 7: one POST-only entry, 20:00 IST open and strict hourly-side EMA bias.
// Only the latest FVG box is shown; hidden first-inversion records remain intact.
// SL protects FVG + inversion + selected candle / MA / local pullback defence.
// Minimum-one-contract exception remains; cash labels show the actual USD amount.
// Validation uses synthetic Python scenarios and source review. Pine compilation
// and these exact TradingView Replay candles have not been verified here.
indicator("Pritesh NQ", "Pritesh NQ", overlay=true, max_lines_count=120, max_labels_count=160, max_boxes_count=120, dynamic_requests=true, max_bars_back=1000)
// One POST-only entry per strategy day. All decisions use confirmed 5m candles.
string G1 = "01 · Clock & sessions"
string tz = input.string("Asia/Kolkata", "Timezone (IANA)", group=G1)
int resetH = input.int(3, "Strategy reset / bias hour", minval=0, maxval=23, group=G1)
int resetM = input.int(30, "Reset minute", minval=0, maxval=59, step=5, group=G1)
string formationWindow = input.session("2000-2130", "POST FVG formation window", group=G1)
string ny = input.session("2000-0240", "NY trading session", group=G1)
// Cash amounts are gross USD estimates before fees and slippage.
string GC = "02b · Dollar risk & sizing"
float cashRiskBudget = input.float(200.0, "Risk budget per trade (USD)", minval=1.0, step=10.0, group=GC)
bool customPointValue = input.bool(false, "Override symbol dollar value per point", group=GC)
float overridePointValue = input.float(2.0, "Override USD / point / contract", minval=0.01, step=0.5, group=GC)
float cashPointValue = customPointValue ? overridePointValue : syminfo.pointvalue
bool cashModelMismatch = customPointValue and (math.abs(cashPointValue - syminfo.pointvalue) > 0.0000001 or syminfo.currency != "USD")
string G2 = "02 · Confirmation & risk"
int slopeBars = input.int(2, "15m / 30m EMA slope lookback (source bars)", minval=1, maxval=10, group=G2)
int hourlySlopeBars = input.int(1, "1H EMA slope lookback (hourly bars)", minval=1, maxval=10, group=G2)
float flatSlopePointsPerHour = input.float(1.0, "Sideways tolerance (EMA points / hour)", minval=0.0, step=0.25, group=G2, tooltip="A completed EMA is sideways when its normalized recent slope is within this tolerance, even if it moved earlier today. No ATR or chart-angle filter is used.")
float minDayMovePoints = input.float(0.0, "Minimum EMA move from daily reference (points)", minval=0.0, step=0.25, group=G2, tooltip="A trending EMA's movement from the strategy-reset reference must agree with its recent slope. Higher-priority conflicting or missing confirmation blocks lower-timeframe fallback.")
int stopBufferTicks = input.int(1, "Stop buffer beyond all 3 layers (ticks)", minval=1, maxval=100, group=G2)
int swingLen = input.int(10, "Swing range (completed 5m bars)", minval=2, maxval=100, group=G2)
bool useStructureStop = input.bool(true, "Use three-layer SL model", group=G2, tooltip="Protect the FVG far boundary and inversion wick, then choose a third defence using the policy below. This is a mechanical interpretation of the supplied video transcript, not its unspecified discretionary exceptions. OFF enables legacy comparisons.")
string thirdDefencePolicy = input.string("Nearest valid layer", "Third SL defence", options=["Nearest valid layer", "Previous candle, then MA, then swing", "Local swing only"], group=G2, tooltip="Nearest: closest valid previous 5m candle wick, completed 15m/30m/1H MA or local pullback. Previous priority: previous candle first, then nearest MA, then local pullback. Local swing only reproduces PULLBACK5. All policies place the actual SL beyond all three selected references.")
bool previousSupportOnly = input.bool(true, "Previous candle must support trade direction", group=G2, tooltip="When ON, previous candle must close bullish for LONG and bearish for SHORT; dojis are excluded. This is an explicit interpretation of the examples, not a threshold specified by the narrator. The previous candle must belong to the same strategy day. The 5m 10 EMA is never an SL reference.")
string stopPolicy = input.string("Fallback when wide", "Legacy comparison: third-layer policy", options=["Fallback when wide", "Always local swing", "Original swing / MA"], group=G2)
float maxExtraPoints = input.float(50.0, "Maximum extra distance from broad swing / MA (points)", minval=0.0, step=0.25, group=G2, tooltip="Fallback triggers when the rounded broad stop adds MORE than this distance beyond the protected FVG + inversion-candle stop. This is a trigger, not a total-risk cap.")
string counterAnchorMode = input.string("Confirmed pivot", "Local countertrend anchor", options=["Confirmed pivot", "FVG pattern only"], group=G2)
int counterPivotStrength = input.int(2, "Countertrend pivot strength (5m bars)", minval=1, maxval=10, group=G2)
int counterAnchorMaxBars = input.int(24, "Maximum countertrend anchor age (5m bars)", minval=3, maxval=200, group=G2)
float minRR = input.float(2.0, "Minimum reward / risk", minval=2.0, step=0.25, group=G2)
string G3 = "03 · Display"
bool showMA = input.bool(true, "Moving averages", group=G3)
bool showMAText = input.bool(true, "MA text", group=G3)
bool showFVG = input.bool(true, "Latest FVG only", group=G3)
bool showLiq = input.bool(false, "Liquidity levels", group=G3)
bool showEntry = input.bool(true, "Entry signals", group=G3)
bool showRisk = input.bool(true, "Entry / SL / TP lines and prices", group=G3)
bool showPanel = input.bool(true, "Bias panel", group=G3)
bool auditFVG = input.bool(false, "FVG audit markers and reasons", group=G3)
int auditLimit = input.int(20, "Retained raw FVG audit records", minval=1, maxval=30, group=G3)
int reach = input.int(16, "Trade line extension (5m bars)", minval=3, maxval=100, group=G3)
int textOffset = input.int(5, "MA text offset (bars)", minval=1, maxval=30, group=G3)
int textGap = input.int(12, "Minimum MA text spacing (ticks)", minval=1, maxval=200, group=G3)
int history = input.int(8, "Retained trade plans", minval=1, maxval=20, group=G3)
bool is5m = timeframe.isminutes and timeframe.multiplier == 5
bool below5m = timeframe.isseconds or (timeframe.isminutes and timeframe.multiplier < 5)
color bull = input.color(#45BFA3, "Bullish accent", group=G3)
color bear = input.color(#E37586, "Bearish accent", group=G3)
color slColor = #EF6475
color tpColor = #45BFA3
color muted = #9AA6B6
color purple = #B18BFA
color blue = #68A9FA
color red = #ED7D87
color green = #62C69C
// Pure helpers. A strategy day starts at the configured local reset.
f_ma() =>
ta.ema(close, 50)
f_hourlyEMA() =>
ta.ema(close, 50)
// State: +1/-1 confirmed trend, 0 recently sideways, 2 unconfirmed/missing.
// Slopes are price points/hour on completed source candles, never chart angles.
f_emaState(float value, float older, float startValue, int sourceMinutes, int lookback) =>
int state = 2
if not na(value) and not na(older) and not na(startValue)
float recentSlope = (value - older) * 60.0 / (sourceMinutes * lookback)
float fromStart = value - startValue
state := math.abs(recentSlope) <= flatSlopePointsPerHour ? 0 : recentSlope > flatSlopePointsPerHour and fromStart > minDayMovePoints ? 1 : recentSlope < -flatSlopePointsPerHour and fromStart < -minDayMovePoints ? -1 : 2
state
f_start(string s) =>
int(str.tonumber(str.substring(s, 0, 2))) * 60 + int(str.tonumber(str.substring(s, 2, 4)))
f_end(string s) =>
int(str.tonumber(str.substring(s, 5, 7))) * 60 + int(str.tonumber(str.substring(s, 7, 9)))
f_day(int t) =>
int today = timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz), resetH, resetM)
t >= today ? today : timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz) - 1, resetH, resetM)
f_sessionEnd(int t, string s) =>
int finish = f_end(s)
int minuteNow = hour(t, tz) * 60 + minute(t, tz)
int extraDay = f_start(s) >= finish and minuteNow >= f_start(s) ? 1 : 0
timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz) + extraDay, int(finish / 60), finish % 60)
// NY open belonging to this strategy day, including starts after midnight.
f_sessionOpen(int strategyDay, string s) =>
int startMinute = f_start(s)
int extraDay = startMinute < resetH * 60 + resetM ? 1 : 0
timestamp(tz, year(strategyDay, tz), month(strategyDay, tz), dayofmonth(strategyDay, tz) + extraDay, int(startMinute / 60), startMinute % 60)
// Neither stop model uses the 5m 10 EMA.
f_roundStop(int dir, float outer) =>
float buffer = stopBufferTicks * syminfo.mintick
dir == 1 ? math.floor((outer - buffer) / syminfo.mintick) * syminfo.mintick : math.ceil((outer + buffer) / syminfo.mintick) * syminfo.mintick
// Legacy comparison only.
f_stop(int dir, float entry, float fvgEdge, float candleExtreme, float swing, float counterExtreme, float ma15, float ma30, float ma60) =>
float thirdLayer = na
for p in array.from(swing, ma15, ma30, ma60)
if not na(p) and (dir == 1 ? p < entry : p > entry)
thirdLayer := na(thirdLayer) ? p : dir == 1 ? math.max(thirdLayer, p) : math.min(thirdLayer, p)
float chosen = na
bool firstTwoValid = not na(fvgEdge) and not na(candleExtreme) and (dir == 1 ? fvgEdge <= entry and candleExtreme <= entry : fvgEdge >= entry and candleExtreme >= entry)
if firstTwoValid
float baseOuter = dir == 1 ? math.min(fvgEdge, candleExtreme) : math.max(fvgEdge, candleExtreme)
float baseStop = f_roundStop(dir, baseOuter)
float normalStop = na
if not na(thirdLayer)
float normalOuter = dir == 1 ? math.min(baseOuter, thirdLayer) : math.max(baseOuter, thirdLayer)
normalStop := f_roundStop(dir, normalOuter)
bool needsLocal = stopPolicy == "Always local swing" or (stopPolicy == "Fallback when wide" and (na(normalStop) or math.abs(normalStop - baseStop) > maxExtraPoints))
if needsLocal
bool localValid = not na(counterExtreme) and (dir == 1 ? counterExtreme < entry : counterExtreme > entry)
if localValid
float localOuter = dir == 1 ? math.min(baseOuter, counterExtreme) : math.max(baseOuter, counterExtreme)
chosen := f_roundStop(dir, localOuter)
else
chosen := normalStop
chosen
f_closerDefence(int dir, float entry, float current, float proposed) =>
not na(proposed) and not na(entry) and (dir == 1 ? proposed < entry : proposed > entry) and (na(current) or (dir == 1 ? proposed > current : proposed < current))
f_previousDefence(int dir) =>
bool sameDay = not na(time[1]) and f_day(time) == f_day(time[1])
bool bodySupports = dir == 1 ? close[1] > open[1] : close[1] < open[1]
sameDay and (not previousSupportOnly or bodySupports) ? (dir == 1 ? low[1] : high[1]) : na
f_thirdDefence(int dir, float entry, float previousWick, float ma15, float ma30, float ma60, float localSwing) =>
float selected = na
string selectedName = "NONE"
if thirdDefencePolicy == "Local swing only"
if f_closerDefence(dir, entry, selected, localSwing)
selected := localSwing
selectedName := "LOCAL PULLBACK"
else if thirdDefencePolicy == "Previous candle, then MA, then swing"
if f_closerDefence(dir, entry, selected, previousWick)
selected := previousWick
selectedName := "PREVIOUS 5m CANDLE"
else
array<float> references = array.from(ma15, ma30, ma60)
array<string> names = array.from("15m MA", "30m MA", "1H EMA")
for index = 0 to 2
float referencePrice = array.get(references, index)
if f_closerDefence(dir, entry, selected, referencePrice)
selected := referencePrice
selectedName := array.get(names, index)
if na(selected) and f_closerDefence(dir, entry, selected, localSwing)
selected := localSwing
selectedName := "LOCAL PULLBACK"
else
array<float> references = array.from(previousWick, ma15, ma30, ma60, localSwing)
array<string> names = array.from("PREVIOUS 5m CANDLE", "15m MA", "30m MA", "1H EMA", "LOCAL PULLBACK")
for index = 0 to 4
float referencePrice = array.get(references, index)
if f_closerDefence(dir, entry, selected, referencePrice)
selected := referencePrice
selectedName := array.get(names, index)
[selected, selectedName]
// Actual SL protects all three selected references.
f_tradeStop(int dir, float entry, float fvgEdge, float candleExtreme, float swing, float counterExtreme, float ma15, float ma30, float ma60, float structureExtreme) =>
float chosen = na
if useStructureStop
[thirdLayer, thirdName] = f_thirdDefence(dir, entry, f_previousDefence(dir), ma15, ma30, ma60, structureExtreme)
bool validFvg = not na(fvgEdge) and (dir == 1 ? fvgEdge <= entry : fvgEdge >= entry)
bool validCandle = not na(candleExtreme) and (dir == 1 ? candleExtreme <= entry : candleExtreme >= entry)
bool validThird = not na(thirdLayer) and (dir == 1 ? thirdLayer < entry : thirdLayer > entry)
if validFvg and validCandle and validThird
float outer = dir == 1 ? math.min(fvgEdge, math.min(candleExtreme, thirdLayer)) : math.max(fvgEdge, math.max(candleExtreme, thirdLayer))
chosen := f_roundStop(dir, outer)
else
chosen := f_stop(dir, entry, fvgEdge, candleExtreme, swing, counterExtreme, ma15, ma30, ma60)
chosen
f_target(int dir, float entry, float risk, float a, float b, float c) =>
float nearest = na
for p in array.from(a, b, c)
if not na(p) and (dir == 1 ? p > entry : p < entry)
nearest := na(nearest) ? p : dir == 1 ? math.min(nearest, p) : math.max(nearest, p)
float distance = math.max(risk * minRR, na(nearest) ? 0.0 : math.abs(nearest - entry))
dir == 1 ? math.ceil((entry + distance) / syminfo.mintick) * syminfo.mintick : math.floor((entry - distance) / syminfo.mintick) * syminfo.mintick
f_price(float p) =>
na(p) ? "—" : str.tostring(p, format.mintick)
f_status(int v) =>
v == 1 ? "BULL" : v == -1 ? "BEAR" : "FLAT"
f_color(int v) =>
v == 1 ? bull : v == -1 ? bear : muted
// Minimum one contract remains an explicit exception to the cash budget.
f_size(float riskPoints, bool splitRequested) =>
int quantity = 0
if not na(riskPoints) and riskPoints > 0 and not na(cashPointValue) and cashPointValue > 0
float oneContractRisk = riskPoints * cashPointValue
quantity := math.max(1, int(math.floor(cashRiskBudget / oneContractRisk)))
if splitRequested and quantity >= 2
quantity := quantity - quantity % 2
quantity
f_cash(float amount) =>
na(amount) ? "—" : (amount < 0 ? "-$" : "+$") + str.tostring(math.abs(amount), "0.00")
f_stopNotes(int dir, float entry, float fvgEdge, float candleExtreme, float localSwing, float ma15, float ma30, float ma60) =>
string notes = "Legacy comparison policy: " + stopPolicy
if useStructureStop
[thirdLayer, thirdName] = f_thirdDefence(dir, entry, f_previousDefence(dir), ma15, ma30, ma60, localSwing)
notes := "Third-defence policy: " + thirdDefencePolicy + "\n1. FVG far boundary: " + f_price(fvgEdge) + "\n2. Inversion candle: " + f_price(candleExtreme) + "\n3. " + thirdName + ": " + f_price(thirdLayer) + "\nSL lies beyond all three plus " + str.tostring(stopBufferTicks) + " tick(s). Values frozen at entry."
notes
// Each FVG owns separate boundaries, swing state and inversion history.
type FvgCandidate
int direction = 0
int formedBar = na
float top = na
float bottom = na
float counterExtreme = na
int counterAnchorBar = na
float pullbackExtreme = na
int pullbackBar = na
bool pullbackResumed = false
float impulseExtreme = na
float retraceExtreme = na
int retraceBar = na
box drawing = na
label auditMarker = na
string auditDetails = ""
string lastEvent = "NONE"
f_poolName(int poolIndex) =>
"POST"
method clearCandidate(FvgCandidate candidate, string reason, bool retainUsed, array<box> retained, string eventZone) =>
candidate.lastEvent := reason + " · " + str.format_time(time_close, "HH:mm", eventZone)
if not na(candidate.auditMarker) and not na(label.get_x(candidate.auditMarker))
label.set_tooltip(candidate.auditMarker, candidate.auditDetails + "\nCandidate event: " + candidate.lastEvent)
if not na(candidate.drawing)
if retainUsed
while array.size(retained) > 0
box.delete(array.shift(retained))
box.set_right(candidate.drawing, bar_index)
box.set_border_style(candidate.drawing, line.style_dotted)
box.set_text(candidate.drawing, "IFVG · USED")
array.push(retained, candidate.drawing)
else
box.delete(candidate.drawing)
candidate.direction := 0
candidate.formedBar := na
candidate.top := na
candidate.bottom := na
candidate.counterExtreme := na
candidate.counterAnchorBar := na
candidate.pullbackExtreme := na
candidate.pullbackBar := na
candidate.pullbackResumed := false
candidate.impulseExtreme := na
candidate.retraceExtreme := na
candidate.retraceBar := na
candidate.drawing := na
candidate.auditMarker := na
candidate.auditDetails := ""
f_candidateText(FvgCandidate candidate) =>
candidate.direction == 1 ? "BULLISH" : candidate.direction == -1 ? "BEARISH" : "NONE"
// Latest formation opposite current bias, never nearest to price.
f_latestEligible(array<FvgCandidate> records, int currentBias) =>
FvgCandidate latest = FvgCandidate.new()
int recordIndex = array.size(records) - 1
while recordIndex >= 0
FvgCandidate item = array.get(records, recordIndex)
if currentBias != 0 and item.direction == -currentBias
latest := item
break
recordIndex -= 1
latest
method hide(FvgCandidate candidate) =>
if not na(candidate.drawing)
box.delete(candidate.drawing)
candidate.drawing := na
if barstate.isfirst
if na(cashPointValue) or cashPointValue <= 0
runtime.error("A positive dollar value per point is required for sizing.")
if not customPointValue and syminfo.currency != "USD"
runtime.error("Automatic cash sizing requires a USD-quoted contract; use an explicit USD point-value override for other symbols.")
if resetM % 5 != 0 or f_start(formationWindow) % 5 != 0 or f_end(formationWindow) % 5 != 0 or f_start(ny) % 5 != 0 or f_end(ny) % 5 != 0
runtime.error("Align reset and session boundaries to 5-minute bars.")
if f_start(formationWindow) >= f_end(formationWindow)
runtime.error("POST formation window must stay within one calendar day.")
int resetMinute = resetH * 60 + resetM
int postStart = (f_start(formationWindow) - resetMinute + 1440) % 1440
int postEnd = (f_end(formationWindow) - resetMinute + 1440) % 1440
int nyStart = (f_start(ny) - resetMinute + 1440) % 1440
int nyEnd = (f_end(ny) - resetMinute + 1440) % 1440
if postStart >= postEnd or nyStart >= nyEnd or postEnd > nyEnd
runtime.error("Reset must precede POST and NY; NY must finish before the next reset.")
if f_start(formationWindow) != f_start(ny)
runtime.error("POST formation must start at NY open.")
if chart.is_standard == false or not (timeframe.isseconds or timeframe.isminutes or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly)
runtime.error("Use standard time-based candles; synthetic OHLC is unsupported.")
// BEGIN GENERATED FIVE-MINUTE PROJECTION
// Drawing-free copy of native 5m decisions for other chart timeframes.
type FvgRecord
int direction = 0
int formedBar = na
float top = na
float bottom = na
float counterExtreme = na
int counterAnchorBar = na
float pullbackExtreme = na
int pullbackBar = na
bool pullbackResumed = false
float impulseExtreme = na
float retraceExtreme = na
int retraceBar = na
string lastEvent = "NONE"
method clearRecord(FvgRecord candidate, string reason, bool retainUsed, array<int> unused, string eventZone) =>
candidate.lastEvent := reason + " · " + str.format_time(time_close, "HH:mm", eventZone)
candidate.direction := 0
candidate.formedBar := na
candidate.top := na
candidate.bottom := na
candidate.counterExtreme := na
candidate.counterAnchorBar := na
candidate.pullbackExtreme := na
candidate.pullbackBar := na
candidate.pullbackResumed := false
candidate.impulseExtreme := na
candidate.retraceExtreme := na
candidate.retraceBar := na
f_latestEligibleRecord(array<FvgRecord> records, int currentBias) =>
FvgRecord latest = FvgRecord.new()
int recordIndex = array.size(records) - 1
while recordIndex >= 0
FvgRecord item = array.get(records, recordIndex)
if currentBias != 0 and item.direction == -currentBias
latest := item
break
recordIndex -= 1
latest
type TradeView
int sourceClose
int bias
bool sideways
int position
int entryTime
int deadline
float entry
float stop
float target
int quantity
float loss
float profit
int pool
int direction
int exitTime
int closedEntryTime
int closedExitTime
int closedDirection
float closedEntry
float closedStop
float closedTarget
int closedQuantity
float closedLoss
float closedProfit
int closedPool
f_view5() =>
[m15, old15] = request.security(syminfo.tickerid, "15", [f_ma()[1], f_ma()[1 + slopeBars]], lookahead=barmerge.lookahead_on)
[m30, old30] = request.security(syminfo.tickerid, "30", [f_ma()[1], f_ma()[1 + slopeBars]], lookahead=barmerge.lookahead_on)
[m60, old60] = request.security(syminfo.tickerid, "60", [f_hourlyEMA()[1], f_hourlyEMA()[1 + hourlySlopeBars]], lookahead=barmerge.lookahead_on)
float swingLow = ta.lowest(low[1], swingLen)
float swingHigh = ta.highest(high[1], swingLen)
bool inPost = not na(time("5", formationWindow, tz))
bool inNY = not na(time("5", ny, tz))
int dayKey = f_day(time)
bool newDay = na(dayKey[1]) or dayKey != dayKey[1]
int weekday = dayofweek(dayKey, tz)
bool workday = weekday >= dayofweek.monday and weekday <= dayofweek.friday
bool lastNYBar = inNY and time_close >= f_sessionEnd(time, ny)
bool leftNY = not inNY and inNY[1]
float counterPivotLow = ta.pivotlow(low, counterPivotStrength, counterPivotStrength)
float counterPivotHigh = ta.pivothigh(high, counterPivotStrength, counterPivotStrength)
int lastLowPivotBar = ta.valuewhen(not na(counterPivotLow), bar_index - counterPivotStrength, 0)
int lastHighPivotBar = ta.valuewhen(not na(counterPivotHigh), bar_index - counterPivotStrength, 0)
int lastLowPivotDay = ta.valuewhen(not na(counterPivotLow), dayKey[counterPivotStrength], 0)
int lastHighPivotDay = ta.valuewhen(not na(counterPivotHigh), dayKey[counterPivotStrength], 0)
int lowPivotAge = na(lastLowPivotBar) ? counterAnchorMaxBars + 1 : bar_index - lastLowPivotBar
int highPivotAge = na(lastHighPivotBar) ? counterAnchorMaxBars + 1 : bar_index - lastHighPivotBar
bool validLowAnchor = not na(lastLowPivotBar) and lastLowPivotDay == dayKey and lowPivotAge <= counterAnchorMaxBars
bool validHighAnchor = not na(lastHighPivotBar) and lastHighPivotDay == dayKey and highPivotAge <= counterAnchorMaxBars
int shortCounterLen = counterAnchorMode == "Confirmed pivot" and validLowAnchor ? math.max(3, lowPivotAge + 1) : 3
int longCounterLen = counterAnchorMode == "Confirmed pivot" and validHighAnchor ? math.max(3, highPivotAge + 1) : 3
float shortCounterSeed = ta.highest(high, shortCounterLen)
float longCounterSeed = ta.lowest(low, longCounterLen)
int shortCounterAnchor = bar_index - shortCounterLen + 1
int longCounterAnchor = bar_index - longCounterLen + 1
var float reference = na
var float dayHi = na
var float dayLo = na
var float prevHi = na
var float prevLo = na
var float nyHi = na
var float nyLo = na
var float prevNYHi = na
var float prevNYLo = na
var bool nyTracking = false
var int trackedNYEnd = na
var int bias = 0
var bool sideways = false
var float start15 = na
var float start30 = na
var float start60 = na
var array<FvgRecord> registry = array.new<FvgRecord>()
var FvgRecord selected = FvgRecord.new()
var string lastEvent = "NONE"
var bool dailyUsed = false
var array<int> usedBoxes = array.new<int>()
var int pos = 0
var int activePool = -1
var float entry = na
var float stop = na
var float target = na
var int tradeQty = 0
var float tradePointValue = na
var float tradeLoss = na
var float tradeProfit = na
var bool tradeOverBudget = false
var int entryBar = na
var int tradeDeadline = na
bool longEvent = false
bool shortEvent = false
bool postEntryEvent = false
bool slEvent = false
bool tpEvent = false
bool sessionEvent = false
var int _entryTime = na
var int _direction = 0
var int _exitTime = na
var int _closedEntryTime = na
var int _closedExitTime = na
var int _closedDirection = 0
var float _closedEntry = na
var float _closedStop = na
var float _closedTarget = na
var int _closedQuantity = 0
var float _closedLoss = na
var float _closedProfit = na
var int _closedPool = -1
if newDay
for record in registry
record.clearRecord("DAILY RESET", false, usedBoxes, tz)
array.clear(registry)
selected := FvgRecord.new()
dailyUsed := false
lastEvent := "DAILY RESET · " + str.format_time(time_close, "HH:mm", tz)
start15 := m15
start30 := m30
start60 := m60
prevHi := not na(reference) ? dayHi : na
prevLo := not na(reference) ? dayLo : na
dayHi := high
dayLo := low
reference := na(dayKey[1]) and time != dayKey ? na : open
else
dayHi := math.max(nz(dayHi, high), high)
dayLo := math.min(nz(dayLo, low), low)
if nyTracking and time >= trackedNYEnd
prevNYHi := nyHi
prevNYLo := nyLo
nyTracking := false
if inNY
if not nyTracking
nyHi := high
nyLo := low
nyTracking := true
trackedNYEnd := f_sessionEnd(time, ny)
else
nyHi := math.max(nyHi, high)
nyLo := math.min(nyLo, low)
if nyTracking and (lastNYBar or leftNY)
prevNYHi := nyHi
prevNYLo := nyLo
nyTracking := false
int state15 = f_emaState(m15, old15, start15, 15, slopeBars)
int state30 = f_emaState(m30, old30, start30, 30, slopeBars)
int state60 = f_emaState(m60, old60, start60, 60, hourlySlopeBars)
sideways := not na(reference) and state15 == 0 and state30 == 0 and state60 == 0
int priorityTrend = state60 == 1 or state60 == -1 ? state60 : state60 == 0 ? (state30 == 1 or state30 == -1 ? state30 : state30 == 0 and (state15 == 1 or state15 == -1) ? state15 : 0) : 0
bias := not na(reference) and not na(m60) and not sideways ? (priorityTrend == 1 and close > m60 ? 1 : priorityTrend == -1 and close < m60 ? -1 : 0) : 0
if pos != 0 and bar_index > entryBar
bool overdue = time >= tradeDeadline
bool hitSL = not overdue and not leftNY and not newDay and (pos == 1 ? low <= stop : high >= stop)
bool hitTP = not overdue and not leftNY and not newDay and (pos == 1 ? high >= target : low <= target)
bool endNow = lastNYBar or leftNY or newDay or overdue
if hitSL or hitTP or endNow
slEvent := hitSL
tpEvent := not hitSL and hitTP
sessionEvent := not hitSL and not hitTP and endNow
float exitPrice = slEvent ? stop : tpEvent ? target : overdue or leftNY ? close[1] : newDay ? open : close
int exitBar = (overdue or leftNY) and sessionEvent ? bar_index - 1 : bar_index
string exitText = slEvent ? "SL HIT" : tpEvent ? "TARGET HIT" : "SESSION END"
color exitColor = slEvent ? slColor : tpEvent ? tpColor : muted
_exitTime := sessionEvent and (overdue or leftNY) ? time_close[1] : sessionEvent and newDay ? time : time_close
_closedEntryTime := _entryTime
_closedExitTime := _exitTime
_closedDirection := _direction
_closedEntry := entry
_closedStop := stop
_closedTarget := target
_closedQuantity := tradeQty
_closedLoss := tradeLoss
_closedProfit := tradeProfit
_closedPool := activePool
pos := 0
array<FvgRecord> records = registry
for record in records
if record.direction != 0
record.counterExtreme := record.direction == 1 ? math.max(nz(record.counterExtreme, high), high) : math.min(nz(record.counterExtreme, low), low)
bool towardLong = record.direction == -1
float adverseWick = towardLong ? low : high
float trendWick = towardLong ? high : low
bool localTurn = towardLong ? close > high[1] : close < low[1]
bool adverseMove = towardLong ? low < low[1] or close < close[1] : high > high[1] or close > close[1]
bool continuedImpulse = towardLong ? trendWick > record.impulseExtreme : trendWick < record.impulseExtreme
if not record.pullbackResumed
bool extendsPullback = na(record.pullbackExtreme) or (towardLong ? adverseWick <= record.pullbackExtreme : adverseWick >= record.pullbackExtreme)
if extendsPullback
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
if localTurn
record.pullbackResumed := true
record.impulseExtreme := trendWick
else if not na(record.retraceExtreme)
bool extendsRetrace = towardLong ? adverseWick <= record.retraceExtreme : adverseWick >= record.retraceExtreme
if extendsRetrace
record.retraceExtreme := adverseWick
record.retraceBar := bar_index
record.pullbackExtreme := record.retraceExtreme
record.pullbackBar := record.retraceBar
if localTurn
record.impulseExtreme := trendWick
record.retraceExtreme := na
record.retraceBar := na
else if localTurn
bool wickIsOuter = towardLong ? adverseWick <= record.pullbackExtreme : adverseWick >= record.pullbackExtreme
if wickIsOuter
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
record.impulseExtreme := trendWick
else if adverseMove
record.retraceExtreme := adverseWick
record.retraceBar := bar_index
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
else if continuedImpulse
record.impulseExtreme := trendWick
if lastNYBar or leftNY or dailyUsed
string why = lastNYBar or leftNY ? "NY END" : "SLOT ALREADY USED"
record.clearRecord(why, false, usedBoxes, tz)
lastEvent := record.lastEvent
int newGapDir = low > high[2] ? 1 : high < low[2] ? -1 : 0
bool sameDayPattern = not na(dayKey[2]) and dayKey == dayKey[2]
int nyOpen = f_sessionOpen(dayKey, ny)
bool whollyPostOpen = not na(time[2]) and time[2] >= nyOpen
bool eligibleFormation = newGapDir != 0 and workday and inPost and not dailyUsed and sameDayPattern and whollyPostOpen and not lastNYBar
if eligibleFormation
FvgRecord candidate = FvgRecord.new()
candidate.direction := newGapDir
candidate.formedBar := bar_index
candidate.top := newGapDir == 1 ? low : low[2]
candidate.bottom := newGapDir == 1 ? high[2] : high
candidate.counterExtreme := newGapDir == 1 ? shortCounterSeed : longCounterSeed
candidate.counterAnchorBar := newGapDir == 1 ? shortCounterAnchor : longCounterAnchor
candidate.pullbackExtreme := newGapDir == -1 ? math.min(low, math.min(low[1], low[2])) : math.max(high, math.max(high[1], high[2]))
candidate.pullbackBar := newGapDir == -1 ? (low == candidate.pullbackExtreme ? bar_index : low[1] == candidate.pullbackExtreme ? bar_index - 1 : bar_index - 2) : (high == candidate.pullbackExtreme ? bar_index : high[1] == candidate.pullbackExtreme ? bar_index - 1 : bar_index - 2)
candidate.pullbackResumed := false
candidate.impulseExtreme := newGapDir == -1 ? high : low
candidate.lastEvent := "RECORDED · " + str.format_time(time, "HH:mm", tz)
array.push(registry, candidate)
lastEvent := candidate.lastEvent
selected := f_latestEligibleRecord(registry, bias)
int selectedBar = selected.formedBar
int recordCount = array.size(registry)
if recordCount > 0
for candidateOffset = 0 to recordCount - 1
FvgRecord candidate = array.get(registry, recordCount - 1 - candidateOffset)
if candidate.direction != 0
bool inverted = bar_index > candidate.formedBar and (candidate.direction == -1 ? close > candidate.top and close[1] <= candidate.top : close < candidate.bottom and close[1] >= candidate.bottom)
if inverted
int dir = -candidate.direction
float structureReference = candidate.pullbackExtreme
float proposedSL = f_tradeStop(dir, close, dir == 1 ? candidate.bottom : candidate.top, dir == 1 ? low : high, dir == 1 ? swingLow : swingHigh, candidate.counterExtreme, m15, m30, m60, structureReference)
float risk = math.abs(close - proposedSL)
int proposedQty = f_size(risk, false)
float proposedTP = f_target(dir, close, risk, dir == 1 ? dayHi : dayLo, dir == 1 ? prevHi : prevLo, dir == 1 ? prevNYHi : prevNYLo)
bool valid = not na(proposedSL) and not na(proposedTP) and risk > 0 and proposedQty >= 1 and (dir == 1 ? proposedSL < close and close < proposedTP : proposedTP < close and close < proposedSL)
bool selectedForEntry = candidate.formedBar == selectedBar
bool entered = false
if inNY and not lastNYBar and workday and bias == dir and (dir == 1 ? close > m60 : close < m60) and not dailyUsed and pos == 0 and valid and selectedForEntry
entered := true
dailyUsed := true
pos := dir
activePool := 0
entry := close
stop := proposedSL
target := proposedTP
tradeQty := proposedQty
tradePointValue := cashPointValue
tradeLoss := math.abs(entry - stop) * tradePointValue * tradeQty
tradeProfit := math.abs(target - entry) * tradePointValue * tradeQty
tradeOverBudget := tradeLoss > cashRiskBudget + 0.0000001
entryBar := bar_index
_entryTime := time_close
_direction := dir
_exitTime := na
tradeDeadline := f_sessionEnd(time, ny)
longEvent := dir == 1
shortEvent := dir == -1
postEntryEvent := true
string why = entered ? "ENTRY ACCEPTED" : not inNY ? "NULLIFIED: INVERSION OUTSIDE NY" : lastNYBar ? "NULLIFIED: NY END BAR" : not workday ? "NULLIFIED: NON-WORKDAY" : bias == 0 ? "NULLIFIED: NEUTRAL AT INVERSION" : bias != dir ? "NULLIFIED: WRONG BIAS" : dailyUsed ? "NULLIFIED: OWN SLOT USED" : pos != 0 ? "NULLIFIED: POSITION OCCUPIED" : not selectedForEntry ? "NULLIFIED: NOT LATEST OPPOSITE FVG" : useStructureStop and na(proposedSL) ? "NULLIFIED: NO VALID THREE-LAYER STOP" : not valid ? "NULLIFIED: INVALID RISK / TARGET" : "NULLIFIED: ENTRY FILTER"
candidate.clearRecord(why, entered, usedBoxes, tz)
if entered or not postEntryEvent
lastEvent := candidate.lastEvent
int recordIndex = array.size(registry) - 1
while recordIndex >= 0
FvgRecord record = array.get(registry, recordIndex)
if record.direction != 0 and dailyUsed
record.clearRecord("DAILY ENTRY USED", false, usedBoxes, tz)
if record.direction == 0
array.remove(registry, recordIndex)
recordIndex -= 1
selected := f_latestEligibleRecord(registry, bias)
TradeView.new(time_close, bias, sideways, pos, _entryTime, tradeDeadline, entry, stop, target, tradeQty, tradeLoss, tradeProfit, activePool, _direction, _exitTime, _closedEntryTime, _closedExitTime, _closedDirection, _closedEntry, _closedStop, _closedTarget, _closedQuantity, _closedLoss, _closedProfit, _closedPool)
// Previous entire snapshot, not a mixture of current/previous fields.
f_closedView5() =>
TradeView snapshot = f_view5()
snapshot[1]
f_viewPair5() =>
TradeView snapshot = f_view5()
[snapshot, snapshot[1]]
// END GENERATED FIVE-MINUTE PROJECTION
// BEGIN SOURCE ENVIRONMENT
[m15, old15] = request.security(syminfo.tickerid, "15", [f_ma()[1], f_ma()[1 + slopeBars]], lookahead=barmerge.lookahead_on)
[m30, old30] = request.security(syminfo.tickerid, "30", [f_ma()[1], f_ma()[1 + slopeBars]], lookahead=barmerge.lookahead_on)
[m60, old60] = request.security(syminfo.tickerid, "60", [f_hourlyEMA()[1], f_hourlyEMA()[1 + hourlySlopeBars]], lookahead=barmerge.lookahead_on)
float swingLow = ta.lowest(low[1], swingLen)
float swingHigh = ta.highest(high[1], swingLen)
bool inPost = not na(time(timeframe.period, formationWindow, tz))
bool inNY = not na(time(timeframe.period, ny, tz))
int dayKey = f_day(time)
bool newDay = na(dayKey[1]) or dayKey != dayKey[1]
int weekday = dayofweek(dayKey, tz)
bool workday = weekday >= dayofweek.monday and weekday <= dayofweek.friday
bool lastNYBar = inNY and time_close >= f_sessionEnd(time, ny)
bool leftNY = not inNY and inNY[1]
float counterPivotLow = ta.pivotlow(low, counterPivotStrength, counterPivotStrength)
float counterPivotHigh = ta.pivothigh(high, counterPivotStrength, counterPivotStrength)
int lastLowPivotBar = ta.valuewhen(not na(counterPivotLow), bar_index - counterPivotStrength, 0)
int lastHighPivotBar = ta.valuewhen(not na(counterPivotHigh), bar_index - counterPivotStrength, 0)
int lastLowPivotDay = ta.valuewhen(not na(counterPivotLow), dayKey[counterPivotStrength], 0)
int lastHighPivotDay = ta.valuewhen(not na(counterPivotHigh), dayKey[counterPivotStrength], 0)
int lowPivotAge = na(lastLowPivotBar) ? counterAnchorMaxBars + 1 : bar_index - lastLowPivotBar
int highPivotAge = na(lastHighPivotBar) ? counterAnchorMaxBars + 1 : bar_index - lastHighPivotBar
bool validLowAnchor = not na(lastLowPivotBar) and lastLowPivotDay == dayKey and lowPivotAge <= counterAnchorMaxBars
bool validHighAnchor = not na(lastHighPivotBar) and lastHighPivotDay == dayKey and highPivotAge <= counterAnchorMaxBars
int shortCounterLen = counterAnchorMode == "Confirmed pivot" and validLowAnchor ? math.max(3, lowPivotAge + 1) : 3
int longCounterLen = counterAnchorMode == "Confirmed pivot" and validHighAnchor ? math.max(3, highPivotAge + 1) : 3
float shortCounterSeed = ta.highest(high, shortCounterLen)
float longCounterSeed = ta.lowest(low, longCounterLen)
int shortCounterAnchor = bar_index - shortCounterLen + 1
int longCounterAnchor = bar_index - longCounterLen + 1
// END SOURCE ENVIRONMENT
// BEGIN NATIVE FIVE-MINUTE STATE
var float reference = na
var float dayHi = na
var float dayLo = na
var float prevHi = na
var float prevLo = na
var float nyHi = na
var float nyLo = na
var float prevNYHi = na
var float prevNYLo = na
var bool nyTracking = false
var int trackedNYEnd = na
var int bias = 0
var bool sideways = false
var float start15 = na
var float start30 = na
var float start60 = na
var array<FvgCandidate> registry = array.new<FvgCandidate>()
var FvgCandidate selected = FvgCandidate.new()
var string lastEvent = "NONE"
var bool dailyUsed = false
var array<box> usedBoxes = array.new<box>()
var array<label> auditMarkers = array.new<label>()
var string auditLastRaw = "—"
var string auditLastGate = "—"
var string auditClosedBar = "—"
var string auditBullWicks = "—"
var string auditBearWicks = "—"
var int pos = 0
var int activePool = -1
var float entry = na
var float stop = na
var float target = na
var int tradeQty = 0
var float tradePointValue = na
var float tradeLoss = na
var float tradeProfit = na
var bool tradeOverBudget = false
var int entryBar = na
var int tradeDeadline = na
bool longEvent = false
bool shortEvent = false
bool postEntryEvent = false
bool slEvent = false
bool tpEvent = false
bool sessionEvent = false
var array<line> tradeLines = array.new<line>()
var array<label> tradeLabels = array.new<label>()
var line liveEntry = na
var line liveStop = na
var line liveTarget = na
var label entryText = na
var label stopText = na
var label targetText = na
// BEGIN NATIVE FIVE-MINUTE CORE
if is5m and barstate.isconfirmed
if auditFVG
auditClosedBar := str.format_time(time, "dd MMM HH:mm", tz)
auditBullWicks := f_price(low) + " > " + f_price(high[2]) + " · " + (na(high[2]) ? "N/A" : low > high[2] ? "YES" : "NO")
auditBearWicks := f_price(high) + " < " + f_price(low[2]) + " · " + (na(low[2]) ? "N/A" : high < low[2] ? "YES" : "NO")
if newDay
for record in registry
record.clearCandidate("DAILY RESET", false, usedBoxes, tz)
array.clear(registry)
selected := FvgCandidate.new()
dailyUsed := false
lastEvent := "DAILY RESET · " + str.format_time(time_close, "HH:mm", tz)
start15 := m15
start30 := m30
start60 := m60
prevHi := not na(reference) ? dayHi : na
prevLo := not na(reference) ? dayLo : na
dayHi := high
dayLo := low
reference := na(dayKey[1]) and time != dayKey ? na : open
else
dayHi := math.max(nz(dayHi, high), high)
dayLo := math.min(nz(dayLo, low), low)
if nyTracking and time >= trackedNYEnd
prevNYHi := nyHi
prevNYLo := nyLo
nyTracking := false
if inNY
if not nyTracking
nyHi := high
nyLo := low
nyTracking := true
trackedNYEnd := f_sessionEnd(time, ny)
else
nyHi := math.max(nyHi, high)
nyLo := math.min(nyLo, low)
if nyTracking and (lastNYBar or leftNY)
prevNYHi := nyHi
prevNYLo := nyLo
nyTracking := false
// 1H EMA priority, then 30m and 15m only if the higher EMA is flat.
int state15 = f_emaState(m15, old15, start15, 15, slopeBars)
int state30 = f_emaState(m30, old30, start30, 30, slopeBars)
int state60 = f_emaState(m60, old60, start60, 60, hourlySlopeBars)
sideways := not na(reference) and state15 == 0 and state30 == 0 and state60 == 0
int priorityTrend = state60 == 1 or state60 == -1 ? state60 : state60 == 0 ? (state30 == 1 or state30 == -1 ? state30 : state30 == 0 and (state15 == 1 or state15 == -1) ? state15 : 0) : 0
// LONG strictly above hourly EMA; SHORT strictly below.
bias := not na(reference) and not na(m60) and not sideways ? (priorityTrend == 1 and close > m60 ? 1 : priorityTrend == -1 and close < m60 ? -1 : 0) : 0
// Exits are checked only after the entry candle. SL wins ambiguity.
if pos != 0 and bar_index > entryBar
bool overdue = time >= tradeDeadline
bool hitSL = not overdue and not leftNY and not newDay and (pos == 1 ? low <= stop : high >= stop)
bool hitTP = not overdue and not leftNY and not newDay and (pos == 1 ? high >= target : low <= target)
bool endNow = lastNYBar or leftNY or newDay or overdue
if hitSL or hitTP or endNow
slEvent := hitSL
tpEvent := not hitSL and hitTP
sessionEvent := not hitSL and not hitTP and endNow
float exitPrice = slEvent ? stop : tpEvent ? target : overdue or leftNY ? close[1] : newDay ? open : close
int exitBar = (overdue or leftNY) and sessionEvent ? bar_index - 1 : bar_index
string exitText = slEvent ? "SL HIT" : tpEvent ? "TARGET HIT" : "SESSION END"
color exitColor = slEvent ? slColor : tpEvent ? tpColor : muted
if showEntry
array.push(tradeLabels, label.new(exitBar, exitPrice, exitText + " · " + f_price(exitPrice) + " · " + f_cash(pos * (exitPrice - entry) * tradePointValue * tradeQty), style=label.style_label_left, color=color.new(exitColor, 88), textcolor=exitColor, size=size.tiny))
if showRisk
line.set_x2(liveEntry, exitBar)
line.set_x2(liveStop, exitBar)
line.set_x2(liveTarget, exitBar)
label.set_x(entryText, exitBar + 1)
label.set_x(stopText, exitBar + 1)
label.set_x(targetText, exitBar + 1)
if showEntry and slEvent
label.set_text(stopText, "")
if showEntry and tpEvent
label.set_text(targetText, "")
pos := 0
// Preserve every record's first-inversion history.
array<FvgCandidate> records = registry
for record in records
if record.direction != 0
record.counterExtreme := record.direction == 1 ? math.max(nz(record.counterExtreme, high), high) : math.min(nz(record.counterExtreme, low), low)
bool towardLong = record.direction == -1
float adverseWick = towardLong ? low : high
float trendWick = towardLong ? high : low
bool localTurn = towardLong ? close > high[1] : close < low[1]
bool adverseMove = towardLong ? low < low[1] or close < close[1] : high > high[1] or close > close[1]
bool continuedImpulse = towardLong ? trendWick > record.impulseExtreme : trendWick < record.impulseExtreme
if not record.pullbackResumed
bool extendsPullback = na(record.pullbackExtreme) or (towardLong ? adverseWick <= record.pullbackExtreme : adverseWick >= record.pullbackExtreme)
if extendsPullback
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
if localTurn
record.pullbackResumed := true
record.impulseExtreme := trendWick
else if not na(record.retraceExtreme)
bool extendsRetrace = towardLong ? adverseWick <= record.retraceExtreme : adverseWick >= record.retraceExtreme
if extendsRetrace
record.retraceExtreme := adverseWick
record.retraceBar := bar_index
record.pullbackExtreme := record.retraceExtreme
record.pullbackBar := record.retraceBar
if localTurn
record.impulseExtreme := trendWick
record.retraceExtreme := na
record.retraceBar := na
else if localTurn
bool wickIsOuter = towardLong ? adverseWick <= record.pullbackExtreme : adverseWick >= record.pullbackExtreme
if wickIsOuter
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
record.impulseExtreme := trendWick
else if adverseMove
record.retraceExtreme := adverseWick
record.retraceBar := bar_index
record.pullbackExtreme := adverseWick
record.pullbackBar := bar_index
else if continuedImpulse
record.impulseExtreme := trendWick
if lastNYBar or leftNY or dailyUsed
string why = lastNYBar or leftNY ? "NY END" : "SLOT ALREADY USED"
record.clearCandidate(why, false, usedBoxes, tz)
lastEvent := record.lastEvent
int newGapDir = low > high[2] ? 1 : high < low[2] ? -1 : 0
bool sameDayPattern = not na(dayKey[2]) and dayKey == dayKey[2]
int nyOpen = f_sessionOpen(dayKey, ny)
bool whollyPostOpen = not na(time[2]) and time[2] >= nyOpen
bool eligibleFormation = newGapDir != 0 and workday and inPost and not dailyUsed and sameDayPattern and whollyPostOpen and not lastNYBar
label rawAudit = na
string rawAuditText = ""
if newGapDir != 0
string gate = not workday ? "NON-WORKDAY" : not inPost ? "OUTSIDE POST WINDOW" : not whollyPostOpen ? "PATTERN STRADDLES NY OPEN" : dailyUsed ? "DAILY ENTRY USED" : not sameDayPattern ? "PATTERN CROSSES RESET" : lastNYBar ? "NY END BAR" : bias != 0 and newGapDir == -bias ? "RECORDED / OPPOSITE CURRENT BIAS" : "RECORDED / WAITING FOR BIAS"
float rawTop = newGapDir == 1 ? low : low[2]
float rawBottom = newGapDir == 1 ? high[2] : high
string rawName = newGapDir == 1 ? "BULLISH" : "BEARISH"
auditLastRaw := str.format_time(time, "dd MMM HH:mm", tz) + " · " + rawName
auditLastGate := gate
string wick = newGapDir == 1 ? "low " + f_price(low) + " > high[2] " + f_price(high[2]) : "high " + f_price(high) + " < low[2] " + f_price(low[2])
rawAuditText := rawName + " FVG\nThird candle OPEN: " + str.format_time(time, "yyyy-MM-dd HH:mm", tz) + "\nConfirmed close: " + str.format_time(time_close, "HH:mm", tz) + " " + tz + "\nPool: " + (inPost ? "POST" : "NONE") + "\nWick test: " + wick + "\nTop / bottom: " + f_price(rawTop) + " / " + f_price(rawBottom) + "\nFormation bias: " + (bias == 1 ? "BULLISH" : bias == -1 ? "BEARISH" : "NEUTRAL") + "\nFormation decision: " + gate + "\nPOST " + formationWindow + "; third candle OPEN, end exclusive. All three candles must start at/after NY open."
if auditFVG
rawAudit := label.new(bar_index, math.avg(rawTop, rawBottom), "·", style=label.style_none, textcolor=muted, size=size.tiny, tooltip=rawAuditText)
array.push(auditMarkers, rawAudit)
if eligibleFormation
while array.size(usedBoxes) > 0
box.delete(array.shift(usedBoxes))
FvgCandidate candidate = FvgCandidate.new()
candidate.direction := newGapDir
candidate.formedBar := bar_index
candidate.top := newGapDir == 1 ? low : low[2]
candidate.bottom := newGapDir == 1 ? high[2] : high
candidate.counterExtreme := newGapDir == 1 ? shortCounterSeed : longCounterSeed
candidate.counterAnchorBar := newGapDir == 1 ? shortCounterAnchor : longCounterAnchor
candidate.pullbackExtreme := newGapDir == -1 ? math.min(low, math.min(low[1], low[2])) : math.max(high, math.max(high[1], high[2]))
candidate.pullbackBar := newGapDir == -1 ? (low == candidate.pullbackExtreme ? bar_index : low[1] == candidate.pullbackExtreme ? bar_index - 1 : bar_index - 2) : (high == candidate.pullbackExtreme ? bar_index : high[1] == candidate.pullbackExtreme ? bar_index - 1 : bar_index - 2)
candidate.pullbackResumed := false
candidate.impulseExtreme := newGapDir == -1 ? high : low
candidate.auditMarker := rawAudit
candidate.auditDetails := rawAuditText
candidate.lastEvent := "RECORDED · " + str.format_time(time, "HH:mm", tz)
array.push(registry, candidate)
lastEvent := candidate.lastEvent
// Bearish bias selects bullish FVG. Bullish bias selects bearish FVG.
selected := f_latestEligible(registry, bias)
// Snapshot before consuming inversions; no older same-bar cascade.
int selectedBar = selected.formedBar
int recordCount = array.size(registry)
if recordCount > 0
for candidateOffset = 0 to recordCount - 1
FvgCandidate candidate = array.get(registry, recordCount - 1 - candidateOffset)
if candidate.direction != 0
if showFVG and na(candidate.drawing) and candidate.formedBar == selectedBar
candidate.drawing := box.new(candidate.formedBar - 2, candidate.top, bar_index, candidate.bottom, border_color=color.new(f_color(candidate.direction), 30), bgcolor=color.new(f_color(candidate.direction), 90), text=f_poolName(0), text_size=size.tiny, text_color=f_color(candidate.direction))
if not na(candidate.drawing)
box.set_right(candidate.drawing, bar_index)
bool inverted = bar_index > candidate.formedBar and (candidate.direction == -1 ? close > candidate.top and close[1] <= candidate.top : close < candidate.bottom and close[1] >= candidate.bottom)
if inverted
int dir = -candidate.direction
float structureReference = candidate.pullbackExtreme
float proposedSL = f_tradeStop(dir, close, dir == 1 ? candidate.bottom : candidate.top, dir == 1 ? low : high, dir == 1 ? swingLow : swingHigh, candidate.counterExtreme, m15, m30, m60, structureReference)
float risk = math.abs(close - proposedSL)
int proposedQty = f_size(risk, false)
float proposedTP = f_target(dir, close, risk, dir == 1 ? dayHi : dayLo, dir == 1 ? prevHi : prevLo, dir == 1 ? prevNYHi : prevNYLo)
bool valid = not na(proposedSL) and not na(proposedTP) and risk > 0 and proposedQty >= 1 and (dir == 1 ? proposedSL < close and close < proposedTP : proposedTP < close and close < proposedSL)
bool selectedForEntry = candidate.formedBar == selectedBar
bool entered = false
if inNY and not lastNYBar and workday and bias == dir and (dir == 1 ? close > m60 : close < m60) and not dailyUsed and pos == 0 and valid and selectedForEntry
entered := true
dailyUsed := true
pos := dir
activePool := 0
entry := close
stop := proposedSL
target := proposedTP
tradeQty := proposedQty
tradePointValue := cashPointValue
tradeLoss := math.abs(entry - stop) * tradePointValue * tradeQty
tradeProfit := math.abs(target - entry) * tradePointValue * tradeQty
tradeOverBudget := tradeLoss > cashRiskBudget + 0.0000001
entryBar := bar_index
tradeDeadline := f_sessionEnd(time, ny)
longEvent := dir == 1
shortEvent := dir == -1
postEntryEvent := true
if showEntry
array.push(tradeLabels, label.new(bar_index, dir == 1 ? low : high, (dir == 1 ? "LONG · " : "SHORT · ") + f_poolName(0) + " · " + str.tostring(tradeQty) + " ct", yloc=dir == 1 ? yloc.belowbar : yloc.abovebar, style=dir == 1 ? label.style_label_up : label.style_label_down, color=color.new(f_color(dir), 12), textcolor=#101820, size=size.tiny))
if showRisk
liveEntry := line.new(bar_index, entry, bar_index + reach, entry, color=color.new(muted, 35), style=line.style_dotted)
liveStop := line.new(bar_index, stop, bar_index + reach, stop, color=slColor)
liveTarget := line.new(bar_index, target, bar_index + reach, target, color=tpColor)
entryText := label.new(bar_index + reach, entry, "ENTRY · " + f_price(entry) + " · " + str.tostring(tradeQty) + " ct", style=label.style_label_left, color=color.new(muted, 94), textcolor=muted, size=size.tiny)
stopText := label.new(bar_index + reach, stop, "SL · " + f_price(stop) + " · " + f_cash(-tradeLoss), style=label.style_label_left, color=color.new(slColor, 92), textcolor=slColor, size=size.tiny, tooltip=f_stopNotes(dir, entry, dir == 1 ? candidate.bottom : candidate.top, dir == 1 ? low : high, structureReference, m15, m30, m60))
targetText := label.new(bar_index + reach, target, "TP · " + f_price(target) + " · " + f_cash(tradeProfit), style=label.style_label_left, color=color.new(tpColor, 92), textcolor=tpColor, size=size.tiny)
array.push(tradeLines, liveEntry)
array.push(tradeLines, liveStop)
array.push(tradeLines, liveTarget)
array.push(tradeLabels, entryText)
array.push(tradeLabels, stopText)
array.push(tradeLabels, targetText)
string why = entered ? "ENTRY ACCEPTED" : not inNY ? "NULLIFIED: INVERSION OUTSIDE NY" : lastNYBar ? "NULLIFIED: NY END BAR" : not workday ? "NULLIFIED: NON-WORKDAY" : bias == 0 ? "NULLIFIED: NEUTRAL AT INVERSION" : bias != dir ? "NULLIFIED: WRONG BIAS" : dailyUsed ? "NULLIFIED: OWN SLOT USED" : pos != 0 ? "NULLIFIED: POSITION OCCUPIED" : not selectedForEntry ? "NULLIFIED: NOT LATEST OPPOSITE FVG" : useStructureStop and na(proposedSL) ? "NULLIFIED: NO VALID THREE-LAYER STOP" : not valid ? "NULLIFIED: INVALID RISK / TARGET" : "NULLIFIED: ENTRY FILTER"
candidate.clearCandidate(why, entered, usedBoxes, tz)
if entered or not postEntryEvent
lastEvent := candidate.lastEvent
int recordIndex = array.size(registry) - 1
while recordIndex >= 0
FvgCandidate record = array.get(registry, recordIndex)
if record.direction != 0 and dailyUsed
record.clearCandidate("DAILY ENTRY USED", false, usedBoxes, tz)
if record.direction == 0
array.remove(registry, recordIndex)
recordIndex -= 1
selected := f_latestEligible(registry, bias)
// Strict countertrend display. There is no raw-gap fallback.
if showFVG
var int usedGapDirection = 0
if postEntryEvent
usedGapDirection := -pos
bool keepUsedBox = not newDay and bias != 0 and not sideways and usedGapDirection == -bias
if not keepUsedBox
while array.size(usedBoxes) > 0
box.delete(array.shift(usedBoxes))
usedGapDirection := 0
for candidate in records
bool visible = bias != 0 and not sideways and candidate.direction == -bias and selected.direction == -bias and candidate.formedBar == selected.formedBar and array.size(usedBoxes) == 0
if visible
color ink = f_color(candidate.direction)
if na(candidate.drawing)
candidate.drawing := box.new(candidate.formedBar - 2, candidate.top, bar_index, candidate.bottom)
box.set_right(candidate.drawing, bar_index)
box.set_border_color(candidate.drawing, color.new(ink, 30))
box.set_bgcolor(candidate.drawing, color.new(ink, 90))
box.set_border_style(candidate.drawing, line.style_solid)
box.set_text(candidate.drawing, candidate.direction == 1 ? "BULLISH FVG" : "BEARISH FVG")
box.set_text_color(candidate.drawing, color.new(ink, 10))
box.set_text_size(candidate.drawing, size.tiny)
box.set_text_halign(candidate.drawing, text.align_left)
box.set_text_valign(candidate.drawing, text.align_top)
else
candidate.hide()
while array.size(auditMarkers) > auditLimit
label oldAudit = array.shift(auditMarkers)
for record in registry
if record.direction != 0 and label.get_x(oldAudit) == record.formedBar
record.auditMarker := na
record.auditDetails := ""
label.delete(oldAudit)
if pos != 0 and showRisk
line.set_x2(liveEntry, bar_index + reach)
line.set_x2(liveStop, bar_index + reach)
line.set_x2(liveTarget, bar_index + reach)
label.set_x(entryText, bar_index + reach)
label.set_x(stopText, bar_index + reach)
label.set_x(targetText, bar_index + reach)
while array.size(usedBoxes) > history
box.delete(array.shift(usedBoxes))
while array.size(tradeLines) > history * 3
line.delete(array.shift(tradeLines))
while array.size(tradeLabels) > history * 5
label.delete(array.shift(tradeLabels))
// END NATIVE FIVE-MINUTE CORE
// Five-minute visuals only.
plot(is5m and showMA ? m15 : na, "50 · 15m", color=blue, linewidth=1)
plot(is5m and showMA ? m30 : na, "50 · 30m", color=red, linewidth=1)
plot(is5m and showMA ? m60 : na, "50 · 1H", color=green, linewidth=2)
plot(is5m and showLiq ? dayHi : na, "Day high", color=color.new(muted, 65), style=plot.style_stepline)
plot(is5m and showLiq ? dayLo : na, "Day low", color=color.new(muted, 65), style=plot.style_stepline)
plot(is5m and showLiq ? prevHi : na, "Previous day high", color=color.new(blue, 65), style=plot.style_stepline)
plot(is5m and showLiq ? prevLo : na, "Previous day low", color=color.new(blue, 65), style=plot.style_stepline)
plot(is5m and showLiq ? prevNYHi : na, "Previous NY high", color=color.new(purple, 65), style=plot.style_stepline)
plot(is5m and showLiq ? prevNYLo : na, "Previous NY low", color=color.new(purple, 65), style=plot.style_stepline)
var array<label> maLabels = array.new<label>()
if barstate.islast
for item in maLabels
label.delete(item)
array.clear(maLabels)
if is5m and showMA and showMAText
array<float> prices = array.from(m15, m30, m60)
array<string> names = array.from("50 · 15m", "50 · 30m", "50 · 1H")
array<color> colors = array.from(blue, red, green)
array<int> sortedIndices = array.sort_indices(prices, order.ascending)
float previous = na
for index in sortedIndices
float level = array.get(prices, index)
if not na(level)
float textY = na(previous) ? level : math.max(level, previous + textGap * syminfo.mintick)
array.push(maLabels, label.new(bar_index + textOffset, textY, array.get(names, index), style=label.style_none, textcolor=array.get(colors, index), size=size.tiny))
previous := textY
// BEGIN OTHER-TIMEFRAME VIEW
type ProjectedPlan
int entryTime = na
int exitTime = na
int sourceClose = na
int deadline = na
int direction = 0
float entry = na
float stop = na
float target = na
int quantity = 0
float loss = na
float profit = na
line entryLine = na
line stopLine = na
line targetLine = na
label entryText = na
label stopText = na
label targetText = na
f_deleteProjection(ProjectedPlan plan) =>
line.delete(plan.entryLine)
line.delete(plan.stopLine)
line.delete(plan.targetLine)
label.delete(plan.entryText)
label.delete(plan.stopText)
label.delete(plan.targetText)
plan.entryLine := na
plan.stopLine := na
plan.targetLine := na
plan.entryText := na
plan.stopText := na
plan.targetText := na
true
f_storeProjection(array<ProjectedPlan> plans, int key, int finish, int sourceClose, int deadline, int direction, float entry, float stop, float target, int quantity, float loss, float profit) =>
bool valid = not na(key) and not na(entry) and not na(stop) and not na(target) and quantity > 0 and (direction == 1 ? stop < entry and entry < target : direction == -1 ? target < entry and entry < stop : false)
if valid
int found = -1
int scan = array.size(plans) - 1
while scan >= 0
ProjectedPlan item = array.get(plans, scan)
if item.entryTime == key
found := scan
break
scan -= 1
bool fitsHistory = array.size(plans) < history or key > array.get(plans, 0).entryTime
if found < 0 and fitsHistory
ProjectedPlan added = ProjectedPlan.new()
added.entryTime := key
added.sourceClose := sourceClose
added.deadline := deadline
added.direction := direction
added.entry := entry
added.stop := stop
added.target := target
added.quantity := quantity
added.loss := loss
added.profit := profit
int insertion = array.size(plans)
while insertion > 0 and array.get(plans, insertion - 1).entryTime > key
insertion -= 1
array.insert(plans, insertion, added)
found := insertion
if found >= 0
ProjectedPlan plan = array.get(plans, found)
if sourceClose >= plan.sourceClose
plan.sourceClose := sourceClose
if na(plan.exitTime) and not na(finish)
plan.exitTime := math.max(plan.entryTime, finish)
while array.size(plans) > history
ProjectedPlan obsolete = array.shift(plans)
f_deleteProjection(obsolete)
true
f_ingestProjection(array<ProjectedPlan> plans, TradeView view, int cutoff, int processedClose) =>
int nextProcessed = processedClose
if not na(view) and view.sourceClose <= cutoff and (na(processedClose) or view.sourceClose > processedClose)
if not na(view.closedEntryTime) and not na(view.closedExitTime) and view.closedExitTime <= cutoff
f_storeProjection(plans, view.closedEntryTime, view.closedExitTime, view.sourceClose, view.closedExitTime, view.closedDirection, view.closedEntry, view.closedStop, view.closedTarget, view.closedQuantity, view.closedLoss, view.closedProfit)
if not na(view.entryTime) and view.entryTime <= cutoff
f_storeProjection(plans, view.entryTime, view.exitTime, view.sourceClose, view.deadline, view.direction, view.entry, view.stop, view.target, view.quantity, view.loss, view.profit)
nextProcessed := view.sourceClose
nextProcessed
// Preserve the frozen 5m prices using timestamp coordinates.
f_renderProjection(ProjectedPlan plan, int cutoff) =>
bool expired = not na(plan.exitTime) or cutoff >= plan.deadline
int rightTime = not na(plan.exitTime) ? plan.exitTime : expired ? plan.deadline : math.min(cutoff + reach * 300000, plan.deadline)
rightTime := math.max(plan.entryTime, rightTime)
int labelTime = rightTime + 300000
if na(plan.entryLine)
plan.entryLine := line.new(plan.entryTime, plan.entry, rightTime, plan.entry, xloc=xloc.bar_time, color=color.new(muted, 35), style=line.style_dotted)
plan.stopLine := line.new(plan.entryTime, plan.stop, rightTime, plan.stop, xloc=xloc.bar_time, color=slColor)
plan.targetLine := line.new(plan.entryTime, plan.target, rightTime, plan.target, xloc=xloc.bar_time, color=tpColor)
plan.entryText := label.new(labelTime, plan.entry, "", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(muted, 94), textcolor=muted, size=size.tiny)
plan.stopText := label.new(labelTime, plan.stop, "", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(slColor, 92), textcolor=slColor, size=size.tiny)
plan.targetText := label.new(labelTime, plan.target, "", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(tpColor, 92), textcolor=tpColor, size=size.tiny)
line.set_xy1(plan.entryLine, plan.entryTime, plan.entry)
line.set_xy2(plan.entryLine, rightTime, plan.entry)
line.set_xy1(plan.stopLine, plan.entryTime, plan.stop)
line.set_xy2(plan.stopLine, rightTime, plan.stop)
line.set_xy1(plan.targetLine, plan.entryTime, plan.target)
line.set_xy2(plan.targetLine, rightTime, plan.target)
label.set_xy(plan.entryText, labelTime, plan.entry)
label.set_xy(plan.stopText, labelTime, plan.stop)
label.set_xy(plan.targetText, labelTime, plan.target)
label.set_text(plan.entryText, "ENTRY · " + f_price(plan.entry) + " · " + str.tostring(plan.quantity) + " ct")
label.set_text(plan.stopText, "SL · " + f_price(plan.stop) + " · " + f_cash(-plan.loss))
label.set_text(plan.targetText, "TP · " + f_price(plan.target) + " · " + f_cash(plan.profit))
true
var array<ProjectedPlan> projectedPlans = array.new<ProjectedPlan>()
var int projectionProcessed = na
var TradeView projectedView = na
int projectionCutoff = barstate.isrealtime ? math.min(time_close, timenow) : time_close
if not is5m
if below5m
projectedView := request.security(syminfo.tickerid, "5", f_closedView5(), lookahead=barmerge.lookahead_on, calc_bars_count=20000)
projectionProcessed := f_ingestProjection(projectedPlans, projectedView, projectionCutoff, projectionProcessed)
else
[currentViews, previousViews] = request.security_lower_tf(syminfo.tickerid, "5", f_viewPair5(), calc_bars_count=20000)
int available = array.size(currentViews)
if available > 0
for intrabarIndex = 0 to available - 1
TradeView previous = array.get(previousViews, intrabarIndex)
TradeView current = array.get(currentViews, intrabarIndex)
if not na(previous) and previous.sourceClose <= projectionCutoff
projectionProcessed := f_ingestProjection(projectedPlans, previous, projectionCutoff, projectionProcessed)
if na(projectedView) or previous.sourceClose > projectedView.sourceClose
projectedView := previous
if not na(current) and current.sourceClose <= projectionCutoff
projectionProcessed := f_ingestProjection(projectedPlans, current, projectionCutoff, projectionProcessed)
if na(projectedView) or current.sourceClose >= projectedView.sourceClose
projectedView := current
// Retain completed trade plans on other timeframes.
if not is5m and barstate.islast
for plan in projectedPlans
if showRisk
f_renderProjection(plan, projectionCutoff)
else
f_deleteProjection(plan)
// END OTHER-TIMEFRAME VIEW
// One bias cell only, on every supported chart timeframe.
var table panel = table.new(position.top_right, 1, 1, bgcolor=#141B25, frame_color=#2B3544, frame_width=1)
if barstate.islast
table.clear(panel, 0, 0, 0, 0)
if showPanel
int displayedBias = is5m ? bias : na(projectedView) ? 0 : projectedView.bias
bool displayedSideways = is5m ? sideways : na(projectedView) ? false : projectedView.sideways
string biasText = displayedSideways ? "SIDEWAYS" : displayedBias == 1 ? "BULLISH" : displayedBias == -1 ? "BEARISH" : "NEUTRAL"
table.cell(panel, 0, 0, biasText, text_color=f_color(displayedBias), text_size=size.small, text_halign=text.align_center)
// Transition-only alerts. Choose Once Per Bar Close.
alertcondition(is5m and longEvent, "APEX LONG", "APEX LONG · {{ticker}} · Entry {{close}}")
alertcondition(is5m and shortEvent, "APEX SHORT", "APEX SHORT · {{ticker}} · Entry {{close}}")
alertcondition(is5m and postEntryEvent, "APEX POST ENTRY", "APEX POST entry · {{ticker}} · {{close}}")
alertcondition(is5m and slEvent, "APEX SL HIT", "APEX SL HIT · {{ticker}}")
alertcondition(is5m and tpEvent, "APEX TARGET HIT", "APEX TARGET HIT · {{ticker}}")
alertcondition(is5m and sessionEvent, "APEX SESSION END", "APEX SESSION END · {{ticker}}")