本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("PrimoX 1.0 — TheurgyLabs", shorttitle="PrimoX 1.0", overlay=false, max_lines_count=200, max_bars_back=600)
// PRIMOX 1.0. Build 2026-11-11. Renamed from PMO Extremes. Same engine as PMO Extremes 1.02, bar for bar. Names
// changed in the title, table, alerts and two export titles (PrimoX BUILD, PrimoX Divergence). Nothing else changes.
// PMO EXTREMES 1.02. Build 2026-11-11. Display only: "Marks on" now defaults to Both, so the triangles and the
// divergence dots show on the price bars and on the PMO pane. Nothing else changes.
// PMO EXTREMES 1.01. Build 2026-11-11. Display only: buy / sell triangles and divergence dots can sit on the
// price bars (new setting "Marks on", default Price bars; also PMO pane, Both, Off). Signals, fills, table numbers
// and exports are unchanged. A divergence dot on price sits on the bar of the PMO turn, not on the exact price
// low or high, which can be a few bars earlier. Divergence lines stay on the PMO pane.
// PMO EXTREMES 1.0 — TheurgyLabs. Build 2026-11-11. First build.
// Premise: the Price Momentum Oscillator (PMO) swings between extremes of its own range. Buy when the PMO line
// crosses up through its signal line at a learned low extreme. Sell when it crosses down at a learned high extreme.
// - PMO: one-bar percent change, smoothed twice (35 then 20, smoothing 2 / length), times 10. Signal: EMA 10 of the
// PMO. Same values as TradingView's built-in Price Momentum Oscillator (checked to 10 decimals on BTC 1D).
// - Learned lines: the 10th and 90th percentile of the PMO over the last 252 bars, anchored to the previous closed
// bar. A cross counts when the PMO on the cross bar or the bar before it is at or beyond the line.
// - Signal book (the wire): each buy signal adds $100 of units; each sell signal sells the sell % of its units.
// Sells need units > 0 and never share a bar with a buy. No cap on the wire.
// - Account: $10,000 starting capital. Each buy spends a percent of the remaining cash (default 25%). Each sell
// sells a percent of the units held (default 25%). Average-cost basis; unsold units carry forward at average
// entry. Decisions at the confirmed close, fills at the next open, 5 + 5 bp per side. Shown beside buy-and-hold.
// - Cycles: a cycle closes when a buy fills after one or more sales, before that buy.
// - Divergence (display and alerts only): lime dot = bullish (price makes a lower low while the PMO makes a higher
// low), white dot = bearish (price higher high, PMO lower high). Pivots are taken on the PMO line. A dot appears
// only after the pivot is confirmed, and is drawn back on the pivot bar.
// Long / cash only. No orders are sent to a broker. Not yet shot on the Pain Board.
// ── INPUTS ──────────────────────────────────────────────────────────────────────
string G_B = "1 · PMO and signals"
int i_len1 = input.int(35, "First smoothing", minval=2, maxval=200, group=G_B, display=display.none)
int i_len2 = input.int(20, "Second smoothing", minval=2, maxval=200, group=G_B, display=display.none)
int i_sigLen = input.int(10, "Signal length", minval=2, maxval=100, group=G_B, display=display.none)
int i_learn = input.int(252, "Learning window (bars)", minval=50, maxval=500, group=G_B, tooltip="The high and low lines are percentiles of the PMO over this many bars, ending at the previous closed bar.", display=display.none)
float i_hiPct = input.float(90, "High line (percentile)", minval=50, maxval=99, step=1, group=G_B, tooltip="A sell needs a cross down with the PMO at or above this percentile of its own recent values.", display=display.none)
float i_loPct = input.float(10, "Low line (percentile)", minval=1, maxval=50, step=1, group=G_B, tooltip="A buy needs a cross up with the PMO at or below this percentile of its own recent values.", display=display.none)
string G_A = "2 · Account"
float i_cap = input.float(10000, "Starting capital", minval=1, group=G_A, display=display.none)
float i_buyPct = input.float(25, "Buy: % of remaining cash", minval=1, maxval=100, step=1, group=G_A, tooltip="Each buy spends this share of the cash left. Buys get smaller as cash runs down.", display=display.none)
float i_sellPct = input.float(25, "Sell: % of units held", minval=1, maxval=100, step=1, group=G_A, tooltip="Each sell sells this share of the units held. 100 = full exit on every sell.", display=display.none)
float i_fee = input.float(5, "Commission per side (bps)", minval=0, maxval=100, group=G_A, display=display.none) / 10000
float i_slip = input.float(5, "Slippage per side (bps)", minval=0, maxval=100, group=G_A, display=display.none) / 10000
float i_minOrder = input.float(1, "Smallest order ($)", minval=0, group=G_A, tooltip="The account skips a buy smaller than this (the signal is still sent). After a sale, units worth less than this are sold with it.", display=display.none)
int i_start = input.time(timestamp("01 Jan 2021 00:00 +0000"), "Start", group=G_A, tooltip="The account opens at the first bar on or after this date once the learned lines exist. Buy-and-hold buys at the same open.", display=display.none)
string G_V = "3 · Divergence (display and alerts only)"
bool i_div = input.bool(true, "Divergence dots (lime = bullish, white = bearish)", group=G_V, display=display.none)
bool i_divLines = input.bool(true, "Divergence lines", group=G_V, display=display.none)
int i_pivL = input.int(5, "Pivot left bars", minval=2, maxval=20, group=G_V, display=display.none)
int i_pivR = input.int(3, "Pivot right bars", minval=1, maxval=10, group=G_V, tooltip="A dot appears this many bars after the PMO turn, once the turn is confirmed.", display=display.none)
int i_pivMax = input.int(90, "Max bars between pivots", minval=10, maxval=300, group=G_V, tooltip="The PMO is slow, so its turns sit weeks apart. The fleet's usual 24 bars would find almost none.", display=display.none)
int i_divWin = input.int(15, "Price window (bars)", minval=3, maxval=50, group=G_V, tooltip="The PMO turns after price does. The price low or high is the extreme of this many bars ending at the confirmation bar.", display=display.none)
string G_D = "4 · Display"
string i_where = input.string("Both", "Marks on", options=["Both", "Price bars", "PMO pane", "Off"], group=G_D, tooltip="Where the buy / sell triangles and the divergence dots are drawn. Price bars puts them on the main chart.", display=display.none)
bool i_zones = input.bool(true, "Learned high and low lines", group=G_D, display=display.none)
bool i_tbl = input.bool(true, "Table", group=G_D, display=display.none)
string i_pos = input.string("Bottom Right", "Table position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=G_D, display=display.none)
string i_tsz = input.string("Small", "Table text size", options=["Tiny", "Small", "Normal"], group=G_D, display=display.none)
string G_W = "5 · Alerts"
bool i_alertBuy = input.bool(true, "alert() on BUY", group=G_W, tooltip="JSON message, sent with 'Any alert() function call'.", display=display.none)
bool i_alertSell = input.bool(true, "alert() on SELL", group=G_W, display=display.none)
// ── COLORS (dark theme) ──────────────────────────────────────────────────────
color C_TXT = #d0d0d0
color C_HDR = #1a1a2e
color C_ROW = #0d0d1a
color C_ROW2 = #1f1f3a
color C_BORDER = #333355
color C_GREEN = #00FF88
color C_RED = #FF4444
color C_GOLD = #FFD700
color C_CYAN = #00FFFF
color C_MAG = #FF00FF
color C_LIME = #32CD32
color C_BLUE = #4DA6FF
// ── HELPERS ──────────────────────────────────────────────────────────────────
f_pos(string p) =>
switch p
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
=> position.bottom_right
string uiSz = i_tsz == "Tiny" ? size.tiny : i_tsz == "Normal" ? size.normal : size.small
f_px(float p) => na(p) ? "—" : p >= 1000 ? str.tostring(p, "#.#") : p >= 1 ? str.tostring(p, "#.##") : p >= 0.01 ? str.tostring(p, "#.####") : str.tostring(p, "#.######")
// DecisionPoint smoothing: weight 2 / length, seeded with the first value.
f_smooth(float src, int len) =>
var float s = na
s := na(src) ? s : na(s) ? src : s + 2.0 / len * (src - s)
s
// ── PMO ──────────────────────────────────────────────────────────────────────
float roc1 = close[1] > 0 ? (close / close[1] - 1) * 100 : na
float pmo = f_smooth(10 * f_smooth(roc1, i_len1), i_len2)
float sig = ta.ema(pmo, i_sigLen)
// Learned lines, anchored to the previous closed bar.
float hiNow = ta.percentile_linear_interpolation(pmo, i_learn, i_hiPct)
float loNow = ta.percentile_linear_interpolation(pmo, i_learn, i_loPct)
float hiThr = hiNow[1]
float loThr = loNow[1]
bool ready = not na(hiThr) and not na(loThr) and not na(sig) and not na(pmo[1])
bool crossUp = ready and pmo > sig and pmo[1] <= sig[1]
bool crossDn = ready and pmo < sig and pmo[1] >= sig[1]
bool rawBuy = crossUp and math.min(pmo, pmo[1]) <= loThr
bool rawSell = crossDn and math.max(pmo, pmo[1]) >= hiThr
// ── ACCOUNT ──────────────────────────────────────────────────────────────────
type Account
float cash = 0.0
float qty = 0.0
float basis = 0.0
float realized = 0.0
float equity = na
float peak = 0.0
float maxDD = 0.0
int marks = 0
int buys = 0
int sells = 0
float peakBasis = 0.0
float ddUsdMin = 0.0
float ddUsdSum = 0.0
float ddUsdSq = 0.0
int ddUsdUW = 0
// Spend a share of cash at px. Returns the dollars spent (entry costs included in the basis).
method purchase(Account a, float fraction, float px) =>
float budget = a.cash * fraction
float spent = 0.0
if budget > 0 and px > 0
a.qty += budget / (px * (1 + i_slip) * (1 + i_fee))
a.basis += budget
a.cash := math.max(0, a.cash - budget)
a.buys += 1
a.peakBasis := math.max(a.peakBasis, a.basis)
spent := budget
spent
// Sell a share of units at px at average cost. Leftover units worth less than the smallest order go with it.
// Returns the sale's net P&L.
method liquidate(Account a, float fraction, float px) =>
float f = a.qty * (1 - fraction) * px < i_minOrder ? 1.0 : fraction
float units = a.qty * f
float salePnl = 0.0
if units > 0
float cost = a.basis * f
float proceeds = units * px * (1 - i_slip) * (1 - i_fee)
salePnl := proceeds - cost
a.cash += proceeds
a.realized += salePnl
a.basis := f >= 1.0 ? 0.0 : math.max(0, a.basis - cost)
a.qty := f >= 1.0 ? 0.0 : math.max(0, a.qty - units)
a.sells += 1
salePnl
method mark(Account a, float px) =>
a.equity := a.cash + a.qty * px
a.peak := math.max(a.peak, a.equity)
float dd = a.peak > 0 ? 100 * (1 - a.equity / a.peak) : 0
a.maxDD := math.max(a.maxDD, dd)
float ddUsd = a.equity - a.peak
a.ddUsdMin := math.min(a.ddUsdMin, ddUsd)
a.ddUsdSq += ddUsd * ddUsd
if ddUsd < 0
a.ddUsdSum += ddUsd
a.ddUsdUW += 1
a.marks += 1
var Account bk = Account.new()
var Account hold = Account.new()
var bool started = false
var int pend = 0 // 1 = buy at the next open, -1 = sell at the next open
var float cycPnl = 0.0 // open cycle: P&L of its sales so far
var int cycSales = 0
var int cycles = 0
var int cycWins = 0
var int cycLosses = 0
var float cycGW = 0.0
var float cycGL = 0.0
var float deployed = 0.0
var int skipBuys = 0
// ── SIGNAL BOOK (unit inventory; drives the wire, independent of the account) ──
var float sigQty = 0.0
var int sigBuys = 0
var int sigSells = 0
bool buyTrig = barstate.isconfirmed and rawBuy
bool sellTrig = barstate.isconfirmed and not buyTrig and sigQty > 0 and rawSell
if buyTrig
sigQty += 100.0 / close
sigBuys += 1
if sellTrig
sigQty := i_sellPct >= 100 ? 0.0 : sigQty * (1 - i_sellPct / 100)
sigSells += 1
int dec = buyTrig ? 1 : sellTrig ? -1 : 0
if barstate.isconfirmed
// 1. Fill the decision from the last close at this bar's open. Cycle close comes before the buy.
if started and pend != 0
if pend == 1
if cycSales > 0
cycles += 1
if cycPnl > 0
cycWins += 1
cycGW += cycPnl
else if cycPnl < 0
cycLosses += 1
cycGL += -cycPnl
cycPnl := 0.0
cycSales := 0
deployed += bk.purchase(i_buyPct / 100, open)
else
cycPnl += bk.liquidate(i_sellPct / 100, open)
cycSales += 1
pend := 0
// 2. Open the account.
if not started and time >= i_start and ready and open > 0
started := true
bk.cash := i_cap
hold.cash := i_cap
bk.peak := i_cap
hold.peak := i_cap
hold.purchase(1.0, open)
// 3. Mark at the close, then follow the signal book's decision with the account.
if started
bk.mark(close)
hold.mark(close)
bool canBuy = bk.cash > 0 and bk.cash * i_buyPct / 100 >= i_minOrder
if buyTrig
if canBuy
pend := 1
else
skipBuys += 1
else if sellTrig and bk.qty > 0
pend := -1
// ── DIVERGENCE (display and alerts only; pivots on the PMO line) ─────────────
float pl = ta.pivotlow(pmo, i_pivL, i_pivR)
float ph = ta.pivothigh(pmo, i_pivL, i_pivR)
float pxLow = ta.lowest(low, i_divWin)
float pxHigh = ta.highest(high, i_divWin)
var float prevLowPmo = na
var float prevLowPx = na
var int prevLowBar = na
var float prevHighPmo = na
var float prevHighPx = na
var int prevHighBar = na
bool bullDiv = false
bool bearDiv = false
if not na(pl)
int barL = bar_index - i_pivR
bullDiv := i_div and not na(prevLowPmo) and pl > prevLowPmo and pxLow < prevLowPx and barL - prevLowBar <= i_pivMax
if bullDiv and i_divLines
line.new(prevLowBar, prevLowPmo, barL, pl, color=C_LIME, width=1)
prevLowPmo := pl
prevLowPx := pxLow
prevLowBar := barL
if not na(ph)
int barH = bar_index - i_pivR
bearDiv := i_div and not na(prevHighPmo) and ph < prevHighPmo and pxHigh > prevHighPx and barH - prevHighBar <= i_pivMax
if bearDiv and i_divLines
line.new(prevHighBar, prevHighPmo, barH, ph, color=color.white, width=1)
prevHighPmo := ph
prevHighPx := pxHigh
prevHighBar := barH
// ── PLOTS ────────────────────────────────────────────────────────────────────
hline(0, "Zero", color=color.new(C_TXT, 60), linestyle=hline.style_dashed)
plot(i_zones ? hiThr : na, "High line", color.new(C_RED, 40), 1, plot.style_stepline)
plot(i_zones ? loThr : na, "Low line", color.new(C_GREEN, 40), 1, plot.style_stepline)
plot(pmo, "PMO", C_BLUE, 2)
plot(sig, "Signal", C_RED, 1)
bool onPane = i_where == "PMO pane" or i_where == "Both"
bool onPrice = i_where == "Price bars" or i_where == "Both"
plotshape(onPane and bullDiv ? pl : na, "Bullish divergence", shape.circle, location.absolute, C_LIME, offset=-i_pivR, size=size.tiny, display=display.pane)
plotshape(onPane and bearDiv ? ph : na, "Bearish divergence", shape.circle, location.absolute, color.white, offset=-i_pivR, size=size.tiny, display=display.pane)
plotshape(onPane and dec == 1 ? math.min(pmo, sig) : na, "Buy", shape.triangleup, location.absolute, C_CYAN, size=size.small, display=display.pane)
plotshape(onPane and dec == -1 ? math.max(pmo, sig) : na, "Sell", shape.triangledown, location.absolute, C_MAG, size=size.small, display=display.pane)
plotshape(onPrice and bullDiv, "Bullish divergence (price)", shape.circle, location.belowbar, C_LIME, offset=-i_pivR, size=size.tiny, force_overlay=true)
plotshape(onPrice and bearDiv, "Bearish divergence (price)", shape.circle, location.abovebar, color.white, offset=-i_pivR, size=size.tiny, force_overlay=true)
plotshape(onPrice and dec == 1, "Buy (price)", shape.triangleup, location.belowbar, C_CYAN, size=size.small, force_overlay=true)
plotshape(onPrice and dec == -1, "Sell (price)", shape.triangledown, location.abovebar, C_MAG, size=size.small, force_overlay=true)
// ── TABLE (display only) ─────────────────────────────────────────────────────
f_dollar(float v) =>
float r = math.round(v)
na(v) ? "—" : (r < 0 ? "-$" : "$") + str.tostring(math.abs(r), "#,###")
f_num(float v) => na(v) ? "—" : str.tostring(v, "0.##")
f_pct(float v) => na(v) ? "—" : str.tostring(v, "0.#") + "%"
f_sign(float v) => na(v) or v == 0 ? C_TXT : v > 0 ? C_GREEN : C_RED
f_row(table t, int col, int row, string lbl, string mine, string bh, color mc, color hc, string tip) =>
color bg = row % 2 == 0 ? C_ROW2 : C_ROW
table.cell(t, col, row, lbl, text_color=C_TXT, bgcolor=bg, text_halign=text.align_left, text_size=uiSz, tooltip=tip)
table.cell(t, col + 1, row, mine, text_color=mc, bgcolor=bg, text_halign=text.align_right, text_size=uiSz, tooltip=tip)
table.cell(t, col + 2, row, bh, text_color=hc, bgcolor=bg, text_halign=text.align_right, text_size=uiSz, tooltip=tip)
var table tb = table.new(f_pos(i_pos), 6, 14, frame_color=C_BORDER, frame_width=1, border_color=C_BORDER, border_width=1)
if barstate.islast and i_tbl
table.clear(tb, 0, 0, 5, 13)
bool on = started and bk.marks > 0
float eq = on ? bk.equity : na
float hEq = on ? hold.equity : na
float unrl = on ? (bk.equity - bk.cash) - bk.basis : na
float hUnrl = on ? (hold.equity - hold.cash) - hold.basis : na
float tot = on ? eq - i_cap : na
float hTot = on ? hEq - i_cap : na
float pain = on ? math.sqrt(bk.ddUsdSq / bk.marks) : na
float hPain = on ? math.sqrt(hold.ddUsdSq / hold.marks) : na
float avgDD = on ? (bk.ddUsdUW > 0 ? bk.ddUsdSum / bk.ddUsdUW : 0) : na
float hAvgDD = on ? (hold.ddUsdUW > 0 ? hold.ddUsdSum / hold.ddUsdUW : 0) : na
float uw = on ? 100.0 * bk.ddUsdUW / bk.marks : na
float hUw = on ? 100.0 * hold.ddUsdUW / hold.marks : na
float pf = cycGL > 0 ? cycGW / cycGL : na
float winRate = cycles > 0 ? 100.0 * cycWins / cycles : na
float perCyc = cycles > 0 ? (cycGW - cycGL) / cycles : na
float avgW = cycWins > 0 ? cycGW / cycWins : na
float avgL = cycLosses > 0 ? cycGL / cycLosses : na
float rp = on and pain > 0 ? bk.realized / pain : na
float expo = on and eq > 0 ? 100 * (eq - bk.cash) / eq : na
float avgEnt = bk.qty > 0 ? bk.basis / bk.qty : na
float nxHi = barstate.isconfirmed ? hiNow : hiThr
float nxLo = barstate.isconfirmed ? loNow : loThr
string tfTxt = timeframe.isdwm ? str.tostring(timeframe.multiplier) + (timeframe.isdaily ? "D" : timeframe.isweekly ? "W" : "M") : timeframe.isminutes and timeframe.multiplier % 60 == 0 ? str.tostring(int(timeframe.multiplier / 60)) + "H" : timeframe.isminutes ? str.tostring(timeframe.multiplier) + "m" : timeframe.period
string queue = pend == 1 ? "BUY at next open" : pend == -1 ? "SELL at next open" : bk.qty > 0 ? "HOLDING" : "CASH"
string zone = na(nxHi) ? "LEARNING" : pmo >= nxHi ? "HIGH ZONE" : pmo <= nxLo ? "LOW ZONE" : "MIDDLE"
color zoneC = na(nxHi) ? C_TXT : pmo >= nxHi ? C_RED : pmo <= nxLo ? C_GREEN : C_TXT
string hdrTip = "PrimoX 1.0. PMO " + str.tostring(i_len1) + " / " + str.tostring(i_len2) + ", signal " + str.tostring(i_sigLen) + ". Buy: PMO crosses up through its signal at or below the " + str.tostring(i_loPct, "0") + "th percentile of its last " + str.tostring(i_learn) + " bars. Sell: PMO crosses down at or above the " + str.tostring(i_hiPct, "0") + "th percentile.\nBuys spend " + str.tostring(i_buyPct, "0.#") + "% of remaining cash; sells sell " + str.tostring(i_sellPct, "0.#") + "% of units. Decisions at confirmed closes, fills at the next open, " + str.tostring(i_fee * 10000, "0.#") + " + " + str.tostring(i_slip * 10000, "0.#") + " bp per side. B&H = all cash at the same first open."
string cycTip = "Per closed cycle. A cycle closes when a buy fills after one or more sales. Open cycle so far: " + str.tostring(cycSales) + " sales, " + f_dollar(cycPnl) + "."
for c = 0 to 5
string h = c == 0 ? "PrimoX 1.0 · " + tfTxt : c == 3 ? queue : c == 1 or c == 4 ? "PrimoX" : "B&H"
color hc = c == 0 ? C_CYAN : c == 3 ? (pend == 1 ? C_GREEN : pend == -1 ? C_RED : C_GOLD) : C_TXT
table.cell(tb, c, 0, h, text_color=hc, bgcolor=C_HDR, text_size=uiSz, tooltip=hdrTip)
f_row(tb, 0, 1, "Real", f_dollar(on ? bk.realized : na), f_dollar(on ? 0 : na), f_sign(bk.realized), C_TXT, "Net P&L of all sales at average cost, costs included. B&H has no sale.")
f_row(tb, 3, 1, "Unrl", f_dollar(unrl), f_dollar(hUnrl), f_sign(unrl), f_sign(hUnrl), "Open units at the last confirmed close minus their basis. No exit fee assumed.")
f_row(tb, 0, 2, "PnL", f_dollar(tot), f_dollar(hTot), f_sign(tot), f_sign(hTot), "Equity minus starting capital.")
f_row(tb, 3, 2, "ROI", f_pct(on ? tot / i_cap * 100 : na), f_pct(on ? hTot / i_cap * 100 : na), f_sign(tot), f_sign(hTot), "Total P&L / starting capital.")
f_row(tb, 0, 3, "PF", f_num(pf), "—", C_TXT, C_TXT, cycTip + " Gross cycle wins / gross cycle losses.")
f_row(tb, 3, 3, "Win%", f_pct(winRate), "—", C_TXT, C_TXT, cycTip + " Winning cycles / closed cycles; breakevens in the denominator.")
f_row(tb, 0, 4, "W/L", str.tostring(cycWins) + "/" + str.tostring(cycLosses), "—", C_TXT, C_TXT, cycTip)
f_row(tb, 3, 4, "$/Cyc", f_dollar(perCyc), "—", f_sign(perCyc), C_TXT, cycTip + " Average net P&L per closed cycle.")
f_row(tb, 0, 5, "AvgW", f_dollar(avgW), "—", C_GREEN, C_TXT, cycTip + " Average winning cycle.")
f_row(tb, 3, 5, "AvgL", f_dollar(avgL), "—", C_RED, C_TXT, cycTip + " Average losing cycle.")
f_row(tb, 0, 6, "MaxDD", f_dollar(on ? bk.ddUsdMin : na), f_dollar(on ? hold.ddUsdMin : na), C_RED, C_RED, "Worst dollar drop of equity from its peak, at closes (realized plus unrealized). Percent: PrimoX " + f_pct(on ? bk.maxDD : na) + ", B&H " + f_pct(on ? hold.maxDD : na) + ".")
f_row(tb, 3, 6, "Pain$", f_dollar(pain), f_dollar(hPain), C_TXT, C_TXT, "Root mean square of the dollar drop below the equity peak, over every close since the start. Deep counts more; time counts too.")
f_row(tb, 0, 7, "R/P", f_num(rp), "—", C_TXT, C_TXT, "Realized P&L / Pain$.")
f_row(tb, 3, 7, "UW%", f_pct(uw), f_pct(hUw), C_TXT, C_TXT, "Share of closes below the equity peak.")
f_row(tb, 0, 8, "AvgDD", f_dollar(avgDD), f_dollar(hAvgDD), C_RED, C_RED, "Average dollar drawdown on the closes that were under water.")
f_row(tb, 3, 8, "Peak$", f_dollar(on ? bk.peakBasis : na), f_dollar(on ? i_cap : na), C_TXT, C_TXT, "Largest open basis, entry costs included.")
f_row(tb, 0, 9, "Eq$", f_dollar(eq), f_dollar(hEq), C_TXT, C_TXT, "Cash plus units at the last confirmed close.")
f_row(tb, 3, 9, "Pos", on ? (bk.qty > 0 ? "L" + str.tostring(math.round(nz(expo))) + "%" : "CASH") : "—", on ? "L" : "—", C_BLUE, C_TXT, "Invested share of equity. Average entry: " + f_px(avgEnt) + ".")
f_row(tb, 0, 10, "AvgEnt", f_px(avgEnt), "—", C_GOLD, C_TXT, "Average cost per unit held, entry costs included. Unsold units carry at this price.")
f_row(tb, 3, 10, "B/S", str.tostring(bk.buys) + "/" + str.tostring(bk.sells), on ? "1/0" : "—", C_TXT, C_TXT, "Filled buys / filled sells. Closed cycles: " + str.tostring(cycles) + ". Signals sent since the lines were ready: " + str.tostring(sigBuys) + " buys / " + str.tostring(sigSells) + " sells. Buy signals the account skipped for lack of cash: " + str.tostring(skipBuys) + ".")
f_row(tb, 0, 11, "Low≤", f_num(nxLo), "—", C_GREEN, C_TXT, "Next bar's low line: the " + str.tostring(i_loPct, "0") + "th percentile of the PMO. A cross up at or below it decides a buy.")
f_row(tb, 3, 11, "High≥", f_num(nxHi), "—", C_RED, C_TXT, "Next bar's high line: the " + str.tostring(i_hiPct, "0") + "th percentile of the PMO. A cross down at or above it decides a sell, units permitting.")
f_row(tb, 0, 12, "PMO", f_num(pmo), "—", C_BLUE, C_TXT, "PMO line. Signal line: " + f_num(sig) + ". PMO " + (pmo > sig ? "above" : "below") + " its signal.")
f_row(tb, 3, 12, "Zone", zone, "—", zoneC, C_TXT, "Where the PMO sits against its learned lines.")
f_row(tb, 0, 13, "Cash", f_dollar(on ? bk.cash : na), f_dollar(on ? hold.cash : na), C_TXT, C_TXT, "Cash on hand. Next buy would spend " + f_dollar(on ? bk.cash * i_buyPct / 100 : na) + ".")
f_row(tb, 3, 13, "Cyc", str.tostring(cycles), "—", C_TXT, C_TXT, cycTip)
// ── ALERTS ───────────────────────────────────────────────────────────────────
string whSym = syminfo.prefix + ":" + syminfo.ticker
if dec == 1 and i_alertBuy
alert('{"engine": "PrimoX 1.0", "action": "BUY", "symbol": "' + whSym + '", "tf": "' + timeframe.period + '", "decision_close": ' + str.tostring(close) + ', "buy_pct_cash": ' + str.tostring(i_buyPct) + ', "fill": "next open", "utc": "' + str.format_time(time_close, "yyyy-MM-dd HH:mm", "UTC") + '"}', alert.freq_once_per_bar_close)
if dec == -1 and i_alertSell
alert('{"engine": "PrimoX 1.0", "action": "SELL", "symbol": "' + whSym + '", "tf": "' + timeframe.period + '", "decision_close": ' + str.tostring(close) + ', "sell_pct_units": ' + str.tostring(i_sellPct) + ', "fill": "next open", "utc": "' + str.format_time(time_close, "yyyy-MM-dd HH:mm", "UTC") + '"}', alert.freq_once_per_bar_close)
alertcondition(dec == 1, "PrimoX BUY", "{{ticker}} PrimoX BUY decided at the close {{close}}; fill at the next open")
alertcondition(dec == -1, "PrimoX SELL", "{{ticker}} PrimoX SELL decided at the close {{close}}; fill at the next open")
alertcondition(bullDiv, "Bullish Divergence", "{{ticker}} bullish PMO divergence confirmed at {{close}}")
alertcondition(bearDiv, "Bearish Divergence", "{{ticker}} bearish PMO divergence confirmed at {{close}}")
// ── SQS SIGNAL + EXPORTS (fleet order) ───────────────────────────────────────
plot(dec, "SQS Signal", display=display.status_line)
plot(bk.realized, "SQS:Real", display=display.data_window)
plot(cycWins, "SQS:Wins", display=display.data_window)
plot(cycLosses, "SQS:Losses", display=display.data_window)
plot(cycGW, "SQS:GrossW", display=display.data_window)
plot(cycGL, "SQS:GrossL", display=display.data_window)
plot(math.abs(bk.ddUsdMin), "SQS:MaxDD", display=display.data_window)
plot(deployed, "SQS:Deploy", display=display.data_window)
plot(sigBuys + sigSells, "SQS:Sigs", display=display.data_window)
plot(cycles, "SQS:Cycles", display=display.data_window)
plot(bk.peakBasis, "SQS:PeakCost", display=display.data_window)
plot(started ? bk.equity - i_cap : 0.0, "SQS:TotPnL", display=display.data_window)
plot(bar_index, "SQS:Bars", display=display.data_window)
plot(1.0, "PrimoX BUILD", display=display.data_window)
plot(bullDiv ? 1 : bearDiv ? -1 : 0, "PrimoX Divergence (1 bull, -1 bear, at confirmation)", display=display.data_window)