Position Size Planner v2

jjjjiiiijjjooohhhnnn · study · 245 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
indicator("Position Size Planner v2", overlay=true, max_lines_count=50, max_labels_count=50)
 
// ══ Inputs ══════════════════════════════════════════════════════════
 
// ── Risk ──
riskAmt    = input.float(300, "Max risk per trade (CAD)", minval=0, group="Risk")
bufferAmt  = input.float(50, "Allowable buffer (CAD)", minval=0, group="Risk", tooltip="Risk may land anywhere within target ± buffer. Set 0 for strict rounding down.")
allowUnder = input.bool(true, "Buffer also applies below target", group="Risk", tooltip="Off = buffer only lets risk go OVER target; sizes under target still round down.")
strictMode = input.bool(false, "Never exceed budget (round down only)", group="Risk", tooltip="Ignores the buffer and always rounds DOWN, so actual risk never goes above the max risk per trade.")
fx         = input.float(1.0, "Price currency → CAD rate (1 if already CAD)", minval=0, group="Risk")
 
// ── Contract & costs ──
autoPV   = input.bool(true, "Auto-detect contract multiplier from chart symbol", group="Contract & costs", tooltip="Uses the chart symbol's point value (NQ = 20, ES = 50, stocks = 1). Turn OFF if you chart one contract but trade another (e.g. chart NQ, trade MNQ = 2).")
ptManual = input.float(1.0, "Manual value per 1.00 move, per unit", minval=0, group="Contract & costs", tooltip="Used when auto-detect is off. MNQ = 2, NQ = 20, MES = 5, ES = 50.")
feeUnit  = input.float(0.0, "Round-trip fees per unit (CAD)", minval=0, group="Contract & costs")
slipTicks = input.float(0.0, "Slippage allowance (ticks, round trip)", minval=0, group="Contract & costs", tooltip="Added to risk per unit as slippage cost.")
unitStep = input.float(1.0, "Unit step (1 = whole units)", minval=0.0001, group="Contract & costs")
 
// ── Account & limits ──
acctSize    = input.float(0, "Account size (CAD, 0 = off)", minval=0, group="Account & limits")
dailyLimit  = input.float(0, "Daily loss limit (CAD, 0 = off)", minval=0, group="Account & limits")
dailyUsed   = input.float(0, "Loss already used today (CAD)", minval=0, group="Account & limits")
maxUnitsIn  = input.int(0, "Max units allowed by broker/firm (0 = no cap)", minval=0, group="Account & limits")
marginUnit  = input.float(0, "Margin per unit (CAD, 0 = off)", minval=0, group="Account & limits")
availMargin = input.float(0, "Available margin (CAD)", minval=0, group="Account & limits")
 
// ── Points ──
entry    = input.price(0.0, "1) Entry price (click on chart)", confirm=true, group="Points")
stopIn   = input.price(0.0, "2) Stop / swing (click on chart)", confirm=true, group="Points")
stopMode = input.string("Manual", "Stop mode", options=["Manual", "ATR"], group="Points", tooltip="ATR mode ignores the clicked stop and places it ATR x multiplier away from entry.")
dirSel   = input.string("Long", "Direction (ATR mode only)", options=["Long", "Short"], group="Points", tooltip="In Manual mode, direction is detected automatically from entry vs stop.")
atrLen   = input.int(14, "ATR length", minval=1, group="Points")
atrMult  = input.float(1.5, "ATR multiplier", minval=0.1, group="Points")
 
// ── Targets ──
r1   = input.float(1.0, "Target 1 (R)", group="Targets")
r2   = input.float(2.0, "Target 2 (R)", group="Targets")
r3   = input.float(3.0, "Target 3 (R)", group="Targets")
pct1 = input.float(50, "Exit % at Target 1", minval=0, maxval=100, group="Targets")
pct2 = input.float(25, "Exit % at Target 2", minval=0, maxval=100, group="Targets", tooltip="Remainder runs to Target 3.")
 
// ── Display ──
tblPos  = input.string(position.top_right, "Table position", options=[position.top_right, position.middle_right, position.bottom_right, position.top_left, position.middle_left, position.bottom_left, position.bottom_center], group="Display")
tblSize = input.string(size.small, "Table text size", options=[size.tiny, size.small, size.normal], group="Display")
compact = input.bool(false, "Compact table", group="Display", tooltip="Shows only direction, units, risk and status.")
 
// ══ Calculations ════════════════════════════════════════════════════
 
ptV    = autoPV ? syminfo.pointvalue : ptManual
atrVal = ta.atr(atrLen)
 
stopAtr = dirSel == "Long" ? entry - atrVal * atrMult : entry + atrVal * atrMult
stop    = stopMode == "ATR" ? math.round_to_mintick(stopAtr) : stopIn
 
isLong    = entry > stop
dir       = isLong ? 1 : -1
priceRisk = math.abs(entry - stop)
stopTicks = priceRisk / syminfo.mintick
 
moveRisk    = priceRisk * ptV * fx
slipCost    = slipTicks * syminfo.mintick * ptV * fx
riskPerUnit = moveRisk + feeUnit + slipCost
rawUnits    = riskPerUnit > 0 ? riskAmt / riskPerUnit : 0.0
 
// two nearest sizes: just under target (A) and just over (B)
loU = math.floor(rawUnits / unitStep + 1e-9) * unitStep
hiU = loU + unitStep
loR = loU * riskPerUnit
hiR = hiU * riskPerUnit
 
bandLo = allowUnder ? riskAmt - bufferAmt : riskAmt - 0.0000001
bandHi = riskAmt + bufferAmt
 
loOK   = loU > 0 and loR >= bandLo - 1e-9 and loR <= bandHi + 1e-9
hiOK   = hiR >= bandLo - 1e-9 and hiR <= bandHi + 1e-9
pickHi = not strictMode and hiOK and (not loOK or (hiR - riskAmt) < (riskAmt - loR))
 
unitsRaw = pickHi ? hiU : loU   // falls back to rounding down if nothing fits
 
// caps: broker/firm max units and margin
float capUnits = 1e12
if maxUnitsIn > 0
    capUnits := math.min(capUnits, maxUnitsIn)
if marginUnit > 0 and availMargin > 0
    capUnits := math.min(capUnits, availMargin / marginUnit)
capUnits := math.floor(capUnits / unitStep + 1e-9) * unitStep
 
units  = math.min(unitsRaw, capUnits)
capped = unitsRaw > capUnits
 
actualRisk = units * riskPerUnit
posValue   = units * entry * ptV * fx
marginReq  = units * marginUnit
inBand     = loOK or hiOK
diffPct    = riskAmt > 0 ? (actualRisk - riskAmt) / riskAmt * 100 : 0.0
loPct      = riskAmt > 0 ? (loR - riskAmt) / riskAmt * 100 : 0.0
hiPct      = riskAmt > 0 ? (hiR - riskAmt) / riskAmt * 100 : 0.0
 
riskPctAcct = acctSize > 0 ? actualRisk / acctSize * 100 : na
dailyLeft   = dailyLimit > 0 ? dailyLimit - dailyUsed : na
overDaily   = dailyLimit > 0 and actualRisk > dailyLeft + 1e-9
mismatch    = not autoPV and syminfo.pointvalue != ptManual
 
// status text + color
string status = ""
color  stCol  = color.new(color.green, 20)
if units <= 0
    status := "Stop too wide: 0 units"
    stCol  := color.new(color.red, 10)
else if actualRisk > bandHi + 1e-9
    status := "OVER MAX RISK"
    stCol  := color.new(color.red, 10)
else if capped
    status := "Capped by limits"
    stCol  := color.new(color.orange, 10)
else if strictMode
    status := "Within budget (strict)"
else if inBand and actualRisk > riskAmt + 1e-9
    status := "Over target, within buffer"
    stCol  := color.new(color.orange, 10)
else if inBand and actualRisk < riskAmt - 1e-9
    status := "Under target, within buffer"
else if inBand
    status := "Exact"
else
    status := "Nothing fits buffer (rounded down)"
    stCol  := color.new(color.orange, 10)
 
// targets + scale-out
p1 = entry + dir * priceRisk * r1
p2 = entry + dir * priceRisk * r2
p3 = entry + dir * priceRisk * r3
 
pctB = math.min(pct2, 100 - pct1)
q1   = math.floor(units * pct1 / 100 / unitStep + 1e-9) * unitStep
q2   = math.floor(units * pctB / 100 / unitStep + 1e-9) * unitStep
q3   = math.max(units - q1 - q2, 0)
 
pnl1    = q1 * riskPerUnit * r1
pnl2    = q2 * riskPerUnit * r2
pnl3    = q3 * riskPerUnit * r3
pnlAll  = pnl1 + pnl2 + pnl3
blendedR = units > 0 ? (q1 * r1 + q2 * r2 + q3 * r3) / units : 0.0
 
// ══ Alerts ══════════════════════════════════════════════════════════
alertcondition(ta.cross(close, entry), "Entry touched", "Price touched entry")
alertcondition(ta.cross(close, stop),  "Stop touched",  "Price touched stop")
alertcondition(ta.cross(close, p1),    "Target 1 hit - move stop to break-even", "Target 1 hit: consider moving stop to break-even")
alertcondition(ta.cross(close, p2),    "Target 2 hit", "Target 2 hit")
alertcondition(ta.cross(close, p3),    "Target 3 hit", "Target 3 hit")
alertcondition(units != units[1],      "Unit size changed", "Position size changed (stop distance or inputs changed)")
 
// ══ Drawing ═════════════════════════════════════════════════════════
var table t = table.new(tblPos, 2, 22, border_width=1)
var line lEntry = na
var line lStop  = na
var line lT1 = na
var line lT2 = na
var line lT3 = na
var label bEntry = na
var label bStop  = na
var label b1 = na
var label b2 = na
var label b3 = na
 
f_line(p, c) => line.new(bar_index - 5, p, bar_index + 5, p, extend=extend.both, color=c, width=1)
f_lbl(p, txt, c) => label.new(bar_index + 8, p, txt, style=label.style_label_left, color=c, textcolor=color.white, size=size.small)
 
hdr = color.new(color.gray, 20)
f_row(table tbl, int r, string k, string v, color vBg, color vTxt, string sz) =>
    table.cell(tbl, 0, r, k, text_color=color.white, bgcolor=hdr, text_size=sz)
    table.cell(tbl, 1, r, v, text_color=vTxt, bgcolor=vBg, text_size=sz)
 
if barstate.islast and priceRisk > 0
    line.delete(lEntry)
    line.delete(lStop)
    line.delete(lT1)
    line.delete(lT2)
    line.delete(lT3)
    label.delete(bEntry)
    label.delete(bStop)
    label.delete(b1)
    label.delete(b2)
    label.delete(b3)
 
    lEntry := f_line(entry, color.new(color.blue, 0))
    lStop  := f_line(stop,  color.new(color.red, 0))
    lT1    := f_line(p1, color.new(color.green, 30))
    lT2    := f_line(p2, color.new(color.green, 30))
    lT3    := f_line(p3, color.new(color.green, 30))
 
    bEntry := f_lbl(entry, "Entry " + str.tostring(entry, format.mintick) + " | " + str.tostring(units) + " units", color.blue)
    bStop  := f_lbl(stop,  "Stop " + str.tostring(stop, format.mintick) + " | risk $" + str.tostring(actualRisk, "#.##"), color.red)
    b1     := f_lbl(p1, str.tostring(r1) + "R  " + str.tostring(p1, format.mintick) + " | exit " + str.tostring(q1) + " | +$" + str.tostring(pnl1, "#.##") + " (BE stop)", color.green)
    b2     := f_lbl(p2, str.tostring(r2) + "R  " + str.tostring(p2, format.mintick) + " | exit " + str.tostring(q2) + " | +$" + str.tostring(pnl2, "#.##"), color.green)
    b3     := f_lbl(p3, str.tostring(r3) + "R  " + str.tostring(p3, format.mintick) + " | exit " + str.tostring(q3) + " | +$" + str.tostring(pnl3, "#.##"), color.green)
 
    table.clear(t, 0, 0, 1, 21)
    int r = 0
    dirCol = isLong ? color.green : color.red
 
    f_row(t, r, "Direction", isLong ? "LONG" : "SHORT", dirCol, color.white, tblSize)
    r += 1
 
    if not compact
        f_row(t, r, "Risk budget", "$" + str.tostring(riskAmt, "#.##") + (strictMode ? "  (strict, no buffer)" : ""), hdr, color.white, tblSize)
        r += 1
        if not strictMode
            f_row(t, r, "Allowable buffer", (allowUnder ? "±$" : "+$") + str.tostring(bufferAmt, "#.##") + "  (max $" + str.tostring(bandHi, "#.##") + ")", hdr, color.white, tblSize)
            r += 1
        contractTxt = (autoPV ? "auto " : "manual ") + "x" + str.tostring(ptV, "#.##") + " | tick $" + str.tostring(syminfo.mintick * ptV, "#.##") + (mismatch ? "  ! chart is x" + str.tostring(syminfo.pointvalue, "#.##") : "")
        f_row(t, r, "Contract", contractTxt, mismatch ? color.new(color.orange, 10) : hdr, color.white, tblSize)
        r += 1
        f_row(t, r, "Stop distance", str.tostring(priceRisk, format.mintick) + " pts | " + str.tostring(stopTicks, "#.#") + " ticks", hdr, color.white, tblSize)
        r += 1
        f_row(t, r, "Risk / unit", "$" + str.tostring(riskPerUnit, "#.##") + "  (move " + str.tostring(moveRisk, "#.##") + " + fees " + str.tostring(feeUnit, "#.##") + " + slip " + str.tostring(slipCost, "#.##") + ")", hdr, color.white, tblSize)
        r += 1
        f_row(t, r, "Size options", "A: " + str.tostring(loU) + "u $" + str.tostring(loR, "#.##") + " (" + str.tostring(loPct, "+#.#;-#.#") + "%)  |  B: " + str.tostring(hiU) + "u $" + str.tostring(hiR, "#.##") + " (" + str.tostring(hiPct, "+#.#;-#.#") + "%)", hdr, color.white, tblSize)
        r += 1
 
    table.cell(t, 0, r, "UNITS TO TRADE", text_color=color.black, bgcolor=color.yellow, text_size=tblSize)
    table.cell(t, 1, r, str.tostring(units) + (capped ? "  (capped)" : ""), text_color=color.black, bgcolor=color.yellow, text_size=tblSize)
    r += 1
    f_row(t, r, "Actual risk", "$" + str.tostring(actualRisk, "#.##") + "  (" + str.tostring(diffPct, "+#.#;-#.#") + "% vs target)", hdr, color.white, tblSize)
    r += 1
    f_row(t, r, "Status", status, stCol, color.white, tblSize)
    r += 1
 
    if not compact
        f_row(t, r, "Position value", "$" + str.tostring(posValue, "#.##"), hdr, color.white, tblSize)
        r += 1
        if acctSize > 0
            f_row(t, r, "Risk % of account", str.tostring(riskPctAcct, "#.##") + "%", hdr, color.white, tblSize)
            r += 1
        if dailyLimit > 0
            f_row(t, r, "Daily loss left", "$" + str.tostring(dailyLeft, "#.##") + (overDaily ? "  EXCEEDS LIMIT" : ""), overDaily ? color.new(color.red, 10) : hdr, color.white, tblSize)
            r += 1
        if marginUnit > 0
            f_row(t, r, "Margin required", "$" + str.tostring(marginReq, "#.##") + (availMargin > 0 ? " of $" + str.tostring(availMargin, "#.##") : ""), hdr, color.white, tblSize)
            r += 1
        f_row(t, r, "Scale-out", str.tostring(q1) + " @ " + str.tostring(r1) + "R | " + str.tostring(q2) + " @ " + str.tostring(r2) + "R | " + str.tostring(q3) + " @ " + str.tostring(r3) + "R", hdr, color.white, tblSize)
        r += 1
        f_row(t, r, "Blended R / P&L", str.tostring(blendedR, "#.##") + "R | +$" + str.tostring(pnlAll, "#.##") + " if all hit", hdr, color.white, tblSize)
        r += 1

← 返回列表