本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// v9 = v8 with ATR/target-based dynamic per-trade position sizing fused in,
// replacing the flat hardcoded quantity. New "Position Sizing" group:
// Target Per Trade ($), Sizing ATR Length, Max Size (contracts).
// Sizing ATR comes from the signal timeframe. Everything else — signal
// detection, both execution modes, stop/target, day-set levels, PDH/PDL
// bias, EOD flat — is unchanged from v8.
// No VWAP logic, no level logic beyond position sizing's own ATR fetch.
// Levels and VWAP are drawn for reference only.
strategy("Execution Signals v9", overlay = true,
default_qty_type = strategy.fixed,
default_qty_value = 1,
calc_on_every_tick = false,
pyramiding = 0,
process_orders_on_close = true,
max_lines_count = 500,
max_labels_count = 500,
max_boxes_count = 500)
// ═══════════════════════════ INPUTS ═══════════════════════════
signalTF = input.timeframe("5", "Signal Timeframe", group = "Signal Settings",
tooltip = "2m floor. Chart timeframe must be strictly below this.")
useFailures = input.bool(true, "Trade Failures", group = "Signal Settings")
useInsideBars = input.bool(true, "Trade Inside Bars", group = "Signal Settings")
execMode = input.string("Break of Signal Bar", "Execution Mode", group = "Execution",
options = ["Break of Signal Bar", "LTF Signal Bar"],
tooltip = "Break of Signal Bar: enter the moment price closes beyond the HTF signal candle. LTF Signal Bar: that break only sets direction — then wait for a signal bar on the chart timeframe and enter on ITS break.")
ltfMatchDir = input.bool(true, "LTF Signal Must Match Bias", group = "Execution",
tooltip = "Long bias accepts failure-lows and inside bars only; short bias accepts failure-highs and inside bars only.")
biasExpiry = input.int(20, "Bias Expiry (bars)", group = "Execution", minval = 1)
ltfExpiry = input.int(3, "LTF Setup Expiry (bars)", group = "Execution", minval = 1)
stopModel = input.string("Prior Bar", "Stop Placement", group = "Risk",
options = ["Prior Bar", "Prior 2 Bars", "HTF Signal Bar", "LTF Signal Bar"],
tooltip = "LTF Signal Bar only applies in nested execution mode; it falls back to Prior Bar otherwise.")
minStopPts = input.float(5.0, "Minimum Stop (points)", group = "Risk", step = 0.25, minval = 0.25)
maxStopPts = input.float(0.0, "Max Risk Per Trade (points, 0 = off)", group = "Risk", step = 5, minval = 0)
rMultiple = input.float(1.0, "Take Profit (R multiple)", group = "Risk", step = 0.25, minval = 0.25)
targetDollars = input.float(1500, "Target Per Trade ($)", group = "Position Sizing", step = 50, minval = 1,
tooltip = "Contracts sized so a 1-ATR (signal timeframe) favorable move nets roughly this amount.")
atrLen = input.int(14, "Sizing ATR Length (RMA)", group = "Position Sizing", minval = 1)
maxSize = input.int(30, "Max Size (contracts)", group = "Position Sizing", minval = 1)
showSizeInfo = input.bool(true, "Show Size Info Table", group = "Position Sizing")
usePdhlBias = input.bool(false, "PDH / PDL Directional Bias", group = "Bias",
tooltip = "Above PDH = longs only. Below PDL = shorts only.")
pdhlInside = input.string("Neutral", "Inside Prior Day's Range", options = ["Neutral", "Block"], group = "Bias")
paintFailHigh = input.color(color.red, "Failure High Paint", group = "Display", inline = "p1")
paintFailLow = input.color(color.lime, "Failure Low Paint", group = "Display", inline = "p1")
paintInside = input.color(color.yellow, "Inside Bar Paint", group = "Display", inline = "p1")
paintTransp = input.int(80, "Paint Transparency", group = "Display", minval = 0, maxval = 95)
showRange = input.bool(true, "Show Range Label", group = "Display")
offsetTicks = input.int(4, "Range Label Offset (ticks)", group = "Display", minval = 0)
textSizeInput = input.string("small", "Range Text Size", group = "Display",
options = ["tiny", "small", "normal", "large", "huge"])
engineColor = input.color(color.blue, "Hourly Level Color", group = "Day-Set Levels")
engineWidth = input.int(2, "Hourly Level Width", group = "Day-Set Levels", minval = 1, maxval = 4)
pdhlColor = input.color(color.yellow, "PDH/PDL Color", group = "Day-Set Levels")
pdhlWidth = input.int(2, "PDH/PDL Width", group = "Day-Set Levels", minval = 1, maxval = 4)
levelRangePts = input.float(500.0, "Level Range From Open (points)", group = "Day-Set Levels", step = 25, minval = 1)
minSpacingPts = input.float(10.0, "Minimum Level Spacing (points)", group = "Day-Set Levels", step = 1, minval = 0)
showRTHOpen = input.bool(true, "Show 09:30 Open Line", group = "Day-Set Levels")
rthOpenColor = input.color(color.orange, "09:30 Open Color", group = "Day-Set Levels")
rthOpenWidth = input.int(2, "09:30 Open Width", group = "Day-Set Levels", minval = 1, maxval = 4)
labelSize = switch textSizeInput
"tiny" => size.tiny
"large" => size.large
"huge" => size.huge
"normal" => size.normal
=> size.small
// ═══════════════════════════ POSITION SIZING ═══════════════════════════
pv = syminfo.pointvalue
strategy.risk.max_position_size(maxSize)
calcSize(float atrVal) =>
usdPerAtr1 = atrVal * pv
sz = na(usdPerAtr1) or usdPerAtr1 <= 0 ? 1.0 : math.max(1, math.min(maxSize, math.floor(targetDollars / usdPerAtr1)))
sz
// ═══════════════════════════ GUARDS ═══════════════════════════
if not timeframe.isintraday
runtime.error("Intraday charts only.")
if timeframe.in_seconds(signalTF) < 120
runtime.error("Signal timeframe floor is 2 minutes.")
if timeframe.in_seconds() >= timeframe.in_seconds(signalTF)
runtime.error("Chart timeframe must be BELOW the signal timeframe.")
// ═══════════ SIGNAL TF DATA — last COMPLETED bar ═══════════
[sT, sO, sH, sL, sC, sATR] = request.security(syminfo.tickerid, signalTF,
[time[1], open[1], high[1], low[1], close[1], ta.atr(atrLen)[1]], lookahead = barmerge.lookahead_on)
newPeriod = ta.change(sT) != 0
sigDurMs = timeframe.in_seconds(signalTF) * 1000
chartDurMs = timeframe.in_seconds() * 1000
var table sizeTable = table.new(position.bottom_right, 2, 3, bgcolor = color.new(color.gray, 20), border_width = 1, border_color = color.new(color.white, 70))
if showSizeInfo and barstate.islast
table.clear(sizeTable, 0, 0, 1, 2)
liveSize = calcSize(sATR)
table.cell(sizeTable, 0, 0, "Sig ATR", text_color = color.white, text_size = size.small)
table.cell(sizeTable, 1, 0, str.tostring(sATR, format.mintick), text_color = color.white, text_size = size.small)
table.cell(sizeTable, 0, 1, "$ / 1 ATR", text_color = color.white, text_size = size.small)
table.cell(sizeTable, 1, 1, "$" + str.tostring(sATR * pv, "#"), text_color = color.white, text_size = size.small)
table.cell(sizeTable, 0, 2, "Next Size", text_color = color.white, text_size = size.small)
table.cell(sizeTable, 1, 2, str.tostring(liveSize, "#"), text_color = color.new(#9C27B0, 0), text_size = size.large)
// ═══════════════ SESSION — RTH 09:30 to 16:15 NY ═══════════════
RTH_OPEN = 570
RTH_CLOSE = 975
FLAT_TIME = 959
EVE_OPEN = 1080
barMins = hour(time, "America/New_York") * 60 + minute(time, "America/New_York")
barDay = dayofmonth(time, "America/New_York")
barMonth = month(time, "America/New_York")
barYear = year(time, "America/New_York")
newDayNY = ta.change(barDay) != 0
inRTH = barMins >= RTH_OPEN and barMins < RTH_CLOSE
isCloseBar = barMins >= FLAT_TIME and barMins[1] < FLAT_TIME
noNewTrades = barMins >= FLAT_TIME and barMins < EVE_OPEN
// ═══════════ RTH HOURLY BUCKETS (drawing only) ═══════════
hIdx = barMins < 630 ? 0 : barMins < 690 ? 1 : barMins < 750 ? 2 :
barMins < 810 ? 3 : barMins < 870 ? 4 : barMins < 930 ? 5 : 6
var int curIdx = -1
var float curO = na
var float curC = na
var int curT = na
var float h1O = na
var float h1C = na
var float h2O = na
var float h2C = na
var int h1T = na
bool hourDone = false
if curIdx != -1 and (not inRTH or hIdx != curIdx)
h2O := h1O
h2C := h1C
h1O := curO
h1C := curC
h1T := curT
curIdx := -1
hourDone := true
if inRTH and curIdx == -1
curIdx := hIdx
curO := open
curT := time
if inRTH
curC := close
curIdx := hIdx
var float[] masterPrices = array.new_float()
var int[] masterTimes = array.new_int()
var float dayPDH = na
var float dayPDL = na
if hourDone and not na(h1O)
if array.size(masterPrices) > 0
for i = array.size(masterPrices) - 1 to 0
lvl = array.get(masterPrices, i)
if (h1O < lvl and h1C > lvl) or (h1O > lvl and h1C < lvl)
array.remove(masterPrices, i)
array.remove(masterTimes, i)
if not na(h2O)
flippedUp = h2C < h2O and h1C > h1O
flippedDown = h2C > h2O and h1C < h1O
if flippedUp or flippedDown
threeMonths = 90 * 24 * 60 * 60 * 1000
allowNew = true
if array.size(masterPrices) > 0
for i = array.size(masterPrices) - 1 to 0
if math.abs(array.get(masterPrices, i) - h1O) < minSpacingPts
if (time - array.get(masterTimes, i)) > threeMonths
array.remove(masterPrices, i)
array.remove(masterTimes, i)
else
allowNew := false
if allowNew
array.push(masterPrices, h1O)
array.push(masterTimes, h1T)
// ═══════════ DAILY CYCLE — deploy day-set ═══════════
var float rthHigh = na
var float rthLow = na
var bool setDeployed = true
deployEvening = barMins >= EVE_OPEN
deployMorning = newDayNY and barMins < RTH_CLOSE
deployNow = not setDeployed and not na(rthHigh) and not na(rthLow) and (deployEvening or deployMorning)
if deployNow
dayShift = deployEvening ? 0 : -1
startTime = timestamp("America/New_York", barYear, barMonth, barDay + dayShift, 18, 0)
endTime = timestamp("America/New_York", barYear, barMonth, barDay + dayShift + 1, 16, 15)
dayPDH := rthHigh
dayPDL := rthLow
line.new(startTime, rthHigh, endTime, rthHigh, xloc = xloc.bar_time, color = pdhlColor, width = pdhlWidth)
line.new(startTime, rthLow, endTime, rthLow, xloc = xloc.bar_time, color = pdhlColor, width = pdhlWidth)
if array.size(masterPrices) > 0
for i = 0 to array.size(masterPrices) - 1
lvl = array.get(masterPrices, i)
if math.abs(lvl - open) <= levelRangePts
line.new(startTime, lvl, endTime, lvl, xloc = xloc.bar_time, color = engineColor, width = engineWidth)
setDeployed := true
rthHigh := na
rthLow := na
if inRTH
rthHigh := na(rthHigh) ? high : math.max(rthHigh, high)
rthLow := na(rthLow) ? low : math.min(rthLow, low)
setDeployed := false
plot(ta.vwap(hlc3), "VWAP", color = color.new(color.purple, 0), linewidth = 2)
// ═══════════ 09:30 OPEN LINE ═══════════
var float rthOpenPx = na
rthStart = inRTH and (not inRTH[1] or newDayNY)
if rthStart
rthOpenPx := open
if showRTHOpen
oStart = timestamp("America/New_York", barYear, barMonth, barDay, 9, 30)
oEnd = timestamp("America/New_York", barYear, barMonth, barDay, 16, 15)
line.new(oStart, open, oEnd, open,
xloc = xloc.bar_time, color = rthOpenColor, width = rthOpenWidth)
plotshape(rthStart, "RTH open fired", style = shape.circle,
location = location.belowbar, color = color.orange, size = size.tiny)
// ═══════════ PDH / PDL BIAS ═══════════
pdhlAllows(int dir) =>
bool ok = true
if usePdhlBias and not na(dayPDH) and not na(dayPDL)
if close > dayPDH
ok := dir == 1
else if close < dayPDL
ok := dir == -1
else if pdhlInside == "Block"
ok := false
ok
// ═══════════ HTF SIGNAL DETECTION ═══════════
var float c1H = na
var float c1L = na
var int c1T = na
var float sigHigh = na
var float sigLow = na
var bool armed = false
flat = strategy.position_size == 0
bool sigFailHigh = false
bool sigFailLow = false
bool sigInside = false
float sigRange = na
if newPeriod
if armed and flat
armed := false
nO = sO
nH = sH
nL = sL
nC = sC
maxSkew = sigDurMs + sigDurMs / 2
prevContig = not na(c1T) and (sT - c1T) <= maxSkew
nowContig = (time - sT) <= maxSkew
if not na(c1H) and not na(nH) and prevContig and nowContig
uw = nH - math.max(nO, nC)
lw = math.min(nO, nC) - nL
sigFailHigh := (nH > c1H and nC <= c1H and uw > 0) and useFailures
sigFailLow := (nL < c1L and nC >= c1L and lw > 0) and useFailures
sigInside := (nH < c1H and nL > c1L) and useInsideBars
sigRange := nH - nL
if sigFailHigh or sigFailLow or sigInside
if flat and not noNewTrades
sigHigh := nH
sigLow := nL
armed := true
pc = sigInside ? paintInside : sigFailHigh ? paintFailHigh : paintFailLow
box.new(sT, nH, sT + sigDurMs, nL, xloc = xloc.bar_time,
bgcolor = color.new(pc, paintTransp), border_color = color.new(pc, 20), border_width = 1)
if showRange
label.new(sT + sigDurMs - chartDurMs, nL - offsetTicks * syminfo.mintick,
str.tostring(sigRange, format.mintick), xloc = xloc.bar_time,
style = label.style_none, textcolor = color.gray, size = labelSize)
c1H := nH
c1L := nL
c1T := sT
// ═══════════ LTF SIGNAL BAR (chart timeframe) ═══════════
ltfUw = high - math.max(open, close)
ltfLw = math.min(open, close) - low
ltfFH = high > high[1] and close <= high[1] and ltfUw > 0
ltfFL = low < low[1] and close >= low[1] and ltfLw > 0
ltfIB = high < high[1] and low > low[1]
// ═══════════ TRADE STATE ═══════════
var int pendBar = na
var float pendEntry = na
var float pendStop = na
var float pendTgt = na
var int pendDir = 0
var box tpBox = na
var box slBox = na
var bool inTrade = false
var int seenClosed = 0
if not na(pendBar)
if strategy.opentrades > 0 or strategy.closedtrades > seenClosed
float tpTop = pendDir == 1 ? pendTgt : pendEntry
float tpBot = pendDir == 1 ? pendEntry : pendTgt
float slTop = pendDir == 1 ? pendEntry : pendStop
float slBot = pendDir == 1 ? pendStop : pendEntry
tpBox := box.new(pendBar, tpTop, bar_index, tpBot,
bgcolor = color.new(color.green, 85), border_color = color.new(color.green, 50))
slBox := box.new(pendBar, slTop, bar_index, slBot,
bgcolor = color.new(color.red, 85), border_color = color.new(color.red, 50))
inTrade := true
pendBar := na
// ═══════════ NESTED-MODE STATE ═══════════
var int biasDir = 0
var float htfStopPx = na
var int biasLeft = 0
var float ltfHi = na
var float ltfLo = na
var int ltfLeft = 0
if biasLeft > 0
biasLeft -= 1
if biasLeft == 0
biasDir := 0
if ltfLeft > 0
ltfLeft -= 1
if ltfLeft == 0
ltfHi := na
ltfLo := na
// ═══════════ EXECUTION ═══════════
placeTrade(int d, float entryPx, float stopRaw) =>
stopPx = d == 1 ? math.min(stopRaw, entryPx - minStopPts) : math.max(stopRaw, entryPx + minStopPts)
dist = d == 1 ? entryPx - stopPx : stopPx - entryPx
[stopPx, dist]
canTrade = flat and not noNewTrades
if canTrade and execMode == "Break of Signal Bar"
if armed
longTrig = close > sigHigh
shortTrig = close < sigLow
d = longTrig ? 1 : shortTrig ? -1 : 0
if d != 0
rawStop = stopModel == "HTF Signal Bar" ? (d == 1 ? sigLow : sigHigh) :
stopModel == "Prior 2 Bars" ? (d == 1 ? math.min(low[1], low) : math.max(high[1], high)) :
(d == 1 ? low[1] : high[1])
[stopPx, stopDist] = placeTrade(d, close, rawStop)
posSize = calcSize(sATR)
riskOK = (maxStopPts <= 0 or stopDist <= maxStopPts) and pdhlAllows(d)
if riskOK
tgt = close + d * stopDist * rMultiple
if d == 1
strategy.entry("Long", strategy.long, qty = posSize)
strategy.exit("Long X", from_entry = "Long", stop = stopPx, limit = tgt)
else
strategy.entry("Short", strategy.short, qty = posSize)
strategy.exit("Short X", from_entry = "Short", stop = stopPx, limit = tgt)
pendBar := bar_index
pendEntry := close
pendStop := stopPx
pendTgt := tgt
pendDir := d
alert((d == 1 ? "LONG " : "SHORT ") + str.tostring(posSize, "#") +
" @ " + str.tostring(close, format.mintick) +
" stop " + str.tostring(stopPx, format.mintick) +
" tgt " + str.tostring(tgt, format.mintick), alert.freq_once_per_bar)
armed := false
if canTrade and execMode == "LTF Signal Bar"
// ── nested mode ──
// step 1: the HTF break only sets direction
if armed and biasDir == 0
if close > sigHigh
biasDir := 1
htfStopPx := sigLow
biasLeft := biasExpiry
armed := false
else if close < sigLow
biasDir := -1
htfStopPx := sigHigh
biasLeft := biasExpiry
armed := false
// step 2: entry on the break of a previously armed LTF signal bar
if biasDir != 0 and not na(ltfHi)
trig = biasDir == 1 ? close > ltfHi : close < ltfLo
if trig
rawStop = stopModel == "HTF Signal Bar" ? htfStopPx :
stopModel == "LTF Signal Bar" ? (biasDir == 1 ? ltfLo : ltfHi) :
stopModel == "Prior 2 Bars" ? (biasDir == 1 ? math.min(low[1], low) : math.max(high[1], high)) :
(biasDir == 1 ? low[1] : high[1])
[stopPx, stopDist] = placeTrade(biasDir, close, rawStop)
posSize = calcSize(sATR)
riskOK = (maxStopPts <= 0 or stopDist <= maxStopPts) and pdhlAllows(biasDir)
if riskOK
tgt = close + biasDir * stopDist * rMultiple
if biasDir == 1
strategy.entry("Long", strategy.long, qty = posSize)
strategy.exit("Long X", from_entry = "Long", stop = stopPx, limit = tgt)
else
strategy.entry("Short", strategy.short, qty = posSize)
strategy.exit("Short X", from_entry = "Short", stop = stopPx, limit = tgt)
pendBar := bar_index
pendEntry := close
pendStop := stopPx
pendTgt := tgt
pendDir := biasDir
alert((biasDir == 1 ? "LONG " : "SHORT ") + str.tostring(posSize, "#") +
" @ " + str.tostring(close, format.mintick) +
" stop " + str.tostring(stopPx, format.mintick) +
" tgt " + str.tostring(tgt, format.mintick), alert.freq_once_per_bar)
biasDir := 0
ltfHi := na
ltfLo := na
// step 3: arm an LTF setup from THIS bar (after the entry check, so a bar
// cannot both trigger and re-arm)
if biasDir != 0
ok = ltfMatchDir ? (biasDir == 1 ? ((ltfFL and useFailures) or (ltfIB and useInsideBars))
: ((ltfFH and useFailures) or (ltfIB and useInsideBars)))
: (((ltfFH or ltfFL) and useFailures) or (ltfIB and useInsideBars))
if ok
ltfHi := high
ltfLo := low
ltfLeft := ltfExpiry
// ═══════════ EOD FORCE FLAT ═══════════
if isCloseBar
if not flat
strategy.close_all(comment = "EOD")
armed := false
biasDir := 0
ltfHi := na
ltfLo := na
// ═══════════ LIFECYCLE ═══════════
closedNow = strategy.closedtrades > seenClosed
if not na(tpBox) and (inTrade or closedNow)
box.set_right(tpBox, bar_index)
box.set_right(slBox, bar_index)
if closedNow
seenClosed := strategy.closedtrades
inTrade := false
alert("EXIT @ " + str.tostring(close, format.mintick), alert.freq_once_per_bar)