本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Tetrad 1.3 — TheurgyLabs", shorttitle="Tetrad 1.3", overlay=false, max_bars_back=600, max_boxes_count=60, max_labels_count=60, max_lines_count=200)
// TETRAD 1.3. Build 2026-11-15. The table moves to the price chart (upper pane), bottom right by default (setting
// "Table on the price chart"; off puts it back in Tetrad's pane). Signals and accounts unchanged.
// TETRAD 1.2. Build 2026-11-14. Sells default to 20% of units (owner decision 2026-11-14); buys stay 50% of cash.
// Signals unchanged. Registered test at 50% buys: 20% sells failed the fair-test rules in both markets. Russ's 21
// stocks: 0.61 to 0.67 of buy-and-hold; median max drawdown 46% to 48% (70 stocks).
// Charts that already carry this indicator keep their old values until Settings > Defaults > Reset settings.
// TETRAD 1.1. Build 2026-11-14. Buys default to 50% of cash (owner decision 2026-11-14); sells stay 25% of units. Signals unchanged.
// The registered test failed the fair-test rules in both markets: on Russ's 21 stocks 50% buys lifted wealth from 0.45 to 0.61
// of buy-and-hold with deeper drawdowns (36% to 46% median, 70 stocks); on the 49-stock set and the 12 coins it did worse.
// Charts that already carry this indicator keep 25% until Settings > Defaults > Reset settings (or set it by hand).
// TETRAD 1.0, DIVERGENCE REVISION. Build 2026-11-14. Display and alerts only: divergence dots and lines (new group
// "5 · Divergence"). Pivots on the meter, 5 bars left and 3 right (the fleet standard), at most 24 bars apart; the
// price low or high is the extreme of the 9 bars ending at the confirmation bar. White = bullish (price lower low,
// meter higher low); yellow = bearish (price higher high, meter lower high). A dot appears once the pivot is
// confirmed, 3 bars later, and is drawn back on the pivot bar. Signals, fills, the table and the exports are unchanged.
// TETRAD 1.0 — TheurgyLabs. Build 2026-11-14. First build.
// Four momentum readings, each scored -1..+1, combined into one meter on a -5..+5 scale.
// - Four votes, each clamped to -1..+1: RSI 14 as (RSI - 50) / 20; Stochastic RSI 14 with K = SMA 3 as (K - 50) / 30;
// the MACD 12 / 26 / 9 histogram over twice its own 100-bar standard deviation; and the Bollinger 20 / 2 position,
// (close - basis) / (2 standard deviations). Meter = 1.25 x EMA 3 of the sum, on -5..+5. Positive = overbought,
// negative = oversold.
// - Buy: the meter turns up after a bar at or below minus the signal level. Sell: it turns down after a bar at or above
// the signal level. Decisions at confirmed closes.
// - 2026-11-14 test against plain MR Zones (same opening bar, levels 2 to 4): no level beat MRZ on stocks. On crypto only
// level 4 passed (12-coin median 1.72 vs 1.57 of buy-and-hold, ahead on 8 of 12), alone, which the test rules count as
// noise. Default level 4. On BTC daily the meter sits beyond +/-2 about half the time, so readings near 2 are common.
// - Signal book and account as MR Zones: $10,000 starting capital, each buy spends 25% of the cash left, each sell sells
// 25% of the units held, average-cost basis, decisions at the confirmed close, fills at the next open, 5 + 5 bp per
// side. A cycle closes when a buy fills after one or more sales. Shown beside buy-and-hold from the same first open.
// - The gauge is drawn in this pane, on the meter's own -5..+5 scale, so its marks are readings, not prices.
// Long / cash only. No orders are sent to a broker. Not financial advice.
// ── INPUTS ──────────────────────────────────────────────────────────────────────
string G_B = "1 · Meter and signals"
int i_rsiLen = input.int(14, "RSI length", minval=2, maxval=100, group=G_B, display=display.none)
int i_stLen = input.int(14, "Stochastic RSI length", minval=2, maxval=100, group=G_B, display=display.none)
int i_kLen = input.int(3, "Stochastic RSI smoothing (K)", minval=1, maxval=20, group=G_B, display=display.none)
int i_fast = input.int(12, "MACD fast", minval=2, maxval=100, group=G_B, display=display.none)
int i_slow = input.int(26, "MACD slow", minval=3, maxval=200, group=G_B, display=display.none)
int i_sigM = input.int(9, "MACD signal", minval=2, maxval=50, group=G_B, display=display.none)
int i_hVol = input.int(100, "MACD histogram volatility (bars)", minval=10, maxval=500, group=G_B, tooltip="The MACD vote is the histogram over twice its standard deviation over this many bars.", display=display.none)
int i_bbLen = input.int(20, "Bollinger length", minval=2, maxval=200, group=G_B, display=display.none)
float i_bbMult = input.float(2.0, "Bollinger width (standard deviations)", minval=0.5, maxval=5, step=0.1, group=G_B, display=display.none)
int i_smooth = input.int(3, "Meter smoothing (EMA)", minval=1, maxval=20, group=G_B, display=display.none)
float i_level = input.float(4.0, "Signal level (+/-)", minval=0.5, maxval=5, step=0.5, group=G_B, tooltip="Buy: the meter turns up after a bar at or below minus this level. Sell: it turns down after a bar at or above it. Test 2026-11-14: 4 was the only level that passed anything (crypto, alone); no level beat MR Zones on stocks.", 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(50, "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(20, "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 2018 00:00 +0000"), "Start", group=G_A, tooltip="The account opens at the first bar on or after this date once the meter exists (about 135 bars of history at default settings). Buy-and-hold buys at the same open.", display=display.none)
string G_D = "3 · Display"
string i_where = input.string("Both", "Marks on", options=["Both", "Price bars", "Meter pane", "Off"], group=G_D, tooltip="Where the buy / sell triangles are drawn.", display=display.none)
bool i_gauge = input.bool(true, "Gauge beside the meter", group=G_D, tooltip="A -5..+5 color bar to the right of the last bar, with the current reading.", display=display.none)
bool i_heat = input.bool(true, "Heat tint on the price chart", group=G_D, tooltip="Tints the price chart's background by the meter: red when overbought, green when oversold, clear between -1 and +1.", 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 = "4 · 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)
// Appended last so saved settings keep their places.
string G_V = "5 · Divergence (display and alerts only)"
bool i_div = input.bool(true, "Divergence dots (white = bullish, yellow = 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 meter turns, once the turn is confirmed, and is drawn back on the turn.", display=display.none)
int i_pivMax = input.int(24, "Max bars between pivots", minval=5, maxval=300, group=G_V, display=display.none)
int i_divWin = input.int(9, "Price window (bars)", minval=3, maxval=50, group=G_V, tooltip="The price low or high is the extreme of this many bars ending at the confirmation bar.", display=display.none)
// 1.3 (declared after every older input so saved settings keep their places)
bool i_tblPrice = input.bool(true, "Table on the price chart", group=G_D, tooltip="On: the table sits in the price pane (upper), at the Table position. Off: in Tetrad's own pane, as before.", 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_BULLDV = color.white // bullish divergence
color C_BEARDV = #FFFF00 // bearish divergence (yellow)
// ── 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, "#.######")
f_clamp(float v) => na(v) ? na : math.max(-1.0, math.min(1.0, v))
f_signed(float v) => na(v) ? "—" : (v >= 0 ? "+" : "") + str.tostring(v, "0.00")
// ── METER (every function on every bar) ──────────────────────────────────────
float rsi = ta.rsi(close, i_rsiLen)
float rLo = ta.lowest(rsi, i_stLen)
float rHi = ta.highest(rsi, i_stLen)
float stRaw = rHi - rLo > 0 ? 100 * (rsi - rLo) / (rHi - rLo) : na
float stK = ta.sma(stRaw, i_kLen)
[mLine, mSig, mHist] = ta.macd(close, i_fast, i_slow, i_sigM)
float hSd = ta.stdev(mHist, i_hVol)
float basis = ta.sma(close, i_bbLen)
float bbSd = ta.stdev(close, i_bbLen)
float v1 = f_clamp((rsi - 50) / 20)
float v2 = f_clamp((stK - 50) / 30)
float v3 = hSd > 0 ? f_clamp(mHist / (2 * hSd)) : na
float v4 = bbSd > 0 ? f_clamp((close - basis) / (i_bbMult * bbSd)) : na
float raw = v1 + v2 + v3 + v4
float m = 1.25 * ta.ema(raw, i_smooth)
// ── SIGNALS ──────────────────────────────────────────────────────────────────
bool ready = not na(m[2]) and not na(m)
bool turnUp = ready and m > m[1] and m[1] <= m[2]
bool turnDn = ready and m < m[1] and m[1] >= m[2]
bool rawBuy = turnUp and m[1] <= -i_level
bool rawSell = turnDn and m[1] >= i_level
// ── 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 meter) ────────────────
float pl = ta.pivotlow(m, i_pivL, i_pivR)
float ph = ta.pivothigh(m, i_pivL, i_pivR)
float pxLow = ta.lowest(low, i_divWin)
float pxHigh = ta.highest(high, i_divWin)
var float prevLowM = na
var float prevLowPx = na
var int prevLowBar = na
var float prevHighM = 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(prevLowM) and pl > prevLowM and pxLow < prevLowPx and barL - prevLowBar <= i_pivMax
if bullDiv and i_divLines
line.new(prevLowBar, prevLowM, barL, pl, color=C_BULLDV, width=1)
prevLowM := pl
prevLowPx := pxLow
prevLowBar := barL
if not na(ph)
int barH = bar_index - i_pivR
bearDiv := i_div and not na(prevHighM) and ph < prevHighM and pxHigh > prevHighPx and barH - prevHighBar <= i_pivMax
if bearDiv and i_divLines
line.new(prevHighBar, prevHighM, barH, ph, color=C_BEARDV, width=1)
prevHighM := ph
prevHighPx := pxHigh
prevHighBar := barH
// ── PLOTS ────────────────────────────────────────────────────────────────────
hline(0, "Zero", color=color.new(C_TXT, 60), linestyle=hline.style_dashed)
hline(i_level, "Sell level", color=color.new(C_RED, 40), linestyle=hline.style_solid)
hline(-i_level, "Buy level", color=color.new(C_GREEN, 40), linestyle=hline.style_solid)
hline(5, "Top", color=color.new(C_RED, 75), linestyle=hline.style_dotted)
hline(-5, "Bottom", color=color.new(C_GREEN, 75), linestyle=hline.style_dotted)
plot(m, "Meter", color.from_gradient(nz(m), -5, 5, C_GREEN, C_RED), 2)
bool onPane = i_where == "Meter pane" or i_where == "Both"
bool onPrice = i_where == "Price bars" or i_where == "Both"
plotshape(onPane and dec == 1 ? m : na, "Buy", shape.triangleup, location.absolute, C_CYAN, size=size.small, display=display.pane)
plotshape(onPane and dec == -1 ? m : na, "Sell", shape.triangledown, location.absolute, C_MAG, size=size.small, display=display.pane)
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)
plotshape(onPane and bullDiv ? pl : na, "Bullish divergence", shape.circle, location.absolute, C_BULLDV, offset=-i_pivR, size=size.tiny, display=display.pane)
plotshape(onPane and bearDiv ? ph : na, "Bearish divergence", shape.circle, location.absolute, C_BEARDV, offset=-i_pivR, size=size.tiny, display=display.pane)
plotshape(onPrice and bullDiv, "Bullish divergence (price)", shape.circle, location.belowbar, C_BULLDV, offset=-i_pivR, size=size.tiny, force_overlay=true)
plotshape(onPrice and bearDiv, "Bearish divergence (price)", shape.circle, location.abovebar, C_BEARDV, offset=-i_pivR, size=size.tiny, force_overlay=true)
// Heat tint on the price chart: clear between -1 and +1, strongest at +/-5.
float heatA = math.max(0.0, math.abs(nz(m)) - 1.0) / 4.0
color heatC = nz(m) >= 0 ? color.new(C_RED, 100 - 30 * heatA) : color.new(C_GREEN, 100 - 30 * heatA)
bgcolor(i_heat and not na(m) ? heatC : na, title="Heat tint (price)", force_overlay=true)
// Gauge: a -5..+5 color bar to the right of the last bar, in this pane, with the current reading.
var array<box> gBoxes = array.new<box>()
var label gMark = na
if barstate.islast and i_gauge
while gBoxes.size() > 0
box.delete(gBoxes.pop())
for k = 0 to 19
float y0 = -5 + 0.5 * k
color gc = color.from_gradient(y0 + 0.25, -5, 5, C_GREEN, C_RED)
gBoxes.push(box.new(bar_index + 3, y0 + 0.5, bar_index + 6, y0, border_color=gc, bgcolor=color.new(gc, 20)))
label.delete(gMark)
gMark := label.new(bar_index + 6, nz(m), f_signed(m), style=label.style_label_left, color=C_HDR, textcolor=nz(m) >= 0 ? C_RED : C_GREEN, size=size.small)
// ── TABLE (display only) ─────────────────────────────────────────────────────
// 12 metrics in 5 columns, as in MR Zones. Left: label, Tetrad, B&H. Right: the cycle stats. The title and the queue
// cell are merged across columns. The rest lives in the tooltips.
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_lbl(table t, int col, int row, string lbl, string tip) =>
table.cell(t, col, row, lbl, text_color=C_TXT, bgcolor=row % 2 == 0 ? C_ROW : C_ROW2, text_halign=text.align_left, text_size=uiSz, tooltip=tip)
f_val(table t, int col, int row, string txt, color tc, string tip) =>
table.cell(t, col, row, txt, text_color=tc, bgcolor=row % 2 == 0 ? C_ROW : C_ROW2, text_halign=text.align_right, text_size=uiSz, tooltip=tip)
f_rowBH(table t, int row, string lbl, string mine, string bh, color mc, color hc, string tip) =>
f_lbl(t, 0, row, lbl, tip)
f_val(t, 1, row, mine, mc, tip)
f_val(t, 2, row, bh, hc, tip)
f_rowOne(table t, int row, string lbl, string mine, color mc, string tip) =>
f_lbl(t, 3, row, lbl, tip)
f_val(t, 4, row, mine, mc, tip)
// 1.3: force_overlay must be a constant, so both tables exist and only the chosen one is filled.
var table tbPane = table.new(f_pos(i_pos), 5, 8, frame_color=C_BORDER, frame_width=1, border_color=C_BORDER, border_width=1)
var table tbPrice = table.new(f_pos(i_pos), 5, 8, frame_color=C_BORDER, frame_width=1, border_color=C_BORDER, border_width=1, force_overlay=true)
table tb = i_tblPrice ? tbPrice : tbPane
if barstate.isfirst and i_tbl
table.merge_cells(tb, 0, 0, 4, 0) // title row
table.merge_cells(tb, 3, 1, 4, 1) // queue state, over the cycle columns
if barstate.islast and i_tbl
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
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 next" : pend == -1 ? "SELL next" : bk.qty > 0 ? "HOLDING" : "CASH"
color queueC = pend == 1 ? C_GREEN : pend == -1 ? C_RED : C_GOLD
string state = na(m) ? "still warming up" : m >= i_level ? "at or above the sell level" : m <= -i_level ? "at or below the buy level" : math.abs(m) <= 1 ? "neutral" : m > 0 ? "leaning overbought" : "leaning oversold"
string hdrTip = "Tetrad 1.3. Votes, each -1..+1: RSI " + str.tostring(i_rsiLen) + ", Stochastic RSI " + str.tostring(i_stLen) + " / " + str.tostring(i_kLen) + ", MACD " + str.tostring(i_fast) + " / " + str.tostring(i_slow) + " / " + str.tostring(i_sigM) + " histogram over twice its " + str.tostring(i_hVol) + "-bar deviation, Bollinger " + str.tostring(i_bbLen) + " / " + str.tostring(i_bbMult, "0.#") + " position. Meter = 1.25 x EMA " + str.tostring(i_smooth) + " of the sum, -5..+5, positive = overbought. Buy: the meter turns up after a bar at or below -" + str.tostring(i_level, "0.#") + ". Sell: it turns down after a bar at or above +" + str.tostring(i_level, "0.#") + ".\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.\nNow: meter " + f_signed(m) + ", " + state + ". Votes: RSI " + f_signed(v1) + ", Stochastic RSI " + f_signed(v2) + ", MACD " + f_signed(v3) + ", Bollinger " + f_signed(v4) + "."
string stTip = (pend == 1 ? "BUY queued for the next open. " : pend == -1 ? "SELL queued for the next open. " : "") + "Invested " + (on ? str.tostring(math.round(nz(expo))) + "%" : "—") + ", average entry " + f_px(avgEnt) + ", cash " + f_dollar(on ? bk.cash : na) + " (next buy would spend " + f_dollar(on ? bk.cash * i_buyPct / 100 : na) + "). Equity " + f_dollar(eq) + ", B&H " + f_dollar(hEq) + ".\nFilled buys / sells " + str.tostring(bk.buys) + " / " + str.tostring(bk.sells) + ", closed cycles " + str.tostring(cycles) + ". Signals sent since the meter was ready: " + str.tostring(sigBuys) + " buys / " + str.tostring(sigSells) + " sells; buys skipped for lack of cash: " + str.tostring(skipBuys) + "."
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) + "."
table.cell(tb, 0, 0, "Tetrad 1.3 · " + tfTxt, text_color=C_CYAN, bgcolor=C_HDR, text_size=uiSz, tooltip=hdrTip)
table.cell(tb, 0, 1, "", text_color=C_TXT, bgcolor=C_HDR, text_size=uiSz, tooltip=hdrTip)
table.cell(tb, 1, 1, "Tetrad", text_color=C_TXT, bgcolor=C_HDR, text_size=uiSz, tooltip=hdrTip)
table.cell(tb, 2, 1, "B&H", text_color=C_TXT, bgcolor=C_HDR, text_size=uiSz, tooltip=hdrTip)
table.cell(tb, 3, 1, queue, text_color=queueC, bgcolor=C_HDR, text_size=uiSz, tooltip=stTip)
f_rowBH(tb, 2, "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. Largest open basis so far (Peak$): " + f_dollar(on ? bk.peakBasis : na) + ".")
f_rowBH(tb, 3, "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_rowBH(tb, 4, "PnL", f_dollar(tot), f_dollar(hTot), f_sign(tot), f_sign(hTot), "Equity minus starting capital.")
f_rowBH(tb, 5, "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_rowBH(tb, 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: Tetrad " + f_pct(on ? bk.maxDD : na) + ", B&H " + f_pct(on ? hold.maxDD : na) + ". Average drop on the closes under water (AvgDD): Tetrad " + f_dollar(avgDD) + ", B&H " + f_dollar(hAvgDD) + ".")
f_rowBH(tb, 7, "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. Realized / Pain$ (R/P): " + f_num(rp) + ". Share of closes under water (UW%): Tetrad " + f_pct(uw) + ", B&H " + f_pct(hUw) + ".")
f_rowOne(tb, 2, "PF", f_num(pf), C_TXT, cycTip + " Gross cycle wins / gross cycle losses.")
f_rowOne(tb, 3, "Win%", f_pct(winRate), C_TXT, cycTip + " Winning cycles / closed cycles; breakevens in the denominator.")
f_rowOne(tb, 4, "W/L", str.tostring(cycWins) + "/" + str.tostring(cycLosses), C_TXT, cycTip + " Closed cycles: " + str.tostring(cycles) + ".")
f_rowOne(tb, 5, "$/Cyc", f_dollar(perCyc), f_sign(perCyc), cycTip + " Average net P&L per closed cycle.")
f_rowOne(tb, 6, "AvgW", f_dollar(avgW), C_GREEN, cycTip + " Average winning cycle.")
f_rowOne(tb, 7, "AvgL", f_dollar(avgL), C_RED, cycTip + " Average losing cycle.")
// ── ALERTS ───────────────────────────────────────────────────────────────────
string whSym = syminfo.prefix + ":" + syminfo.ticker
if dec == 1 and i_alertBuy
alert('{"engine": "Tetrad 1.3", "action": "BUY", "symbol": "' + whSym + '", "tf": "' + timeframe.period + '", "decision_close": ' + str.tostring(close) + ', "meter": ' + str.tostring(m, "0.00") + ', "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": "Tetrad 1.3", "action": "SELL", "symbol": "' + whSym + '", "tf": "' + timeframe.period + '", "decision_close": ' + str.tostring(close) + ', "meter": ' + str.tostring(m, "0.00") + ', "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, "Tetrad BUY", "{{ticker}} Tetrad BUY decided at the close {{close}}; fill at the next open")
alertcondition(dec == -1, "Tetrad SELL", "{{ticker}} Tetrad SELL decided at the close {{close}}; fill at the next open")
alertcondition(bullDiv, "Tetrad Bullish Divergence", "{{ticker}} Tetrad bullish divergence confirmed at {{close}}")
alertcondition(bearDiv, "Tetrad Bearish Divergence", "{{ticker}} Tetrad bearish 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.3, "Tetrad BUILD", display=display.data_window)
plot(v1, "Tetrad vote RSI", display=display.data_window)
plot(v2, "Tetrad vote Stochastic RSI", display=display.data_window)
plot(v3, "Tetrad vote MACD", display=display.data_window)
plot(v4, "Tetrad vote Bollinger", display=display.data_window)
plot(bullDiv ? 1 : bearDiv ? -1 : 0, "Tetrad Divergence (1 bull, -1 bear, at confirmation)", display=display.data_window)