Scaled position calculator

JCT_PT · study · 270 行 · 点赞 10 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("Scaled position calculator", "Scaled position calculator", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 50)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
const string G_LVL = "Levels (click / drag on chart)"
const string G_POS = "Position"
const string G_VIS = "Visual"
 
topIn     = input.price(0.0,   "Range top",    confirm = true, group = G_LVL)
botIn     = input.price(0.0,   "Range bottom", confirm = true, group = G_LVL)
slIn      = input.price(0.0,   "Stop loss",    confirm = true, group = G_LVL)
tpIn      = input.price(0.0,   "Take profit",  confirm = true, group = G_LVL)
showTp    = input.bool(true,   "Use take profit", group = G_LVL, tooltip = "Untick to hide the TP and the RR.")
 
const string M_USD  = "Total size ($)"
const string M_PCT  = "Risk % of equity"
const string M_RISK = "Risk in $"
 
const string T_SIZE = "Tick ONE sizing method.\nTotal size ($): uses this value and calculates the risk.\nRisk % / Risk $: calculates the total size so that the loss at the SL equals that risk exactly.\nIf more than one (or none) is ticked, nothing is calculated and a warning is shown on the chart."
 
nOrders   = input.int(10,      "Number of orders", minval = 1, maxval = 50, group = G_POS)
useUsd    = input.bool(false,   "Total size ($)",     inline = "usd",  group = G_POS)
totalUsd  = input.float(3000.,  "",                   minval = 0, inline = "usd",  group = G_POS, tooltip = T_SIZE)
usePct    = input.bool(false,   "Risk (% of equity)", inline = "pct",  group = G_POS)
riskPctIn = input.float(0.2,   "",                   minval = 0, step = 0.1, inline = "pct", group = G_POS, tooltip = T_SIZE)
useRisk   = input.bool(true,    "Risk ($)",           inline = "risk", group = G_POS)
riskUsdIn = input.float(50.,    "",                   minval = 0, inline = "risk", group = G_POS, tooltip = T_SIZE)
equityUsd = input.float(10000., "Account equity ($)", minval = 0, group = G_POS)
 
string sizeMode = usePct ? M_PCT : useRisk ? M_RISK : M_USD
int    nChecked = (useUsd ? 1 : 0) + (usePct ? 1 : 0) + (useRisk ? 1 : 0)
 
offBars   = input.int(10,  "Box start (bars: − back / + forward)", minval = -400, maxval = 400, group = G_VIS)
widthBars = input.int(10,  "Box width (bars)", minval = 1, maxval = 400, group = G_VIS)
colMkt    = input.color(color.new(#5D606B, 0),  "Market order",  group = G_VIS)
colLmtBuy = input.color(color.new(#089981, 0),  "Limit order (buy / long)",   group = G_VIS)
colLmtSel = input.color(color.new(#B22833, 0),  "Limit order (sell / short)", group = G_VIS)
colSl     = input.color(color.new(#9C27B0, 0),  "Stop loss",     group = G_VIS)
colTp     = input.color(color.new(#00BCD4, 0),  "Take profit",   group = G_VIS)
colAvg    = input.color(color.new(#FFEB3B, 0),  "Average entry", group = G_VIS)
colRisk   = input.color(color.new(#F23645, 90), "Risk zone (avg → SL)",   group = G_VIS)
colReward = input.color(color.new(#00BCD4, 90), "Reward zone (avg → TP)", group = G_VIS)
colRange  = input.color(color.new(#787B86, 95), "Order range",   group = G_VIS)
wOrder    = input.int(2, "Order line width", minval = 1, maxval = 5, group = G_VIS)
wSl       = input.int(4, "SL / TP line width", minval = 1, maxval = 5, group = G_VIS)
wAvg      = input.int(2, "Avg line width",   minval = 1, maxval = 5, group = G_VIS)
lblSizeS  = input.string("Normal", "Grid text size",  options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_VIS)
tblSizeS  = input.string("Normal", "Table text size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_VIS)
showTable = input.bool(true, "Show table", group = G_VIS)
tablePosS = input.string("Top right", "Table position",
     options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_VIS)
 
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
fPrice(float v) => str.tostring(v, format.mintick)
fQty(float v)   => str.tostring(v, "#.######")
fUsd(float v)   => str.tostring(v, "#,##0.00") + " $"
 
fSize(string s) =>
    switch s
        "Tiny"  => size.tiny
        "Small" => size.small
        "Large" => size.large
        "Huge"  => size.huge
        => size.normal
 
tablePos = switch tablePosS
    "Top left"     => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left"  => position.bottom_left
    => position.top_right
 
// One size step up (for highlighted key figures)
fUp(string s) =>
    s == size.tiny ? size.small : s == size.small ? size.normal : s == size.normal ? size.large : size.huge
 
lblSize = fSize(lblSizeS)
tblSize = fSize(tblSizeS)
kpiSize = fUp(tblSize)
 
// Real-time current price: last trade of the symbol (real feed, even on Heikin Ashi / Renko)
float livePrice = request.security(ticker.standard(syminfo.tickerid), timeframe.period, close)
 
var table tbl = na
 
cell(int c, int r, string txt, color tc = na, color bg = na, string sz = na, bool bold = false) =>
    table.cell(tbl, c, r, txt, text_color = na(tc) ? chart.fg_color : tc, bgcolor = bg,
         text_size = na(sz) ? tblSize : sz, text_formatting = bold ? text.format_bold : text.format_none)
 
// Full-width row (merged across all columns)
wideRow(int r, string txt, color tc = na, color bg = na, string sz = na, bool bold = false) =>
    cell(0, r, txt, tc, bg, sz, bold)
    table.merge_cells(tbl, 0, r, 6, r)
 
// ─────────────────────────────────────────────────────────────────────────────
// Calculation and drawing (last bar only)
// ─────────────────────────────────────────────────────────────────────────────
if barstate.islast
    // Clear everything drawn on the previous tick
    for l in line.all
        l.delete()
    for lb in label.all
        lb.delete()
    for b in box.all
        b.delete()
    if not na(tbl)
        tbl.delete()
 
    bool tpOn = showTp
    int  k    = tpOn ? 1 : 0          // extra key-figure row when TP is on
 
    tbl := table.new(tablePos, 7, nOrders + 6 + k, bgcolor = color.new(chart.bg_color, 10),
         border_color = color.new(chart.fg_color, 80), border_width = 1, frame_color = color.new(chart.fg_color, 60), frame_width = 1)
 
    float top   = math.max(topIn, botIn)
    float bot   = math.min(topIn, botIn)
    float sl    = slIn
    float price = livePrice
    bool isLong  = sl < bot
    bool isShort = sl > top
 
    // Pine can only draw up to 500 bars into the future
    int x1 = math.min(bar_index + offBars, bar_index + 499)
    int x2 = math.min(x1 + widthBars, bar_index + 500)
 
    if nChecked != 1
        string ticked = (useUsd ? "\n  ☑ Total size ($)" : "") + (usePct ? "\n  ☑ Risk (% of equity)" : "") + (useRisk ? "\n  ☑ Risk ($)" : "")
        label.new(bar_index, price, "⚠ Scaled position calculator\n" +
             (nChecked == 0 ? "No sizing method ticked." : "More than one sizing method ticked:" + ticked) +
             "\n\nTick only ONE in ⚙ Settings → Position.",
             style = label.style_label_left, color = colSl, textcolor = color.white, size = size.normal)
    else if topIn <= 0 or botIn <= 0 or slIn <= 0
        label.new(bar_index, price, str.format("⚠ Scaled position calculator\nA level is not set (value 0)\nRemove and re-add the indicator, or set it in the settings.\n\nTop: {0}\nBottom: {1}\nSL: {2}", fPrice(topIn), fPrice(botIn), fPrice(slIn)),
             style = label.style_label_left, color = colSl, textcolor = color.white, size = size.normal)
    else if not (isLong or isShort)
        label.new(bar_index, price, str.format("⚠ Scaled position calculator\nThe SL must be outside the range\n(below the bottom = Long, above the top = Short)\n\nTop: {0}\nBottom: {1}\nSL: {2}", fPrice(top), fPrice(bot), fPrice(sl)),
             style = label.style_label_left, color = colSl, textcolor = color.white, size = size.normal)
    else
        float step     = nOrders > 1 ? (top - bot) / (nOrders - 1) : 0.0
        float farEntry = isLong ? top : bot
 
        // Loss at SL per 1 $ of position (loss is linear in total size)
        float lossPerUsd = 0.0
        for i = 0 to nOrders - 1
            float lp = nOrders == 1 ? farEntry : (isLong ? top - i * step : bot + i * step)
            float fp = isLong ? math.min(lp, price) : math.max(lp, price)
            lossPerUsd += (1.0 / nOrders) / lp * math.abs(fp - sl)
 
        float riskTarget = sizeMode == M_PCT ? equityUsd * riskPctIn / 100 : riskUsdIn
        float posUsd     = sizeMode == M_USD ? totalUsd : (lossPerUsd > 0 ? riskTarget / lossPerUsd : 0.0)
        float usdOrder   = posUsd / nOrders
 
        float sumQty  = 0.0
        float sumCost = 0.0
        float sumLoss = 0.0
        int   nMkt    = 0
 
        int rHdr = 3 + k             // column header row
        int r0   = 4 + k             // first order row
 
        // Order range (neutral)
        box.new(x1, top, x2, bot, bgcolor = colRange, border_color = na, border_width = 0)
 
        if showTable
            cell(0, rHdr, "#")
            cell(1, rHdr, "Limit")
            cell(2, rHdr, "Type")
            cell(3, rHdr, "Fill")
            cell(4, rHdr, "Qty")
            cell(5, rHdr, "$")
            cell(6, rHdr, "SL loss")
 
        for i = 0 to nOrders - 1
            // Order 1 = farthest from the SL
            float limitPx = nOrders == 1 ? farEntry : (isLong ? top - i * step : bot + i * step)
            bool  isMkt   = isLong ? limitPx > price : limitPx < price
            float fill    = isLong ? math.min(limitPx, price) : math.max(limitPx, price)
            float qty     = usdOrder / limitPx
            float loss    = qty * math.abs(fill - sl)
 
            sumQty  += qty
            sumCost += qty * fill
            sumLoss += loss
            nMkt    += isMkt ? 1 : 0
 
            color c = isMkt ? colMkt : (isLong ? colLmtBuy : colLmtSel)
            string tipo = isMkt ? "MKT" : "LMT"
            line.new(x1, limitPx, x2, limitPx, color = c, width = wOrder)
            label.new(x2, limitPx, str.format("#{0} {1} {2} → {3} | qty {4}", i + 1, fPrice(limitPx), tipo, fPrice(fill), fQty(qty)),
                 style = label.style_label_left, color = c, textcolor = color.new(color.white, color.t(c)), size = lblSize)
 
            if showTable
                int r = r0 + i
                cell(0, r, str.tostring(i + 1))
                cell(1, r, fPrice(limitPx))
                cell(2, r, tipo, color.white, color.new(c, 30))
                cell(3, r, fPrice(fill))
                cell(4, r, fQty(qty))
                cell(5, r, fUsd(usdOrder))
                cell(6, r, fUsd(loss), colSl)
 
        float avgPx   = sumCost / sumQty
        float riskPct = equityUsd > 0 ? sumLoss / equityUsd * 100 : na
        string riskPctS = na(riskPct) ? "—" : str.tostring(riskPct, "#.##") + " %"
 
        // ── Take profit (assumes all orders filled, same as the SL loss) ──
        float tp = tpOn and tpIn > 0 ? tpIn : na
        bool  tpValid  = not na(tp) and (isLong ? tp > avgPx : tp < avgPx)
        float profit   = tpValid ? sumQty * math.abs(tp - avgPx) : na
        float rr       = tpValid and sumLoss > 0 ? profit / sumLoss : na
        float profPct  = tpValid and equityUsd > 0 ? profit / equityUsd * 100 : na
 
        // Risk zone: from average entry to SL (like TV's Long/Short Position tool)
        box.new(x1, math.max(avgPx, sl), x2, math.min(avgPx, sl),
             bgcolor = colRisk, border_color = na, border_width = 0)
 
        // Reward zone + TP line
        if tpValid
            box.new(x1, math.max(avgPx, tp), x2, math.min(avgPx, tp),
                 bgcolor = colReward, border_color = na, border_width = 0)
            line.new(x1, tp, x2, tp, color = colTp, width = wSl)
            label.new(x2, tp, str.format("TP {0} | profit {1} ({2} %) | RR {3}", fPrice(tp), fUsd(profit), str.tostring(profPct, "#.##"), str.tostring(rr, "#.##")),
                 style = label.style_label_left, color = colTp, textcolor = color.new(color.white, color.t(colTp)), size = lblSize)
 
        // SL line
        line.new(x1, sl, x2, sl, color = colSl, width = wSl)
        label.new(x2, sl, str.format("SL {0} | loss {1} ({2})", fPrice(sl), fUsd(sumLoss), riskPctS),
             style = label.style_label_left, color = colSl, textcolor = color.new(color.white, color.t(colSl)), size = lblSize)
 
        // Average entry line
        line.new(x1, avgPx, x2, avgPx, color = colAvg, style = line.style_dashed, width = wAvg)
        label.new(x2, avgPx, "Avg " + fPrice(avgPx), style = label.style_label_left,
             color = colAvg, textcolor = color.new(color.black, color.t(colAvg)), size = lblSize)
 
        if showTable
            string dir = isLong ? "LONG" : "SHORT"
            wideRow(0, str.format("{0} · price {1} · {2} MKT / {3} LMT", dir, fPrice(price), nMkt, nOrders - nMkt),
                 color.white, isLong ? color.new(#089981, 20) : color.new(#F23645, 20))
 
            // ── Key figures (top, larger + bold) ──
            wideRow(1, str.format("RISK  {0}  ·  {1}", fUsd(sumLoss), riskPctS),
                 color.white, color.new(#F23645, 15), kpiSize, true)
            if tpOn
                string tpTxt = tpValid ?
                     str.format("REWARD  {0}  ·  RR  1 : {1}", fUsd(profit), str.tostring(rr, "#.##")) :
                     (tpIn <= 0 ? "TP not set (⚙ → Levels → Take profit)" : "⚠ TP on the wrong side of the average entry")
                wideRow(2, tpTxt, color.white, color.new(#00838F, 15), kpiSize, true)
            wideRow(2 + k, str.format("SIZE  {0}  ·  LOT  {1}\nAVG ENTRY  {2}", fUsd(posUsd), fQty(sumQty), fPrice(avgPx)),
                 color.white, color.new(#2962FF, 35), kpiSize, true)
 
            // ── Totals row ──
            int rt = r0 + nOrders
            cell(0, rt, "Total")
            cell(1, rt, "")
            cell(2, rt, str.format("{0}/{1}", nMkt, nOrders - nMkt))
            cell(3, rt, fPrice(avgPx))
            cell(4, rt, fQty(sumQty))
            cell(5, rt, fUsd(posUsd))
            cell(6, rt, fUsd(sumLoss), colSl)
 
            // ── Secondary info (bottom, muted) ──
            string lev   = equityUsd > 0 ? str.tostring(posUsd / equityUsd, "#.##") + "x" : "—"
            string tpInf = tpValid ? " · TP " + fPrice(tp) : ""
            wideRow(rt + 1, str.format("{0} · Lev. {1} · Equity {2}\nTop {3} · Bottom {4} · SL {5}{6} · N {7} · ⚙ to edit",
                 sizeMode, lev, fUsd(equityUsd), fPrice(top), fPrice(bot), fPrice(sl), tpInf, nOrders),
                 color.new(chart.fg_color, 30))

← 返回列表