WaveMaster DCA Geometric Grid v2.7

WaveMaster777 · study · 729 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  WaveMaster DCA Geometric Grid v2.7
//  Two-anchor DCA ladder (Start → Fall), long or short.
//  v1.1: anchors may be placed in the FUTURE (empty area) — e.g. projected
//        Elliott wave targets; all objects drawn by time (xloc.bar_time).
//  v1.2: 3rd anchor TOP = ultimate reversal target (e.g. wave 5 / C top):
//        exit target, Profit @ Top and R:R per fill scenario.
//  v1.3: Take Profit modes — Top (single) / Risk-Based ladder (1:1, 1:2, 1:3,
//        1:5, Top with % per take) / Reversed DCA (exit grid mirrored above
//        the average up to Top) / Avg + %. Takes table, hit tracking, alerts.
//  v1.4: average labels centred on their lines; Avg-now label built from
//        hideable metrics (size, PnL, PnL %, % of position + optional ones);
//        tooltip on every input; opaque label text with optional backdrop.
//  v1.5: one consistent profit base for takes AND Top (selectable: Auto =
//        current position → plan, or Full Grid plan); Top label shows both
//        'now' and 'all filled' profit / R:R; takes above Top flagged.
//  v1.6: optional Early reversal takes — partial takes on the path Avg → Top
//        (25/50/75% by default) for a reversal before the grid is filled.
//  v1.7: configurable label sides — Entry/Adds left, Takes right (default);
//        Stop and Top side selectable too.
//  v1.8: Normal text size by default (labels and tables set separately);
//        Avg (all) label shows only the average price.
//  v1.9: each Entry / Add label shows the order quantity (#) next to its $.
//  v2.0: Avg (all) label shows the total position ($ and #); each level label
//        shows expected PnL when that order fills and PnL at Top from there.
//  v2.1: Grid table hidden by default; Small text by default.
//  v2.2: Risk-Based Ladder R-multiples are enterable per take (e.g. 0.5, 1.5).
//  v2.3: renamed "WaveMaster DCA Geometric Grid"; takes table uses the take
//        colour (opaque text, tinted row when reached) instead of red.
//  v2.4: cumulative PnL at each entry (position PnL at the moment that order
//        fills) — rows in the Summary table and a column in the Grid table.
//  v2.5: tables switched — Summary / entries on the left, Takes on the right.
//  v2.6: Summary table top right; Grid and Takes tables hidden by default.
//  v2.7: grid Direction — Auto / Long / Short. Auto: Top above Fall = Long,
//        Top below Fall = Short (falls back to Start vs Fall if Top is unset).
//        Short grid: entry at Start, adds UP to Fall, stop above Fall,
//        takes DOWN toward Top; all PnL / R:R / fills mirrored.
//  • Grid types: Geometric (default — distance AND volume grow down) / Even
//  • Aggressiveness K = (Start − AvgPrice) / (Start − Fall)
//      K = 50% → volume centre in the middle of the grid; K > 50% → volume
//      shifted down. Can be set as a TARGET (volume multiplier auto-solved).
//  • Total Risk TR = Deposit × MaxRisk%. Risk-Based sizing scales the grid so
//    that the loss at Stop (all orders filled) equals TR (capped by Deposit).
//  • AvgPrice = (V1·P1 + … + Vn·Pn) / (V1 + … + Vn), V = quantity per order
//  • Add-ons (доборы): Trading ≤ 4, Investing ≤ 10, default 5
// ═══════════════════════════════════════════════════════════════════════════
indicator("WaveMaster DCA Geometric Grid v2.7", overlay = true, max_lines_count = 100, max_labels_count = 100)
 
// ─── Anchors ────────────────────────────────────────────────────────────────
const string GA = "Anchors"
tStart   = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Start", confirm = true, inline = "s", group = GA)
pStartIn = input.price(0.0, "", confirm = true, inline = "s", group = GA,
     tooltip = "Start anchor: top of the grid, where the first (entry) order sits. Click a point on the chart — it may be in the future.")
tFall    = input.time(timestamp("01 Feb 2026 00:00 +0000"), "Fall", confirm = true, inline = "f", group = GA)
pFallIn  = input.price(0.0, "", confirm = true, inline = "f", group = GA,
     tooltip = "Fall anchor: the adverse extreme where the last add-on sits — below Start for Long (e.g. end of wave 4 / C), above Start for Short.")
tTop     = input.time(timestamp("01 Apr 2026 00:00 +0000"), "Top", confirm = true, inline = "t", group = GA)
pTopIn   = input.price(0.0, "", confirm = true, inline = "t", group = GA,
     tooltip = "Top anchor: ultimate reversal target after the Fall (e.g. end of wave 5 / C). Used for take profits, Profit @ Top and R:R. Always the clicked price.")
dirIn    = input.string("Auto", "Direction", options = ["Auto", "Long", "Short"], group = GA,
     tooltip = "Auto: Long if the Top anchor is above Fall, Short if Top is below Fall (if Top is not set: Long when Start is above Fall).\nLong: buy the dip — adds go DOWN from Start to Fall, takes go UP.\nShort: sell the rally — adds go UP from Start to Fall (the adverse extreme), stop above Fall, takes go DOWN toward Top.")
srcMode  = input.string("Clicked Price", "Anchor Price", options = ["Clicked Price", "Candle: Start Close / Extreme to Fall"], group = GA,
     tooltip = "Clicked Price: exact prices you clicked.\nCandle: Start = close of the Start candle, Fall = lowest low (Long) or highest high (Short) between the anchors. Anchors in the future always use the clicked price.")
 
// ─── Capital & Risk ─────────────────────────────────────────────────────────
const string GC = "Capital & Risk"
deposit    = input.float(10000.0, "Initial Sum (Deposit)", minval = 0.0, step = 100.0, group = GC,
     tooltip = "Total account capital available for this idea.")
maxRiskPct = input.float(10.0, "Max Risk %", minval = 0.1, maxval = 100.0, step = 0.5, group = GC,
     tooltip = "Maximum share of the Deposit you accept to lose. Total Risk TR = Deposit × Max Risk %.")
sizing     = input.string("Risk-Based", "Sizing", options = ["Risk-Based", "Full Deposit"], group = GC,
     tooltip = "Risk-Based: grid capital is chosen so that the loss at Stop with ALL orders filled = TR (never more than Deposit).\nFull Deposit: the whole Deposit is spread over the grid; loss at Stop is compared with TR.")
stopPct    = input.float(2.0, "Stop beyond Fall %", minval = 0.0, step = 0.5, group = GC,
     tooltip = "Stop-loss distance beyond the Fall anchor (below it for Long, above it for Short), in % of the Fall price.")
 
// ─── Take Profit ────────────────────────────────────────────────────────────
const string GTP = "Take Profit"
tpMode   = input.string("Risk-Based Ladder", "Mode", options = ["Top (single)", "Risk-Based Ladder", "Reversed DCA", "Avg + %"], group = GTP,
     tooltip = "Top (single): whole position closed at the Top anchor.\nRisk-Based Ladder: partial takes at R-multiples of the risk (Avg − Stop) plus Top.\nReversed DCA: exit grid mirrored above the average — starts once price is above Avg and sells more the higher it goes, up to Top.\nAvg + %: single classic take above the average.\nAll takes are measured from the CURRENT average (planned full-grid average until the first fill).")
tpBase   = input.string("Auto (position → plan)", "Profit Base", options = ["Auto (position → plan)", "Full Grid (plan)"], group = GTP,
     tooltip = "Base for take prices, take profits, Top profit and R:R.\nAuto: the CURRENT filled position (its average and its risk to Stop); the full planned grid until the first fill. Takes move as new orders fill.\nFull Grid (plan): always the planned full grid (all orders filled, risk = loss at Stop). Takes stay fixed.")
tpK1     = input.float(1.0, "Take 1 · R / close %", minval = 0.1, step = 0.1, inline = "k1", group = GTP)
tpR1     = input.float(20.0, "", minval = 0.0, maxval = 100.0, inline = "k1", group = GTP,
     tooltip = "Risk-Based Ladder take 1: R-multiple (profit ÷ risk; 0.5 = half the risk, 1 = 1:1, 1.5 = 1:1.5 …) and the share of the position closed there. Price = Avg + R × (Avg − Stop). Share 0 = off.")
tpK2     = input.float(2.0, "Take 2 · R / close %", minval = 0.1, step = 0.1, inline = "k2", group = GTP)
tpR2     = input.float(20.0, "", minval = 0.0, maxval = 100.0, inline = "k2", group = GTP,
     tooltip = "Risk-Based Ladder take 2: R-multiple and close %.")
tpK3     = input.float(3.0, "Take 3 · R / close %", minval = 0.1, step = 0.1, inline = "k3", group = GTP)
tpR3     = input.float(20.0, "", minval = 0.0, maxval = 100.0, inline = "k3", group = GTP,
     tooltip = "Risk-Based Ladder take 3: R-multiple and close %.")
tpK4     = input.float(5.0, "Take 4 · R / close %", minval = 0.1, step = 0.1, inline = "k4", group = GTP)
tpR5     = input.float(20.0, "", minval = 0.0, maxval = 100.0, inline = "k4", group = GTP,
     tooltip = "Risk-Based Ladder take 4: R-multiple and close %.")
tpRTop   = input.float(20.0, "Top %", minval = 0.0, maxval = 100.0, inline = "r3", group = GTP,
     tooltip = "Risk-Based Ladder: share closed at the Top anchor. All ladder shares are normalised to 100% if they don't add up.")
rdOffset = input.float(3.0, "Reversed DCA: 1st take beyond Avg %", minval = 0.0, step = 0.5, group = GTP,
     tooltip = "Reversed DCA: first take sits this % above the current average; the last take is at Top.")
rdTakes  = input.int(5, "Reversed DCA: takes", minval = 2, maxval = 10, group = GTP,
     tooltip = "Reversed DCA: number of exit orders between the first take and Top.")
rdMult   = input.float(1.3, "Reversed DCA: volume multiplier (up)", minval = 0.5, maxval = 3.0, step = 0.05, group = GTP,
     tooltip = "Reversed DCA: > 1 → each higher take sells more (mirror of the geometric entry). Distance growth uses the grid's Distance Multiplier.")
erOn     = input.bool(false, "Early reversal takes", group = GTP,
     tooltip = "Adds partial takes between the base average and Top, so profit is locked in if the market reverses up before the lower add-ons fill. The main takes share the rest of the position.")
erOnlyPart = input.bool(true, "Only while grid is partially filled", group = GTP,
     tooltip = "On: early takes appear only while some orders are still unfilled (a real early reversal). Off: always shown.")
erL1     = input.float(25.0, "ER1: % of path Avg → Top", minval = 1.0, maxval = 99.0, step = 1.0, group = GTP,
     tooltip = "Price of early take 1 = Avg + this % of the distance from Avg to Top.")
erS1     = input.float(15.0, "ER1: close % of position", minval = 0.0, maxval = 100.0, step = 1.0, group = GTP,
     tooltip = "Share of the position closed at early take 1 (0 = off).")
erL2     = input.float(50.0, "ER2: % of path Avg → Top", minval = 1.0, maxval = 99.0, step = 1.0, group = GTP,
     tooltip = "Price of early take 2 = Avg + this % of the distance from Avg to Top.")
erS2     = input.float(15.0, "ER2: close % of position", minval = 0.0, maxval = 100.0, step = 1.0, group = GTP,
     tooltip = "Share of the position closed at early take 2 (0 = off).")
erL3     = input.float(75.0, "ER3: % of path Avg → Top", minval = 1.0, maxval = 99.0, step = 1.0, group = GTP,
     tooltip = "Price of early take 3 = Avg + this % of the distance from Avg to Top.")
erS3     = input.float(15.0, "ER3: close % of position", minval = 0.0, maxval = 100.0, step = 1.0, group = GTP,
     tooltip = "Share of the position closed at early take 3 (0 = off). Early shares are taken first; if they total ≥ 100% they are normalised and the main takes get nothing.")
tpPct    = input.float(3.0, "Avg ± %: take beyond Avg %", minval = 0.0, step = 0.5, group = GTP,
     tooltip = "Avg + % mode (and fallback when Top is not usable): single take this % above the current average.")
 
// ─── Grid ───────────────────────────────────────────────────────────────────
const string GG = "Grid"
style     = input.string("Investing", "Style", options = ["Trading", "Investing"], group = GG,
     tooltip = "Trading: max 4 add-ons. Investing: max 10.")
addsIn    = input.int(5, "Add-ons (доборы)", minval = 1, maxval = 10, group = GG,
     tooltip = "Number of add-on orders below the entry. Total orders = 1 + add-ons. Capped at 4 in Trading style.")
gridType  = input.string("Geometric", "Grid Type", options = ["Geometric", "Even"], group = GG,
     tooltip = "Geometric: step distance grows × Distance Multiplier and volume grows down the grid.\nEven: equal steps, equal amounts.")
distMult  = input.float(1.3, "Distance Multiplier", minval = 1.0, maxval = 3.0, step = 0.05, group = GG,
     tooltip = "Geometric grid: each step down is this many times wider than the previous one. 1.0 = equal steps.")
volMode   = input.string("Target Aggressiveness", "Volume Mode", options = ["Target Aggressiveness", "Volume Multiplier"], group = GG,
     tooltip = "Target Aggressiveness: you set K, the volume multiplier is solved automatically.\nVolume Multiplier: you set the multiplier, K is shown as a result.")
aggTarget = input.float(65.0, "Aggressiveness Target %", minval = 20.0, maxval = 95.0, step = 1.0, group = GG,
     tooltip = "K = (Start − Avg) / (Start − Fall): where the full-grid average sits. 0% = Start, 100% = Fall, ~50% = neutral; higher = more volume at the bottom.")
volMult   = input.float(1.5, "Volume Multiplier", minval = 0.5, maxval = 5.0, step = 0.05, group = GG,
     tooltip = "Volume Multiplier mode: each order's $ amount = previous × this value.")
 
// ─── Visuals ────────────────────────────────────────────────────────────────
const string GV = "Visuals"
showLevels = input.bool(true, "Levels", inline = "v1", group = GV)
showLabels = input.bool(true, "Labels", inline = "v1", group = GV,
     tooltip = "Levels: grid order lines. Labels: text labels on all lines.")
showAvg    = input.bool(true, "Avg (full)", inline = "v2", group = GV)
showCur    = input.bool(true, "Avg (now)", inline = "v2", group = GV,
     tooltip = "Avg (full): average if every order fills. Avg (now): average of the orders filled so far.")
showTP     = input.bool(true, "Takes", inline = "v3", group = GV)
showStop   = input.bool(true, "Stop", inline = "v3", group = GV)
showTop    = input.bool(true, "Top", inline = "v3", group = GV,
     tooltip = "Take-profit lines, Stop line and Top line with the wave path.")
showQty    = input.bool(true, "Quantity (#) on levels", group = GV,
     tooltip = "Show the order size in units (shares / coins) next to the $ amount on each Entry / Add label.")
qtyFmt     = input.string("#,##0.####", "Quantity format", options = ["#,##0", "#,##0.##", "#,##0.####", "#,##0.########"], group = GV,
     tooltip = "Decimal places for quantities: whole shares for stocks, 4–8 decimals for crypto.")
lvPnlFill  = input.bool(true, "Level PnL @ fill", group = GV,
     tooltip = "On each Entry / Add label: expected unrealized PnL of the whole position at the moment that order fills (all orders above it already filled), in $ and %.")
lvPnlTop   = input.bool(true, "Level PnL @ Top", group = GV,
     tooltip = "On each Entry / Add label: profit if price reverses from that level (position = orders down to it) and reaches the Top anchor.")
labelShift = input.int(10, "Label Shift (bars)", minval = 0, maxval = 200, group = GV,
     tooltip = "How far (in bars) lines extend past the last candle / furthest anchor; side labels sit at that point.")
colFilled  = input.color(color.new(#26a69a, 0), "Filled", inline = "c1", group = GV)
colPending = input.color(color.new(#b2b5be, 0), "Pending", inline = "c1", group = GV,
     tooltip = "Colours of filled and pending grid levels.")
colAvg     = input.color(color.new(#ff9800, 0), "Avg", inline = "c2", group = GV)
colCur     = input.color(color.new(#ffeb3b, 0), "Avg now", inline = "c2", group = GV,
     tooltip = "Colours of the full-grid and current averages.")
colTP      = input.color(color.new(#00bcd4, 0), "TP", inline = "c3", group = GV)
colStop    = input.color(color.new(#f23645, 0), "Stop", inline = "c3", group = GV)
colTop     = input.color(color.new(#e040fb, 0), "Top", inline = "c3", group = GV,
     tooltip = "Colours of take profits, Stop and Top.")
lblSizeIn  = input.string("Small", "Label Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = GV,
     tooltip = "Text size of all line labels (levels, averages, takes, Stop, Top).")
tblSizeIn  = input.string("Small", "Table Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = GV,
     tooltip = "Text size of the Summary, Grid and Takes tables.")
lblTxtTr   = input.int(0, "Label Text Transparency", minval = 0, maxval = 90, group = GV,
     tooltip = "0 = fully opaque text (default).")
lblBg      = input.bool(true, "Label Backdrop", inline = "bg", group = GV)
lblBgTr    = input.int(35, "", minval = 0, maxval = 100, inline = "bg", group = GV,
     tooltip = "Dark backdrop behind label text for contrast; the number is its transparency (0 = solid).")
 
// ─── Label Sides ────────────────────────────────────────────────────────────
const string GS = "Label Sides"
lvlSide  = input.string("Left", "Entry / Adds", options = ["Left", "Right"], group = GS,
     tooltip = "Where Entry and Add labels sit: Left = at the start of the line (Start anchor), text ending at the line; Right = at the right end of the line.")
tkSide   = input.string("Right", "Takes", options = ["Left", "Right"], group = GS,
     tooltip = "Where take-profit labels (1:1 … Top, RD, ER, Avg+) sit.")
stopSide = input.string("Right", "Stop", options = ["Left", "Right"], group = GS,
     tooltip = "Where the Stop label sits.")
topSide  = input.string("Right", "Top", options = ["Left", "Right"], group = GS,
     tooltip = "Where the Top line label sits (Left = at the Fall anchor, where the Top line starts).")
 
// ─── Average Label ──────────────────────────────────────────────────────────
const string GL = "Average Label"
avgMid  = input.bool(true, "Average labels in the centre", group = GL,
     tooltip = "Place the Avg (now) and Avg (full) labels in the middle of their lines instead of at the right end.")
alSize  = input.bool(true,  "Position Size $", group = GL, tooltip = "$ invested in the filled orders.")
alPosP  = input.bool(true,  "% of Position Total", group = GL, tooltip = "Filled $ ÷ planned grid capital (how much of the full grid is already bought).")
alPnl   = input.bool(true,  "PnL $", group = GL, tooltip = "Unrealized profit/loss of the filled position at the current close, in $.")
alPnlP  = input.bool(true,  "PnL %", group = GL, tooltip = "Unrealized profit/loss in % of the filled position.")
alQty   = input.bool(false, "Quantity", group = GL, tooltip = "Units (shares / coins) held.")
alFill  = input.bool(false, "Filled n/N", group = GL, tooltip = "Filled orders out of the total number of grid orders.")
alDist  = input.bool(false, "Price vs Avg %", group = GL, tooltip = "Current close relative to the average price.")
alBE    = input.bool(false, "Bounce to BE %", group = GL, tooltip = "Rise needed from the current close to get back to break-even.")
alStop  = input.bool(false, "Loss @ Stop", group = GL, tooltip = "Loss of the current position if the Stop is hit.")
alTop   = input.bool(false, "Profit @ Top", group = GL, tooltip = "Profit of the current position if the Top anchor is reached.")
alRR    = input.bool(false, "R:R now", group = GL, tooltip = "Profit @ Top ÷ Loss @ Stop for the current position.")
alDep   = input.bool(false, "% of Deposit", group = GL, tooltip = "Position size ÷ Deposit.")
 
// ─── Tables ─────────────────────────────────────────────────────────────────
const string GT = "Tables"
showSum = input.bool(true, "Summary", inline = "t1", group = GT)
sumPos  = input.string("Top Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"], inline = "t1", group = GT,
     tooltip = "Summary table: capital, risk, aggressiveness, averages, fills, takes and Top metrics.")
sumCum  = input.bool(true, "Summary: Cum PnL per entry", group = GT,
     tooltip = "Adds one row per Entry / Add to the Summary table: price and the cumulative PnL of the whole position at the moment that order fills ($ and %). Filled entries are highlighted.")
showTab = input.bool(false, "Grid Table", inline = "t2", group = GT)
tabPos  = input.string("Bottom Left", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"], inline = "t2", group = GT,
     tooltip = "Per-level table: price, amount, weight, cumulative average, bounce to BE, PnL @ Top and R:R.")
showTk  = input.bool(false, "Takes Table", inline = "t3", group = GT)
tkPos   = input.string("Bottom Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"], inline = "t3", group = GT,
     tooltip = "Take-profit table: price, % above average, close %, quantity, profit and R per take.")
 
// ─── Helpers ────────────────────────────────────────────────────────────────
f_pos(string s) =>
    switch s
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        "Middle Right" => position.middle_right
        "Middle Left"  => position.middle_left
        => position.top_right
 
f_size(string s) =>
    switch s
        "Tiny"  => size.tiny
        "Small" => size.small
        "Large" => size.large
        => size.normal
lblSize = f_size(lblSizeIn)
tblSize = f_size(tblSizeIn)
 
// Level prices: cumulative geometric offsets from Start to Fall
f_prices(float p0, float pn, int n, float q) =>
    array<float> a = array.new<float>()
    float d = pn - p0
    for i = 0 to n
        float f = q == 1.0 ? float(i) / n : (math.pow(q, i) - 1.0) / (math.pow(q, n) - 1.0)
        a.push(p0 + d * f)
    a
 
// $-weights m^i, normalised to 1
f_weights(int n, float m) =>
    array<float> w = array.new<float>()
    float s = 0.0
    for i = 0 to n
        float v = math.pow(m, i)
        w.push(v)
        s += v
    for i = 0 to n
        w.set(i, w.get(i) / s)
    w
 
// Average price = Σ(Qty·P) / ΣQty = Σ$ / Σ($/P)
f_avg(array<float> p, array<float> w) =>
    float inv = 0.0
    for i = 0 to p.size() - 1
        inv += w.get(i) / p.get(i)
    1.0 / inv
 
// Solve the volume multiplier for a target aggressiveness (bisection in log space)
f_solveM(array<float> p, float p0, float pn, int n, float target) =>
    float lo = math.log(0.05)
    float hi = math.log(20.0)
    for _ = 0 to 50
        float mid = (lo + hi) / 2.0
        float k = (p0 - f_avg(p, f_weights(n, math.exp(mid)))) / (p0 - pn)
        if k < target
            lo := mid
        else
            hi := mid
    math.exp((lo + hi) / 2.0)
 
f_cell(table t, int c, int r, string s, color tc, color bg) =>
    t.cell(c, r, s, text_color = tc, bgcolor = bg, text_size = tblSize)
 
f_take(array<float> p, array<float> f, array<string> nm, float px, float fr, string s) =>
    if fr > 0 and not na(px)
        p.push(px)
        f.push(fr)
        nm.push(s)
 
f_money(float v) => "$" + str.tostring(v, "#,##0.00")
f_smoney(float v) => (v >= 0 ? "+$" : "−$") + str.tostring(math.abs(v), "#,##0.00")
f_pct(float v)   => str.tostring(v, "+0.00;-0.00") + "%"
 
// ─── Anchor capture ─────────────────────────────────────────────────────────
var float cStart     = na
var float lowBetween = na
var float highBetween = na
var int   startBar   = na
if na(startBar) and time >= tStart
    startBar := bar_index
    cStart   := close
if time >= tStart and time <= tFall
    lowBetween  := na(lowBetween) ? low : math.min(lowBetween, low)
    highBetween := na(highBetween) ? high : math.max(highBetween, high)
 
// Future anchors (no candles yet) always use the clicked price
bool  clicked = srcMode == "Clicked Price"
float p0      = clicked or na(cStart) ? pStartIn : cStart
float pTop    = pTopIn
// Direction: +1 = Long, −1 = Short. Auto decides by where Top sits relative to Fall.
int   dirNow  = dirIn == "Long" ? 1 : dirIn == "Short" ? -1 : pTop > 0 ? (pTop > pFallIn ? 1 : -1) : (p0 >= pFallIn ? 1 : -1)
float pn      = clicked or time < tFall ? pFallIn : dirNow > 0 ? lowBetween : highBetween
int   n       = style == "Trading" ? math.min(addsIn, 4) : addsIn
bool  capped  = style == "Trading" and addsIn > 4
bool  isGeo   = gridType == "Geometric"
float q       = isGeo ? distMult : 1.0
float TR      = deposit * maxRiskPct / 100.0
 
// ─── Build grid (once) ──────────────────────────────────────────────────────
var array<float> P   = array.new<float>()
var array<float> W   = array.new<float>()
var array<float> USD = array.new<float>()
var array<float> QTY = array.new<float>()
var bool  built    = false
var bool  valid    = false
var float mUsed    = na
var float avgFull  = na
var float kAch     = na
var float capital  = na
var float stopPx   = na
var float lossStop = na
var float qtyAll   = na
var float profTop  = na
var bool  topOk    = false
var int   dir      = 1          // grid direction fixed at build: +1 Long, −1 Short
 
bool ready = not na(p0) and not na(pn) and (clicked or time > tFall or barstate.islast)
if ready and not built
    built := true
    dir   := dirNow
    valid := pn > 0 and dir * (p0 - pn) > 0          // Long: Start above Fall; Short: Start below Fall
    if valid
        P       := f_prices(p0, pn, n, q)
        mUsed   := not isGeo ? 1.0 : volMode == "Target Aggressiveness" ? f_solveM(P, p0, pn, n, aggTarget / 100.0) : volMult
        W       := f_weights(n, mUsed)
        avgFull := f_avg(P, W)
        kAch    := (p0 - avgFull) / (p0 - pn)
        stopPx  := pn * (1.0 - dir * stopPct / 100.0)
        float qtyPerUsd = 1.0 / avgFull                       // Σ(w/P)
        float lossPerUsd = dir * (1.0 - stopPx * qtyPerUsd)   // loss per $1 of grid capital at Stop
        float riskCap = lossPerUsd > 0 ? TR / lossPerUsd : deposit
        capital  := sizing == "Risk-Based" ? math.min(riskCap, deposit) : deposit
        lossStop := capital * lossPerUsd
        for i = 0 to n
            float u = capital * W.get(i)
            USD.push(u)
            QTY.push(u / P.get(i))
        qtyAll  := capital / avgFull
        topOk   := pTop > 0 and dir * (pTop - pn) > 0
        profTop := topOk ? dir * (qtyAll * pTop - capital) : na
 
// ─── Fill tracking ──────────────────────────────────────────────────────────
var float minLow  = na
var float maxHigh = na
if time >= tStart
    minLow  := na(minLow) ? low : math.min(minLow, low)
    maxHigh := na(maxHigh) ? high : math.max(maxHigh, high)
// a level is filled once price has traded through it (down for Long, up for Short)
f_isFilled(float lvl) => dir > 0 ? minLow <= lvl : maxHigh >= lvl
 
int   filled = 0
float invUsd = 0.0
float invQty = 0.0
if valid and not na(minLow)
    for i = 0 to n
        if f_isFilled(P.get(i))
            filled += 1
            invUsd += USD.get(i)
            invQty += QTY.get(i)
float curAvg = invQty > 0 ? invUsd / invQty : na
float profTopNow = invQty > 0 and topOk ? dir * (invQty * pTop - invUsd) : na
float pnl    = invQty > 0 ? dir * (invQty * close - invUsd) : na
 
// ─── Take Profit ladder ─────────────────────────────────────────────────────
// Base = current position (filled orders) or the planned full grid before the first fill
array<float>  TKP = array.new<float>()
array<float>  TKF = array.new<float>()
array<string> TKN = array.new<string>()
float baseAvg = na
float baseQty = na
float rUnit   = na
if valid
    bool usePlan = tpBase == "Full Grid (plan)" or na(curAvg)
    baseAvg := usePlan ? avgFull : curAvg
    baseQty := usePlan ? qtyAll : invQty
    rUnit   := dir * (baseAvg - stopPx)                  // risk per unit, always positive
    switch tpMode
        "Top (single)" =>
            if topOk
                f_take(TKP, TKF, TKN, pTop, 1.0, "Top")
        "Risk-Based Ladder" =>
            float sPct = tpR1 + tpR2 + tpR3 + tpR5 + (topOk ? tpRTop : 0.0)
            if sPct > 0
                f_take(TKP, TKF, TKN, baseAvg + dir * tpK1 * rUnit, tpR1 / sPct, "1:" + str.tostring(tpK1, "0.##"))
                f_take(TKP, TKF, TKN, baseAvg + dir * tpK2 * rUnit, tpR2 / sPct, "1:" + str.tostring(tpK2, "0.##"))
                f_take(TKP, TKF, TKN, baseAvg + dir * tpK3 * rUnit, tpR3 / sPct, "1:" + str.tostring(tpK3, "0.##"))
                f_take(TKP, TKF, TKN, baseAvg + dir * tpK4 * rUnit, tpR5 / sPct, "1:" + str.tostring(tpK4, "0.##"))
                if topOk
                    f_take(TKP, TKF, TKN, pTop, tpRTop / sPct, "Top")
        "Reversed DCA" =>
            float s0 = baseAvg * (1.0 + dir * rdOffset / 100.0)
            if topOk and dir * (pTop - s0) > 0
                int k = rdTakes - 1
                array<float> rp = f_prices(s0, pTop, k, q)
                array<float> rw = f_weights(k, rdMult)
                for i = 0 to k
                    f_take(TKP, TKF, TKN, rp.get(i), rw.get(i), "RD" + str.tostring(i + 1))
    if TKP.size() == 0      // Avg + % mode, or fallback when Top is not usable
        f_take(TKP, TKF, TKN, baseAvg * (1.0 + dir * tpPct / 100.0), 1.0, "Avg" + (dir > 0 ? "+" : "−") + str.tostring(tpPct, "0.#") + "%")
 
    // Early reversal takes: partial takes on the path Avg → Top, taken before the main takes
    bool erActive = erOn and topOk and dir * (pTop - baseAvg) > 0 and (not erOnlyPart or filled < n + 1)
    float erSum = erS1 + erS2 + erS3
    if erActive and erSum > 0
        float eScale = erSum >= 100.0 ? 100.0 / erSum : 1.0       // normalise if early shares ≥ 100%
        float mainShare = math.max(0.0, 1.0 - erSum * eScale / 100.0)
        for i = 0 to TKF.size() - 1
            TKF.set(i, TKF.get(i) * mainShare)
        float dist = pTop - baseAvg
        // unshift in reverse so the order is ER1, ER2, ER3, then the main takes
        array<float>  eP = array.from(baseAvg + dist * erL3 / 100.0, baseAvg + dist * erL2 / 100.0, baseAvg + dist * erL1 / 100.0)
        array<float>  eS = array.from(erS3, erS2, erS1)
        array<string> eN = array.from("ER3", "ER2", "ER1")
        for i = 0 to 2
            if eS.get(i) > 0
                TKP.unshift(eP.get(i))
                TKF.unshift(eS.get(i) * eScale / 100.0)
                TKN.unshift(eN.get(i))
        // drop main takes whose share became 0
        for i = TKF.size() - 1 to 0
            if TKF.get(i) <= 0
                TKP.remove(i)
                TKF.remove(i)
                TKN.remove(i)
 
float exitAvg = 0.0
if TKP.size() > 0
    for i = 0 to TKP.size() - 1
        exitAvg += TKF.get(i) * TKP.get(i)
float profTakes = TKP.size() > 0 ? dir * baseQty * (exitAvg - baseAvg) : na
float baseRisk  = valid ? baseQty * rUnit : na                       // $ loss at Stop for the base
float baseTop   = valid and topOk ? dir * baseQty * (pTop - baseAvg) : na  // $ profit at Top for the base
bool  baseIsNow = valid and tpBase != "Full Grid (plan)" and not na(curAvg)
 
// Hit tracking: highest high since the last fill
var int   lastFilled = 0
var float hiSince    = na      // favourable extreme since the last fill: highest high (Long) / lowest low (Short)
if filled != lastFilled
    hiSince    := na
    lastFilled := filled
else if filled > 0
    hiSince := na(hiSince) ? (dir > 0 ? high : low) : dir > 0 ? math.max(hiSince, high) : math.min(hiSince, low)
f_hit(float px) => not na(hiSince) and dir * (hiSince - px) >= 0
int hits = 0
if TKP.size() > 0
    for i = 0 to TKP.size() - 1
        if f_hit(TKP.get(i))
            hits += 1
var int prevHits = 0
if filled > 0 and hits > prevHits
    alert("WM DCA: " + syminfo.ticker + " take " + str.tostring(hits) + "/" + str.tostring(TKP.size()) + " reached · avg " + str.tostring(baseAvg, format.mintick), alert.freq_once_per_bar)
prevHits := hits
 
// ─── Alerts ─────────────────────────────────────────────────────────────────
var int prevFilled = 0
if valid and filled > prevFilled and prevFilled > 0
    alert("WM DCA: " + syminfo.ticker + " order " + str.tostring(filled) + "/" + str.tostring(n + 1) + " filled @ " + str.tostring(P.get(filled - 1), format.mintick) + " · new avg " + str.tostring(curAvg, format.mintick), alert.freq_once_per_bar)
prevFilled := filled
bool stopDn  = ta.crossunder(low, stopPx)
bool stopUp  = ta.crossover(high, stopPx)
bool topUp   = ta.crossover(high, topOk ? pTop : na)
bool topDn   = ta.crossunder(low, topOk ? pTop : na)
bool stopHit = dir > 0 ? stopDn : stopUp
bool topHit  = dir > 0 ? topUp : topDn
if topHit
    alert("WM DCA: " + syminfo.ticker + " ultimate TOP target reached @ " + str.tostring(pTop, format.mintick), alert.freq_once_per_bar)
if valid and stopHit
    alert("WM DCA: " + syminfo.ticker + " STOP hit @ " + str.tostring(stopPx, format.mintick), alert.freq_once_per_bar)
 
// ─── Drawing ────────────────────────────────────────────────────────────────
var array<line>  lns = array.new<line>()
var array<label> lbs = array.new<label>()
var table tSum = table.new(f_pos(sumPos), 2, 31, border_width = 1, frame_color = color.new(#787b86, 60), frame_width = 1)
var table tGrd = table.new(f_pos(tabPos), 12, 13, border_width = 1, frame_color = color.new(#787b86, 60), frame_width = 1)
var table tTk  = table.new(f_pos(tkPos), 7, 16, border_width = 1, frame_color = color.new(#787b86, 60), frame_width = 1)
 
// All objects are placed by TIME, so anchors can sit in the future (empty chart area)
f_lbl(int x, float y, string txt, color c, string st) =>
    lbs.push(label.new(x, y, txt, xloc.bar_time, yloc.price, lblBg ? color.new(#131722, lblBgTr) : color(na), st, color.new(c, lblTxtTr), lblSize, text.align_left))
 
f_line(int x1, int x2, float y, color c, string st, int w, string txt, string side) =>
    lns.push(line.new(x1, y, x2, y, xloc.bar_time, extend.none, c, st, w))
    if showLabels and txt != ""
        if side == "Left"
            f_lbl(x1, y, txt, c, label.style_label_right)     // text ends at the line start
        else
            f_lbl(x2, y, txt, c, label.style_label_left)      // text starts at the line end
 
// Average lines: label centred on the line (or at the right end)
f_lineMid(int x1, int x2, float y, color c, string st, int w, string txt) =>
    lns.push(line.new(x1, y, x2, y, xloc.bar_time, extend.none, c, st, w))
    if showLabels and txt != ""
        if avgMid
            f_lbl(int(math.round((x1 + x2) / 2.0)), y, txt, c, label.style_label_center)
        else
            f_lbl(x2, y, txt, c, label.style_label_left)
 
if barstate.islast
    for l in lns
        l.delete()
    lns.clear()
    for b in lbs
        b.delete()
    lbs.clear()
    tSum.clear(0, 0, 1, 30)
    tGrd.clear(0, 0, 11, 12)
    tTk.clear(0, 0, 6, 15)
 
    color hdrBg = color.new(#2a2e39, 0)
    color rowBg = color.new(#131722, 10)
    color txt   = color.new(#d1d4dc, 0)
 
    if built and not valid
        f_cell(tSum, 0, 0, "WM DCA Geometric Grid", txt, hdrBg)
        f_cell(tSum, 1, 0, dir > 0 ? "Long: Start must be above Fall" : "Short: Start must be below Fall", colStop, rowBg)
    else if valid
        int barMs = timeframe.in_seconds(timeframe.period) * 1000
        int x1    = tStart
        int x2    = math.max(time, tFall, topOk ? tTop : tFall) + labelShift * barMs
        // Anchors (work in the future too)
        lbs.push(label.new(tStart, p0, "Start", xloc.bar_time, yloc.price, color.new(#434651, 0), dir > 0 ? label.style_label_down : label.style_label_up, color.white, size.tiny))
        lbs.push(label.new(tFall, pn, "Fall", xloc.bar_time, yloc.price, color.new(#434651, 0), dir > 0 ? label.style_label_up : label.style_label_down, color.white, size.tiny))
        lns.push(line.new(tStart, p0, tFall, pn, xloc.bar_time, extend.none, color.new(colPending, 50), line.style_dotted, 1))
        if topOk and showTop
            lbs.push(label.new(tTop, pTop, "Top", xloc.bar_time, yloc.price, colTop, dir > 0 ? label.style_label_down : label.style_label_up, color.white, size.tiny))
            lns.push(line.new(tFall, pn, tTop, pTop, xloc.bar_time, extend.none, color.new(colTop, 40), line.style_dotted, 1))
            string tTopTxt = "Top  " + str.tostring(pTop, format.mintick)
            if baseIsNow
                tTopTxt += "\nnow  " + f_smoney(baseTop) + "  R:R " + (baseRisk > 0 ? str.tostring(baseTop / baseRisk, "0.00") : "—")
            tTopTxt += "\n" + (baseIsNow ? "all  " : "") + f_smoney(profTop) + "  R:R " + (lossStop > 0 ? str.tostring(profTop / lossStop, "0.00") : "—")
            f_line(tFall, x2, pTop, colTop, line.style_solid, 2, tTopTxt, topSide)
 
        // Levels
        if showLevels
            float lcu = 0.0     // cumulative $ down to this level
            float lcq = 0.0     // cumulative qty down to this level
            for i = 0 to n
                float px = P.get(i)
                bool  f  = f_isFilled(px)
                lcu += USD.get(i)
                lcq += QTY.get(i)
                string t = (i == 0 ? "Entry" : "Add " + str.tostring(i)) + "  " + str.tostring(px, format.mintick) + "  " + f_money(USD.get(i)) + (showQty ? "  " + str.tostring(QTY.get(i), qtyFmt) + " #" : "") + "  " + f_pct((px / p0 - 1.0) * 100.0)
                if lvPnlFill and i > 0
                    float pf = dir * (lcq * px - lcu)               // unrealized PnL of the position at this fill
                    t += "  ·  PnL " + f_smoney(pf) + " (" + f_pct(pf / lcu * 100.0) + ")"
                if lvPnlTop and topOk
                    t += "  ·  @Top " + f_smoney(dir * (lcq * pTop - lcu))
                f_line(x1, x2, px, f ? colFilled : colPending, f ? line.style_solid : line.style_dashed, i == 0 ? 2 : 1, t, lvlSide)
        if showAvg
            string tAll = "Avg (all)  " + str.tostring(avgFull, format.mintick) + "\nPosition " + f_money(capital) + "  ·  " + str.tostring(qtyAll, qtyFmt) + " #"
            if alDep
                tAll += "\n" + str.tostring(deposit > 0 ? capital / deposit * 100 : 0, "0.0") + "% of deposit"
            if alStop
                tAll += "\nLoss @ Stop " + f_smoney(-lossStop)
            if alTop and topOk
                tAll += "\nProfit @ Top " + f_smoney(profTop)
            if alRR and topOk and lossStop > 0
                tAll += "\nR:R " + str.tostring(profTop / lossStop, "0.00")
            f_lineMid(x1, x2, avgFull, colAvg, line.style_dotted, 2, tAll)
        if showCur and not na(curAvg)
            float lsNow = dir * (invUsd - invQty * stopPx)
            string tCur = "Avg now  " + str.tostring(curAvg, format.mintick)
            if alSize
                tCur += "\nSize " + f_money(invUsd)
            if alPosP
                tCur += "\n" + str.tostring(invUsd / capital * 100, "0.0") + "% of position total"
            if alPnl
                tCur += "\nPnL " + f_smoney(pnl)
            if alPnlP
                tCur += (alPnl ? "  (" : "\nPnL ") + f_pct(pnl / invUsd * 100.0) + (alPnl ? ")" : "")
            if alQty
                tCur += "\nQty " + str.tostring(invQty, qtyFmt)
            if alFill
                tCur += "\nFilled " + str.tostring(filled) + "/" + str.tostring(n + 1)
            if alDist
                tCur += "\nPrice vs Avg " + f_pct((close / curAvg - 1.0) * 100.0)
            if alBE
                tCur += "\n" + (dir > 0 ? "Bounce" : "Drop") + " to BE " + (dir * (curAvg - close) > 0 ? f_pct((curAvg / close - 1.0) * 100.0) : "in profit")
            if alStop
                tCur += "\nLoss @ Stop " + f_smoney(-lsNow)
            if alTop and not na(profTopNow)
                tCur += "\nProfit @ Top " + f_smoney(profTopNow)
            if alRR and not na(profTopNow) and lsNow > 0
                tCur += "\nR:R " + str.tostring(profTopNow / lsNow, "0.00")
            if alDep
                tCur += "\n" + str.tostring(deposit > 0 ? invUsd / deposit * 100 : 0, "0.0") + "% of deposit"
            f_lineMid(x1, x2, curAvg, colCur, line.style_solid, 2, tCur)
        if showTP and TKP.size() > 0
            for i = 0 to TKP.size() - 1
                string nm = TKN.get(i)
                if not (nm == "Top" and topOk and showTop)
                    float px  = TKP.get(i)
                    bool  hit = f_hit(px)
                    bool  over = topOk and dir * (px - pTop) > pTop * 0.0000001
                    f_line(x1, x2, px, over ? color.new(colTP, 40) : colTP, hit ? line.style_solid : line.style_dashed, 1, nm + (over ? " ↑Top" : "") + "  " + str.tostring(px, format.mintick) + "  " + str.tostring(TKF.get(i) * 100, "0.#") + "%  " + f_smoney(dir * TKF.get(i) * baseQty * (px - baseAvg)), tkSide)
        if showStop
            f_line(x1, x2, stopPx, colStop, line.style_solid, 1, "Stop  " + str.tostring(stopPx, format.mintick) + "  −" + f_money(lossStop), stopSide)
 
        // ── Summary table
        if showSum
            f_cell(tSum, 0, 0, "WM DCA Geometric Grid", txt, hdrBg)
            f_cell(tSum, 1, 0, (dir > 0 ? "LONG · " : "SHORT · ") + gridType + " · 1 + " + str.tostring(n) + " add-ons" + (capped ? " (Trading cap)" : ""), txt, hdrBg)
            f_cell(tSum, 0, 1, "Deposit", txt, rowBg)
            f_cell(tSum, 1, 1, f_money(deposit), txt, rowBg)
            f_cell(tSum, 0, 2, "Total Risk (TR)", txt, rowBg)
            f_cell(tSum, 1, 2, f_money(TR) + "  (" + str.tostring(maxRiskPct, "0.##") + "%)", txt, rowBg)
            f_cell(tSum, 0, 3, "Grid Capital", txt, rowBg)
            f_cell(tSum, 1, 3, f_money(capital) + "  (" + str.tostring(deposit > 0 ? capital / deposit * 100 : 0, "0.0") + "% dep)", txt, rowBg)
            f_cell(tSum, 0, 4, "Loss @ Stop", txt, rowBg)
            f_cell(tSum, 1, 4, f_money(lossStop) + (lossStop > TR * 1.0001 ? "  > TR!" : "  ≤ TR"), lossStop > TR * 1.0001 ? colStop : colFilled, rowBg)
            f_cell(tSum, 0, 5, "Distance × / Volume ×", txt, rowBg)
            f_cell(tSum, 1, 5, str.tostring(q, "0.00") + " / " + str.tostring(mUsed, "0.000"), txt, rowBg)
            f_cell(tSum, 0, 6, "Aggressiveness K", txt, rowBg)
            f_cell(tSum, 1, 6, str.tostring(kAch * 100, "0.0") + "%" + (isGeo and volMode == "Target Aggressiveness" ? "  (target " + str.tostring(aggTarget, "0") + "%)" : ""), colAvg, rowBg)
            f_cell(tSum, 0, 7, "Avg Price (all filled)", txt, rowBg)
            f_cell(tSum, 1, 7, str.tostring(avgFull, format.mintick) + "  " + f_pct((avgFull / p0 - 1.0) * 100.0), colAvg, rowBg)
            f_cell(tSum, 0, 8, "Start → Fall", txt, rowBg)
            f_cell(tSum, 1, 8, str.tostring(p0, format.mintick) + " → " + str.tostring(pn, format.mintick) + "  " + f_pct((pn / p0 - 1.0) * 100.0), txt, rowBg)
            f_cell(tSum, 0, 9, "Stop", txt, rowBg)
            f_cell(tSum, 1, 9, str.tostring(stopPx, format.mintick), colStop, rowBg)
            f_cell(tSum, 0, 10, "Filled", txt, rowBg)
            f_cell(tSum, 1, 10, str.tostring(filled) + " / " + str.tostring(n + 1) + "  ·  " + f_money(invUsd), txt, rowBg)
            f_cell(tSum, 0, 11, "Avg now", txt, rowBg)
            f_cell(tSum, 1, 11, na(curAvg) ? "—" : str.tostring(curAvg, format.mintick), colCur, rowBg)
            f_cell(tSum, 0, 12, "Unrealized PnL", txt, rowBg)
            f_cell(tSum, 1, 12, na(pnl) ? "—" : f_money(pnl) + "  " + f_pct(pnl / invUsd * 100.0), na(pnl) ? txt : pnl >= 0 ? colFilled : colStop, rowBg)
            f_cell(tSum, 0, 13, "Take Profit · " + tpMode + (baseIsNow ? " (position)" : " (plan)"), txt, rowBg)
            f_cell(tSum, 1, 13, na(profTakes) ? "—" : "exit avg " + str.tostring(exitAvg, format.mintick) + "  +" + f_money(profTakes) + "  (" + str.tostring(hits) + "/" + str.tostring(TKP.size()) + " hit)", colTP, rowBg)
            f_cell(tSum, 0, 14, "Top (ultimate)", txt, rowBg)
            f_cell(tSum, 1, 14, topOk ? str.tostring(pTop, format.mintick) + "  " + f_pct((pTop / pn - 1.0) * 100.0) + " from Fall" : (dir > 0 ? "set Top above Fall" : "set Top below Fall"), topOk ? colTop : colStop, rowBg)
            f_cell(tSum, 0, 15, "Profit @ Top (all filled)", txt, rowBg)
            f_cell(tSum, 1, 15, topOk ? f_money(profTop) + "  " + f_pct(profTop / capital * 100.0) : "—", colTop, rowBg)
            f_cell(tSum, 0, 16, "R:R (all filled)", txt, rowBg)
            f_cell(tSum, 1, 16, topOk and lossStop > 0 ? str.tostring(profTop / lossStop, "0.00") : "—", colTop, rowBg)
            float lsNowT = dir * (invUsd - invQty * stopPx)
            f_cell(tSum, 0, 17, "Profit @ Top / R:R (now)", txt, rowBg)
            f_cell(tSum, 1, 17, na(profTopNow) ? "—" : f_smoney(profTopNow) + "  " + f_pct(profTopNow / invUsd * 100.0) + "  R:R " + (lsNowT > 0 ? str.tostring(profTopNow / lsNowT, "0.00") : "—"), colTop, rowBg)
            // Cumulative PnL at each entry (position PnL when that order fills)
            if sumCum
                f_cell(tSum, 0, 18, "Cum PnL @ fill", txt, hdrBg)
                f_cell(tSum, 1, 18, "position at each entry", txt, hdrBg)
                float scu = 0.0
                float scq = 0.0
                for i = 0 to n
                    float px = P.get(i)
                    scu += USD.get(i)
                    scq += QTY.get(i)
                    float cp = dir * (scq * px - scu)
                    bool  fl = f_isFilled(px)
                    f_cell(tSum, 0, 19 + i, (i == 0 ? "Entry" : "Add " + str.tostring(i)) + "  " + str.tostring(px, format.mintick), fl ? colFilled : txt, rowBg)
                    f_cell(tSum, 1, 19 + i, i == 0 ? "0.00" : f_smoney(cp) + "  (" + f_pct(cp / scu * 100.0) + ")", i == 0 ? txt : colStop, fl ? color.new(colFilled, 85) : rowBg)
 
        // ── Grid table
        if showTab
            array<string> hdr = array.from("#", "Price", "Δ Start", "Amount", "Weight", "Qty", "Cum $", "Avg if filled", "Cum PnL @ fill", "Move to BE", "PnL @ Top", "R:R")
            for c = 0 to 11
                f_cell(tGrd, c, 0, hdr.get(c), txt, hdrBg)
            float cu = 0.0
            float cq = 0.0
            for i = 0 to n
                float px = P.get(i)
                cu += USD.get(i)
                cq += QTY.get(i)
                float ca = cu / cq
                bool  f  = f_isFilled(px)
                color tc = f ? colFilled : txt
                f_cell(tGrd, 0, i + 1, i == 0 ? "E" : str.tostring(i), tc, rowBg)
                f_cell(tGrd, 1, i + 1, str.tostring(px, format.mintick), tc, rowBg)
                f_cell(tGrd, 2, i + 1, f_pct((px / p0 - 1.0) * 100.0), tc, rowBg)
                f_cell(tGrd, 3, i + 1, f_money(USD.get(i)), tc, rowBg)
                f_cell(tGrd, 4, i + 1, str.tostring(W.get(i) * 100, "0.0") + "%", tc, rowBg)
                f_cell(tGrd, 5, i + 1, str.tostring(QTY.get(i), qtyFmt), tc, rowBg)
                f_cell(tGrd, 6, i + 1, f_money(cu), tc, rowBg)
                f_cell(tGrd, 7, i + 1, str.tostring(ca, format.mintick), tc, rowBg)
                float cPnl = dir * (cq * px - cu)                          // cumulative position PnL when this entry fills
                f_cell(tGrd, 8, i + 1, i == 0 ? "—" : f_smoney(cPnl) + " (" + f_pct(cPnl / cu * 100.0) + ")", i == 0 ? tc : colStop, rowBg)
                f_cell(tGrd, 9, i + 1, f_pct((ca / px - 1.0) * 100.0), tc, rowBg)
                float pT = dir * (cq * pTop - cu)
                float lS = dir * (cu - cq * stopPx)
                f_cell(tGrd, 10, i + 1, topOk ? f_money(pT) : "—", tc, rowBg)
                f_cell(tGrd, 11, i + 1, topOk and lS > 0 ? str.tostring(pT / lS, "0.00") : "—", tc, rowBg)
 
        // ── Takes table
        if showTk and TKP.size() > 0
            array<string> th = array.from("Take", "Price", "Δ Avg", "Close %", "Qty", "Profit", "R")
            for c = 0 to 6
                f_cell(tTk, c, 0, th.get(c), txt, hdrBg)
            for i = 0 to TKP.size() - 1
                float px  = TKP.get(i)
                bool  hit = f_hit(px)
                bool  over = topOk and dir * (px - pTop) > pTop * 0.0000001
                color tc  = colTP                                        // opaque take colour
                color tb  = hit ? color.new(colTP, 80) : rowBg           // reached takes get a tinted row
                f_cell(tTk, 0, i + 1, TKN.get(i) + (over ? " ↑Top" : ""), tc, tb)
                f_cell(tTk, 1, i + 1, str.tostring(px, format.mintick), tc, tb)
                f_cell(tTk, 2, i + 1, f_pct((px / baseAvg - 1.0) * 100.0), tc, tb)
                f_cell(tTk, 3, i + 1, str.tostring(TKF.get(i) * 100, "0.0") + "%", tc, tb)
                f_cell(tTk, 4, i + 1, str.tostring(TKF.get(i) * baseQty, qtyFmt), tc, tb)
                f_cell(tTk, 5, i + 1, f_money(dir * TKF.get(i) * baseQty * (px - baseAvg)), tc, tb)
                f_cell(tTk, 6, i + 1, rUnit > 0 ? str.tostring(dir * (px - baseAvg) / rUnit, "0.00") : "—", tc, tb)
            f_cell(tTk, 0, TKP.size() + 1, "Total", txt, hdrBg)
            f_cell(tTk, 1, TKP.size() + 1, str.tostring(exitAvg, format.mintick), txt, hdrBg)
            f_cell(tTk, 2, TKP.size() + 1, f_pct((exitAvg / baseAvg - 1.0) * 100.0), txt, hdrBg)
            f_cell(tTk, 3, TKP.size() + 1, "100%", txt, hdrBg)
            f_cell(tTk, 4, TKP.size() + 1, str.tostring(baseQty, qtyFmt), txt, hdrBg)
            f_cell(tTk, 5, TKP.size() + 1, f_money(profTakes), colTP, hdrBg)
            f_cell(tTk, 6, TKP.size() + 1, rUnit > 0 ? str.tostring(dir * (exitAvg - baseAvg) / rUnit, "0.00") : "—", txt, hdrBg)

← 返回列表