PineTunnel

Fractalyst · library · 4139 行 · 点赞 33 · TradingView 原页

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

Pine Script

//@version=6
//@author=fractalyst
//@description PineTunnel re-implements TradingView's strategy.* broker emulator as a Pine v6 library, so indicator() scripts can backtest with strategy-grade execution: market, limit, stop and stop-limit entries, TP/SL/trailing brackets, OCA groups, pyramiding, reversals, process_orders_on_close, FIFO/LIFO closes, slippage, commission models, margin calls, currency conversion, the five strategy.risk.* guards, and intrabar O→H/L→C path processing. 114 exports mirror the strategy.* namespace one-to-one (dots → underscores) and were validated against the Strategy Tester with a dual-engine probe suite. Includes a 50+ metric analytics engine and on-chart performance table; the analytics derive from the author's own earlier open-source work.
library("PineTunnel", overlay = true, dynamic_requests = true)
// ═══════════════════════════════════════════════════════════════════════════════
// PineTunnel — indicator-side backtesting and order-execution engine
// ═══════════════════════════════════════════════════════════════════════════════
//
// PineTunnel re-implements the TradingView `strategy.*` broker emulator as a
// Pine v6 library. Consumer indicators keep full control of plotting while the
// engine reproduces strategy-grade fills: market / limit / stop / stop-limit
// entries, pyramiding, reversals, brackets (TP / SL / trailing), OCA groups,
// slippage, commissions, margin calls, currency conversion, the five
// `strategy.risk.*` guards, and intrabar path processing (O → H/L → C walk).
//
// FILE LAYOUT (top to bottom)
//   §1  Constants, configuration & core data types — PTConfig, Order,
//       ExitOrder, ClosedTrade, OpenTrade, PTEngine, makePTConfig, makePT
//   §2  Internal engine mechanics — exit-row bookkeeping, tick/lot rounding,
//       default sizing, FX rates, position refresh, leg lifecycle
//   §3  Order lifecycle & public order API — exit(), entry(), order(),
//       close(), close_all(), cancel(), cancel_all(), risk guards
//   §4  Exit levels, margin engine & intrabar walk — onBarPost(), _intrabarWalk()
//   §5  Bar driver — onBar(): rollover, fills, margin, MAE/MFE, equity
//   §6  Analytics engine — MTMStats computation + on-chart performance table
//   §7  Exported constants — TV-parity names (PT.long, PT.oca_cancel, …)
//   §8  Namespace accessors — the full `strategy.*` read surface (dots → underscores)
//
// EXECUTION MODEL (call order per bar)
//   PT.onBar(eng)             — advance the engine one bar. Call once per bar,
//                               before any order logic.
//   PT.entry()/order()/exit() — queue orders. They arm on the next bar (or
//                               fill at the signal bar's close when
//                               `process_orders_on_close` = true).
//   PT.<accessors>            — read state (opentrades, closedtrades, equity…).
//   PT.runDeeptest(eng)       — on the last confirmed history bar, render the
//                               performance table.
//
// MINIMAL EXAMPLE
//   import Fractalyst/PineTunnel/1 as PT
//   var PT.PTEngine eng = PT.makePT(PT.makePTConfig(initial_capital = 100000))
//   PT.onBar(eng)
//   if ta.crossover(close, ta.sma(close, 20))
//       PT.entry(eng, "long", PT.long)
//   PT.exit(eng, "x", from_entry = "long", stop = close * 0.97)
//   plot(PT.equity(eng))
//   PT.runDeeptest(eng)
//
// PARITY CONTRACT — inline comments marked "TV law" document observed
// TradingView broker-emulator behavior that this engine reproduces. They are
// load-bearing documentation: update them together with the logic they
// explain. Every exported member mirrors its `strategy.*` counterpart by
// name (dots → underscores) and semantics; hover docs quote the official
// Pine Script reference.
const float PT_QTY_EPS = 1e-9
// ── §1 · Constants, configuration & core data types ──────────────────────────
const float DEFAULT_RISK_FREE_RATE = 2.0
//@type PTConfig
//@description Backtest engine configuration. Mirrors the native `strategy()` declaration parameters.
export type PTConfig
    //@field initial_capital Starting capital of the backtest account.
    float initial_capital
    //@field default_qty_type "fixed" | "percent_of_equity" | "cash"
    string default_qty_type
    //@field default_qty_value Order size: contracts for "fixed", percent of equity for "percent_of_equity", cash for "cash".
    float default_qty_value
    //@field commission_type "percent" | "per_contract" | "cash_per_order" | "cash_per_trade"
    string commission_type
    //@field commission_value Commission size; percent for "percent", currency units otherwise.
    float commission_value
    //@field slippage in ticks (TV strategy() slippage is const int)
    int   slippage
    //@field pyramiding Maximum same-direction entries per position (0 behaves as 1).
    int   pyramiding
    //@field process_orders_on_close true = market orders fill at the signal bar's close instead of the next bar's open.
    bool  process_orders_on_close
    //@field direction_filter "both" | "long" | "short"
    string direction_filter
    //@field history_cap 0 = full history
    int   history_cap
    //@field mintick Symbol minimum price movement (tick size) used for all price rounding.
    float mintick
    //@field margin_long long margin % (100 = unleveraged, calls skipped)
    float margin_long
    //@field margin_short short margin % (ANY value > 0 can trigger calls)
    float margin_short
    //@field close_entries_rule "FIFO" (TV default) | "LIFO" — which leg closes first
    string close_entries_rule
    //@field fill_limits_assumption ticks: limit fills need price BETTER than the level by this × mintick (TV v4-era broker emulator; fill price unchanged; 0 = touch fills)
    float  fill_limits_assumption = 0.0
    //@field qty_step TV: symbol qty step; 0 = no flooring (engine keeps raw float)
    float  qty_step = 0.0
    //@field currency Account currency. "" (default) = resolve to syminfo.currency, mirroring TV strategy(currency = syminfo.currency)
    string currency = ""
    //@field risk_free_rate annual risk-free rate in PERCENT units, mirroring strategy(risk_free_rate = 2); engine converts to decimal at the stats boundary
    float risk_free_rate = 2.0
//@type Order
//@description A queued order (entry or persistent order).
export type Order
    //@field id Order id. Consumer ids are entry ids; "__close__"-prefixed ids are queued market closes.
    string id
    //@field dir 1 = long, -1 = short, 0 = market-close marker
    int    dir
    //@field qty na → default sizing
    float  qty
    //@field limit Limit price (na = not a limit order).
    float  limit
    //@field stop Stop price (na = not a stop order).
    float  stop
    //@field is_persistent true = strategy.order semantics
    bool   is_persistent
    //@field is_entry true = strategy.entry semantics (pyramiding + reversal)
    bool   is_entry
    //@field qty_percent default 100.0 (used by __close__ market orders)
    float  qty_percent
    //@field oca_name OCA group name ("" = none)
    string oca_name
    //@field oca_type 0 none, 1 cancel, 2 reduce
    int    oca_type
    //@field sl_triggered stop-limit two-phase: stop hit, limit leg pending
    bool   sl_triggered
    //@field sl_bar bar_index when sl_triggered armed; == current bar → limit fills at level (open precedes trigger), else open clamp
    int    sl_bar = -1
    //@field comment order comment (rides the fill into leg/trade forensics)
    string comment = ""
    //@field alert_message stored only; alert() emission is consumer-side per design
    string alert_message = ""
    //@field signal_equity frozen equity at signal bar (entry() call bar) for sizing
    float  signal_equity = na
    //@field signal_close frozen close at signal bar (entry() call bar) for sizing; overrides e.prev_close when not na
    float  signal_close = na
    //@field place_bar bar_index where the order was placed; limit/stop entries not evaluated on the same bar (TV: arms for next bar)
    int    place_bar = -1
//@type ExitOrder
//@description A pending exit order (stop, limit, trail or market close).
export type ExitOrder
    //@field id Bracket id. A same-id re-issue replaces the bracket in place.
    string id
    //@field from_entry "" = all legs
    string from_entry
    //@field qty na → qty_percent used
    float  qty
    //@field qty_percent default 100
    float  qty_percent
    //@field profit ticks relative TP
    float  profit
    //@field loss ticks relative SL
    float  loss
    //@field limit absolute TP (supersedes profit)
    float  limit
    //@field stop absolute SL (supersedes loss)
    float  stop
    //@field trail_price trailing stop activation price
    float  trail_price
    //@field trail_points trailing offset in ticks
    float  trail_points
    //@field trail_offset trailing stop offset in ticks
    float  trail_offset
    //@field t_legs per-trade trail state (na-safe parallel arrays; keyed by str.tostring(leg.seq) — one row per ENTRY FILL, not per entry_id)
    array<string> t_legs
    //@field t_act per-trade trail activation flags
    array<bool>   t_act
    //@field t_stop per-trade trail stop levels
    array<float>  t_stop
    //@field t_res per-trade qty reservations
    array<float>  t_res
    //@field t_init per-trade FROZEN original qty at row creation (qty_percent sizes from this, TV per-fill binding law)
    array<float>  t_init
    //@field t_used per-trade qty CONSUMED by fills (step-rounded actuals — later exits budget from t_init − t_used, not raw t_res)
    array<float>  t_used
    //@field t_fired per-trade fired state (qty_percent<100 child consumed for this entry fill — TV doesn't re-fire the same slice)
    array<bool>   t_fired
    //@field t_abar per-trade bar_index where the trail ARMED. Gap-through-open fills apply only to stops carried from an EARLIER bar (armed-and-persisted trail_triggered). A stop armed THIS bar fills at the level — the open precedes the arming step.
    array<int>    t_abar
    //@field oca_name OCA group name ("" = none)
    string oca_name = ""
    //@field oca_type 0 none, 1 cancel, 2 reduce
    int    oca_type = 0
    //@field comment exit comment (surfaced as ClosedTrade.exit_comment)
    string comment = ""
    //@field comment_profit Overrides `comment` on fills from profit/limit TP orders (TV v6 outcome comments)
    string comment_profit    = ""
    //@field comment_loss Overrides `comment` on fills from loss/stop SL orders
    string comment_loss      = ""
    //@field comment_trailing Overrides `comment` on fills from trail_price/trail_points stop orders
    string comment_trailing  = ""
    //@field alert_message stored only; alert() emission is consumer-side per design
    string alert_message = ""
    //@field alert_profit Overrides `alert_message` on profit/limit TP fills (stored only)
    string alert_profit      = ""
    //@field alert_loss Overrides `alert_message` on loss/stop SL fills (stored only)
    string alert_loss        = ""
    //@field alert_trailing Overrides `alert_message` on trail fills (stored only)
    string alert_trailing    = ""
    //@field place_bar bar_index where the exit was placed; not evaluated on the same onBar (process_orders_on_close=true signal-bar fill safety)
    int    place_bar = -1
    //@field re-placed bar — set on same-id replacement; onBarPost evaluates at that bar's close (TV: re-issued exits are fill-eligible same bar)
    int    repl_bar = -1
    //@field c_init frozen contracts = Σ original fills of from_entry, accumulated at row creation (TV stale-exit law: survives bound-leg death, drains FIFO across visible legs)
    float  c_init = 0.0
    //@field ever_fired true after any fill — stale-exit survival applies only to never-fired brackets
    bool   ever_fired = false
    //@field flat_gen_at_place engine flat-generation at placement — stale survival requires no flat/reversal transition since placement (TV cancels working exits when the position goes flat)
    int    flat_gen_at_place = -1
    //@field ever_bound true once this exit has bound at least one leg row (from_entry matched a live leg). TV law: an exit whose from_entry NEVER matched any entry dangles forever and can never fire — the stale-survivor path must require ever_bound (only exits whose legs DIED may survive and fire later).
    bool   ever_bound = false
    //@field fz_tp frozen TP level from the exit's OWN bound leg at last walk-scan refresh (relative profit recomputed tick-space from own leg avg — TV freezes bracket levels per binding; stale fills fire at this level after the bound leg dies)
    float  fz_tp = na
    //@field fz_sl frozen SL level (final, tick-rounded) from the exit's own bound leg at last refresh
    float  fz_sl = na
    //@field fz_slraw frozen raw SL level (pre-rounding; _exitStopPrice gap-through input)
    float  fz_slraw = na
    //@field fz_dir bound leg direction at last refresh (stale hit-test direction — own leg is gone when the stale fill fires)
    int    fz_dir = 0
    //@field prev_stop frozen stop level BEFORE a re-issue — TV law: the re-placement bar's intrabar path uses the OLD level; new level arms for next bar
    float  prev_stop = na
    //@field prev_loss frozen loss ticks BEFORE a re-issue (for relative SL recomputation from avg_price)
    float  prev_loss = na
//@type ClosedTrade
//@description A completed trade with entry/exit prices, times, profit and MAE/MFE.
export type ClosedTrade
    //@field entry_time Entry fill timestamp (Unix ms).
    int    entry_time
    //@field exit_time Exit fill timestamp (Unix ms).
    int    exit_time
    //@field entry_price Average entry price of the trade.
    float  entry_price
    //@field exit_price Average exit price of the trade.
    float  exit_price
    //@field qty positive
    float  qty
    //@field dir Trade direction: 1 = long, -1 = short.
    int    dir
    //@field profit excludes commission
    float  profit
    //@field profit_percent Net profit as percent of the entry cost basis, frozen at the trade's fill-time FX rate.
    float  profit_percent
    //@field commission entry+exit commissions of this trade
    float  commission
    //@field entry_id Entry order id.
    string entry_id
    //@field exit_id Exit order id (or closing entry id on same-bar reversals).
    string exit_id
    //@field entry_bar_index Chart bar_index of the entry fill.
    int    entry_bar_index = -1
    //@field exit_bar_index Chart bar_index of the exit fill.
    int    exit_bar_index  = -1
    //@field max_drawdown MAE in currency (positive), from entry to exit
    float  max_drawdown    = 0.0
    //@field max_runup MFE in currency (positive), from entry to exit
    float  max_runup       = 0.0
    //@field denom_at_close entry×qty×pointvalue×rate at close — percent accessors denominator, frozen at fill-time FX
    float  denom_at_close  = 0.0
    //@field entry_comment Comment of the entry order.
    string entry_comment   = ""
    //@field exit_comment Comment of the exit order.
    string exit_comment    = ""
//@type OpenTrade
//@description An open trade produced by a single entry fill. Maps 1:1 to `strategy.opentrades` — one entry per `strategy.opentrades(i)`.
export type OpenTrade
    //@field entry_id Entry order id that opened this leg.
    string entry_id
    //@field dir Leg direction: 1 = long, -1 = short.
    int    dir
    //@field qty Remaining open quantity of this leg.
    float  qty
    //@field avg_price Average entry price of this leg.
    float  avg_price
    //@field entry_time Entry fill timestamp (Unix ms).
    int    entry_time
    //@field entry_commission entry-side commission carried by this leg (split proportionally on partial closes)
    float  entry_commission
    //@field entry_bar_index bar the leg first opened (kept on merges/splits)
    int    entry_bar_index = -1
    //@field max_drawdown running max adverse excursion in currency (positive)
    float  max_drawdown   = 0.0
    //@field max_runup running max favorable excursion in currency (positive)
    float  max_runup      = 0.0
    //@field entry_comment comment of the entry order that opened this leg
    string entry_comment  = ""
    //@field seq unique per entry fill — exit rows key by this, not entry_id
    int    seq            = -1
    //@field entry_equity realized equity at the moment this leg opened
    float  entry_equity   = na
    //@field max_equity_before max realized equity before this leg opened
    float  max_equity_before = na
//@type PTEngine
//@description Backtest engine state. Tracks orders, open trades, closed trades, equity, risk guards, and margin. `openTrades` maps to `strategy.opentrades`.
export type PTEngine
    //@field cfg Engine configuration.
    PTConfig cfg
    //@field equity Realized equity (excludes open profit).
    float   equity
    //@field open_profit Unrealized P&L of the open position.
    float   open_profit
    //@field position_size signed
    float   position_size
    //@field position_avg_price Volume-weighted average entry price of the open position (na when flat).
    float   position_avg_price
    //@field wintrades Number of winning closed trades.
    int     wintrades
    //@field losstrades Number of losing closed trades.
    int     losstrades
    //@field eventrades Number of break-even closed trades.
    int     eventrades
    //@field grossprofit Sum of profits of all winning trades.
    float   grossprofit
    //@field grossloss Sum of losses of all losing trades (positive).
    float   grossloss
    //@field queue Pending orders — queued `strategy.entry`/`strategy.order` before fill (no direct `strategy.*` equiv).
    array<Order>       queue
    //@field exits Active exit brackets.
    array<ExitOrder>   exits
    //@field legs Open trades — array<OpenTrade> per-fill open trades (maps to `strategy.opentrades`; `array.size(legs)` == `strategy.opentrades`).
    array<OpenTrade>     legs
    //@field closed Closed trades — array<ClosedTrade> (maps to `strategy.closedtrades`; `array.size(closed)` == `strategy.closedtrades`).
    array<ClosedTrade> closed
    //@field equity_series Equity curve — per-bar `strategy.equity` (realized + open profit).
    array<float>       equity_series
    //@field bar_index Engine bar counter — increments once per onBar() call.
    int     bar_index
    //@field _bar_h (internal) current bar high, cached by onBar.
    float   _bar_h = na
    //@field _bar_l (internal) current bar low, cached by onBar.
    float   _bar_l = na
    //@field prev_close Close of the previous onBar() bar (default sizing reference).
    float   prev_close
    //@field _last_rate engine's most recent currency rate (opentrades accessors; account-currency marks)
    float   _last_rate  = 1.0
    //@field _bar_c last onBar close — ref price for opentrades profit/pct accessors (TV marks open trades at current bar)
    float   _bar_c      = na
    //@field _commission_total (internal) cumulative commissions paid.
    float   _commission_total
    //@field equity_peak running equity high (strategy.max_drawdown basis)
    float   equity_peak          = na
    //@field equity_trough running equity low (strategy.max_runup basis)
    float   equity_trough        = na
    //@field realized_equity_peak Running peak of realized equity.
    float   realized_equity_peak = na
    //@field realized_equity_trough Running trough of realized equity.
    float   realized_equity_trough = na
    //@field max_dd_value Largest equity drawdown seen (positive, currency).
    float   max_dd_value         = 0.0
    //@field max_dd_peak Equity peak from which max_dd_value was measured.
    float   max_dd_peak          = na
    //@field max_runup_value Largest equity run-up seen (positive, currency).
    float   max_runup_value      = 0.0
    //@field max_contracts_held_all Maximum total contracts held at any time.
    int     max_contracts_held_all   = 0
    //@field max_contracts_held_long Maximum long contracts held at any time.
    int     max_contracts_held_long  = 0
    //@field max_contracts_held_short Maximum short contracts held at any time.
    int     max_contracts_held_short = 0
    //@field position_entry_name id of the entry that opened the current position
    string  position_entry_name  = ""
    //@field flat_gen increments every time the leg book empties (flat transition) — stale-exit survival requires exit.flat_gen_at_place == this (TV cancels working exits at flat/reversal transitions)
    int     flat_gen             = 0
    //@field risk_halt_perm R1/R4 fired: cancel pending, close all, block new orders FOREVER
    bool    risk_halt_perm       = false
    //@field risk_halt_today R2/R3 fired: same teardown, clears at next day rollover
    bool    risk_halt_today      = false
    //@field risk_day calendar day id (t / 86400000) of the current bar
    int     risk_day             = -1
    //@field day_max_equity intraday peak equity (R2 basis, anchored at day start)
    float   day_max_equity       = na
    //@field day_start_equity equity at day start (R4 daily-P&L settlement basis)
    float   day_start_equity     = na
    //@field day_filled_orders filled-order events today (R3)
    int     day_filled_orders    = 0
    //@field consec_loss_days current run of straight losing days (R4)
    int     consec_loss_days     = 0
    //@field last_loss_day day id of the last losing day (R4 diagnostic)
    int     last_loss_day        = -1
    //@field risk_max_dd_value R1 limit (na = disabled)
    float   risk_max_dd_value    = na
    //@field risk_max_dd_is_pct R1: 1 = percent of equity, 0 = money
    int     risk_max_dd_is_pct   = 0
    //@field risk_intraday_value R2 limit (na = disabled)
    float   risk_intraday_value  = na
    //@field risk_intraday_is_pct R2: 1 = percent of max intraday equity, 0 = money
    int     risk_intraday_is_pct = 0
    //@field risk_max_filled_orders R3 cap (0 = disabled)
    int     risk_max_filled_orders = 0
    //@field risk_max_cons_loss R4 cap (0 = disabled)
    int     risk_max_cons_loss   = 0
    //@field risk_max_pos R5 entry() qty cap (na = disabled)
    float   risk_max_pos         = na
    //@field risk_alert_dd alert_message captured by risk_max_drawdown
    string  risk_alert_dd        = ""
    //@field risk_alert_id alert_message captured by risk_max_intraday_loss
    string  risk_alert_id        = ""
    //@field risk_alert_fo alert_message captured by risk_max_intraday_filled_orders
    string  risk_alert_fo        = ""
    //@field risk_alert_cl alert_message captured by risk_max_cons_loss_days
    string  risk_alert_cl        = ""
    //@field risk_last_alert the alert_message of the rule that fired last
    string  risk_last_alert      = ""
    //@field margin_call_count margin-call events fired
    int     margin_call_count    = 0
    //@field margin_liquidated_total units liquidated across all calls
    float   margin_liquidated_total = 0.0
    //@field mc_deferred deferred 1-lot MC pending to close
    bool    mc_deferred          = false
    //@field mc_deferred_short deferred call is on a short
    bool    mc_deferred_short    = false
    //@field _id P5: unique engine id (per-engine stats cache key; makePT assigns)
    int     _id                  = -1
    //@field _next_seq monotonic per-entry-fill sequence — exit rows key by this
    int     _next_seq            = 0
    //@field _first_close chart close at barstate.isfirst (Buy&Hold anchor)
    float   _first_close         = na
    //@field _spy_first SPY daily close at chart bar 0
    float   _spy_first           = na
    //@field _spy_last SPY daily close at last confirmed history bar
    float   _spy_last            = na
    //@field _spy_rets SPY daily bar-to-bar returns (beta benchmark)
    array<float> _spy_rets       = na
//@function makePTConfig
//@description Builds a `PTConfig` from the same properties as the native `strategy()` declaration.
//@param initial_capital Parameter `initial_capital`. Default: `1000000.0` (TV strategy() default)
//@param default_qty_type Parameter `default_qty_type`. Default: `"fixed"`
//@param default_qty_value Parameter `default_qty_value`. Default: `1.0`
//@param commission_type Parameter `commission_type`. Default: `"percent"`
//@param commission_value Parameter `commission_value`. Default: `0.0`
//@param slippage Parameter `slippage`. Default: `0`
//@param pyramiding Parameter `pyramiding`. Default: `0`
//@param process_orders_on_close Parameter `process_orders_on_close`. Default: `false`
//@param direction_filter Parameter `direction_filter`. Default: `"both"`
//@param history_cap Parameter `history_cap`. Default: `0`
//@param mintick Parameter `mintick`. Default: `1.0`
//@param margin_long Parameter `margin_long`. Default: `100.0`
//@param margin_short Parameter `margin_short`. Default: `100.0`
//@param close_entries_rule Parameter `close_entries_rule`. Default: `"FIFO"`
//@param fill_limits_assumption Parameter `fill_limits_assumption`. Default: `0.0`
//@param qty_step Parameter `qty_step`. Default: `0.0`
//@param currency Parameter `currency`. Default: `""` (follows syminfo.currency, TV default)
//@param risk_free_rate Parameter `risk_free_rate`. Default: `2.0` (PERCENT units, TV convention; engine converts to decimal)
//@returns PTConfig instance.
export makePTConfig(
     float  initial_capital        = 1000000.0,
     string default_qty_type       = "fixed",
     float  default_qty_value      = 1.0,
     string commission_type        = "percent",
     float  commission_value       = 0.0,
     int    slippage               = 0,
     int    pyramiding             = 0,
     bool   process_orders_on_close = false,
     string direction_filter       = "both",
     int    history_cap            = 0,
     float  mintick                = 1.0,
     float  margin_long            = 100.0,
     float  margin_short           = 100.0,
     string close_entries_rule     = "FIFO",
     float  fill_limits_assumption = 0.0,
     float  qty_step               = 0.0,
     string currency               = "",
     float  risk_free_rate         = 2.0) =>
    PTConfig.new(
         initial_capital, default_qty_type, default_qty_value,
         commission_type, commission_value, slippage, pyramiding,
         process_orders_on_close, direction_filter, history_cap, mintick,
         margin_long, margin_short, close_entries_rule, fill_limits_assumption, qty_step,
         currency, risk_free_rate)
//@function makePT
//@description Creates a `PTEngine` from a `PTConfig`. Mints a unique `_id` per engine for the `ptStats` per-engine cache. NOTE: the counter is a function-local `var` — unique per makePT() CALL SITE. CE10180 forbids exported functions from touching mutable globals, so a library-wide registry is impossible; all consumer scripts must create engines at a single makePT() call site (every in-repo consumer does).
//@param cfg Parameter `cfg`.
//@returns PTEngine instance with empty queues, no open trades and initial capital as equity.
export makePT(PTConfig cfg) =>
    var int _ptNextId = 0
    _ptNextId := _ptNextId + 1
    int newId = _ptNextId
    PTEngine.new(
         cfg = cfg,
         _id = newId,
         equity = cfg.initial_capital,
         open_profit = 0.0,
         position_size = 0.0,
         position_avg_price = na,
         wintrades = 0, losstrades = 0, eventrades = 0,
         grossprofit = 0.0, grossloss = 0.0,
         queue = array.new<Order>(),
         exits = array.new<ExitOrder>(),
         legs = array.new<OpenTrade>(),
         closed = array.new<ClosedTrade>(),
         equity_series = array.new<float>(),
         bar_index = -1,
         prev_close = na,
         _commission_total = 0.0,
         realized_equity_peak = cfg.initial_capital,
         realized_equity_trough = cfg.initial_capital,
         max_dd_peak = cfg.initial_capital,
         _spy_rets = array.new<float>())
// ── §2 · Internal engine mechanics ───────────────────────────────────────────
_rowOf(ExitOrder x, string seqKey) =>
    int idx = -1
    for i = 0 to (array.size(x.t_legs) == 0 ? na : array.size(x.t_legs) - 1)
        if array.get(x.t_legs, i) == seqKey
            idx := i
            break
    idx
_trailIdx(ExitOrder x, string seqKey) =>
    int idx = _rowOf(x, seqKey)
    if idx == -1
        array.push(x.t_legs, seqKey)
        array.push(x.t_act, false)
        array.push(x.t_stop, float(na))
        array.push(x.t_res, float(na))
        array.push(x.t_init, float(na))
        array.push(x.t_used, 0.0)
        array.push(x.t_fired, false)
        array.push(x.t_abar, -1)
        idx := array.size(x.t_legs) - 1
    idx
_resAt(ExitOrder x, int rIdx) =>
    float res = 0.0
    if rIdx >= 0 and array.size(x.t_res) > rIdx
        float rv = array.get(x.t_res, rIdx)
        res := na(rv) ? 0.0 : rv
    res
_resOr(ExitOrder x, int rIdx) =>
    float v = 0.0
    if rIdx >= 0
        float uv = array.get(x.t_used, rIdx)
        v := uv > 0.0 ? uv : _resAt(x, rIdx)
    v
_staleSurvives(PTEngine e, ExitOrder x) =>
    x.ever_bound and x.qty_percent >= 100.0 and x.from_entry != "" and x.oca_name == "" and
     na(x.trail_price) and na(x.trail_points) and na(x.trail_offset) and
     not x.ever_fired and x.c_init > PT_QTY_EPS and x.flat_gen_at_place == e.flat_gen and
     (na(x.qty) or x.qty > PT_QTY_EPS)
_stripLegRows(PTEngine e, string legId, string seqKey) =>
    if array.size(e.exits) > 0
        bool pendingEntry = false
        for od in e.queue
            if od.dir != 0
                pendingEntry := true
        for xi = array.size(e.exits) - 1 to 0
            ExitOrder x = array.get(e.exits, xi)
            int ri = _rowOf(x, seqKey)
            if ri >= 0
                bool spentRow = false
                if na(x.qty)
                    float used = array.get(x.t_used, ri)
                    float res  = array.get(x.t_res, ri)
                    bool matches = false
                    for lk in e.legs
                        if x.from_entry == "" or x.from_entry == lk.entry_id
                            matches := true
                    spentRow := res <= PT_QTY_EPS or used + PT_QTY_EPS >= res or not matches
                else
                    spentRow := true
                if spentRow
                    array.remove(x.t_legs, ri)
                    array.remove(x.t_act, ri)
                    array.remove(x.t_stop, ri)
                    array.remove(x.t_res, ri)
                    array.remove(x.t_init, ri)
                    array.remove(x.t_used, ri)
                    array.remove(x.t_fired, ri)
                    array.remove(x.t_abar, ri)
            if array.size(x.t_legs) == 0
                bool matches = false
                for lk in e.legs
                    if x.from_entry == "" or x.from_entry == lk.entry_id
                        matches := true
                bool pending = x.from_entry == "" and pendingEntry
                if not pending
                    for od in e.queue
                        if od.dir != 0 and od.id == x.from_entry
                            pending := true
                if not matches and not pending and not _staleSurvives(e, x)
                    array.remove(e.exits, xi)
_stepFloor(PTEngine e, float qty) =>
    if e.cfg.qty_step > 0
        float scale = math.round(1.0 / e.cfg.qty_step)
        math.floor(qty * scale) / scale
    else
        qty
_stepRoundQty(PTEngine e, float qty) =>
    if e.cfg.qty_step > 0
        float scale = math.round(1.0 / e.cfg.qty_step)
        float scaled = qty * scale
        float nearest = math.round(scaled)
        float lots = math.abs(scaled - nearest) <= scaled * 1.0e-12 + 1.0e-9 ? nearest : math.floor(scaled)
        lots / scale
    else
        qty
_reserveExits(PTEngine e) =>
    if array.size(e.exits) > 0 and array.size(e.legs) > 0
        for xi = 0 to array.size(e.exits) - 1
            ExitOrder x = array.get(e.exits, xi)
            for li = 0 to array.size(e.legs) - 1
                OpenTrade lg = array.get(e.legs, li)
                if x.from_entry == "" or x.from_entry == lg.entry_id
                    string seqKey = str.tostring(lg.seq)
                    int rIdx = _rowOf(x, seqKey)
                    if rIdx >= 0 and array.get(x.t_fired, rIdx)
                        continue
                    if rIdx == -1
                        rIdx := _trailIdx(x, seqKey)
                        array.set(x.t_init, rIdx, lg.qty)
                        array.set(x.t_fired, rIdx, false)
                        x.c_init += lg.qty
                        x.ever_bound := true
                    float earlierUsed = 0.0
                    if xi > 0
                        for xj = 0 to xi - 1
                            ExitOrder xo = array.get(e.exits, xj)
                            int uIdx = _rowOf(xo, seqKey)
                            if uIdx >= 0
                                earlierUsed += _resOr(xo, uIdx)
                    float initQty = array.get(x.t_init, rIdx)
                    float selfUsed = array.get(x.t_used, rIdx)
                    float requested = na(x.qty) ? (x.qty_percent >= 100.0 ? math.max(0.0, initQty - earlierUsed - selfUsed) : _stepRoundQty(e, initQty * math.min(x.qty_percent, 100.0) / 100.0)) : math.min(x.qty, math.max(0.0, initQty - earlierUsed - selfUsed))
                    array.set(x.t_res, rIdx, math.max(0.0, requested))
_consumeExitQty(PTEngine e, ExitOrder x, float q, string seqKey) =>
    x.ever_fired := true
    if not na(x.qty)
        x.qty := x.qty - q
        if x.qty <= PT_QTY_EPS and array.size(e.exits) > 0
            for i = array.size(e.exits) - 1 to 0
                if array.get(e.exits, i).id == x.id
                    array.remove(e.exits, i)
    else
        int rIdx = _rowOf(x, seqKey)
        if rIdx >= 0
            if x.qty_percent < 100.0
                array.set(x.t_fired, rIdx, true)
                array.set(x.t_res, rIdx, 0.0)
            else
                float res = _resAt(x, rIdx)
                float used = array.get(x.t_used, rIdx)
                if res <= PT_QTY_EPS or used + PT_QTY_EPS >= res
                    array.set(x.t_fired, rIdx, true)
                    array.set(x.t_res, rIdx, 0.0)
        bool legsRemain = false
        for lk in e.legs
            if x.from_entry == "" or x.from_entry == lk.entry_id
                legsRemain := true
        if not legsRemain and not _staleSurvives(e, x) and array.size(e.exits) > 0
            for i = array.size(e.exits) - 1 to 0
                if array.get(e.exits, i).id == x.id
                    array.remove(e.exits, i)
        na
_ocaReduce(PTEngine e, ExitOrder x, string seqKey, float overlap) =>
    if overlap > 0.0 and array.size(e.exits) > 0
        for xj = array.size(e.exits) - 1 to 0
            ExitOrder xo = array.get(e.exits, xj)
            if xo.id != x.id
                int rj = _rowOf(xo, seqKey)
                if rj >= 0 and _resAt(xo, rj) > 0.0
                    float left = math.max(0.0, _resAt(xo, rj) - overlap)
                    array.set(xo.t_res, rj, left)
                    if left <= PT_QTY_EPS
                        array.remove(xo.t_legs, rj)
                        array.remove(xo.t_act, rj)
                        array.remove(xo.t_stop, rj)
                        array.remove(xo.t_res, rj)
                        array.remove(xo.t_init, rj)
                        array.remove(xo.t_used, rj)
                        array.remove(xo.t_fired, rj)
                        array.remove(xo.t_abar, rj)
_ocaExitCancel(PTEngine e, ExitOrder x, string seqKey, float fillQty) =>
    if x.oca_name != "" and x.oca_type != 0 and array.size(e.exits) > 0
        for xj = array.size(e.exits) - 1 to 0
            ExitOrder xo = array.get(e.exits, xj)
            if xo.id != x.id and xo.oca_name == x.oca_name and xo.oca_type == x.oca_type
                int rj = _rowOf(xo, seqKey)
                if rj >= 0
                    if not array.get(xo.t_fired, rj)
                        if x.oca_type == 1
                            float dust = _stepRoundQty(e, math.max(0.0, _resAt(xo, rj) - fillQty))
                            array.set(xo.t_fired, rj, true)
                            array.set(xo.t_res, rj, dust)
                        else if x.oca_type == 2
                            float left = math.max(0.0, _resAt(xo, rj) - fillQty)
                            array.set(xo.t_res, rj, left)
                            if left <= PT_QTY_EPS
                                array.remove(xo.t_legs, rj)
                                array.remove(xo.t_act, rj)
                                array.remove(xo.t_stop, rj)
                                array.remove(xo.t_res, rj)
                                array.remove(xo.t_init, rj)
                                array.remove(xo.t_used, rj)
                                array.remove(xo.t_fired, rj)
                                array.remove(xo.t_abar, rj)
    0
_roundTick(PTEngine e, float price) =>
    if e.cfg.mintick > 0
        float scale = math.round(1.0 / e.cfg.mintick)
        math.round(math.round(price * scale, 7)) / scale
    else
        price
_roundTickDir(PTEngine e, float price, int legDir) =>
    if e.cfg.mintick > 0
        float scale = math.round(1.0 / e.cfg.mintick)
        legDir == 1 ? math.ceil(math.round(price * scale, 7)) / scale : math.floor(math.round(price * scale, 7)) / scale
    else
        price
_defaultQty(PTEngine e, float refPrice, int dir = 0, bool useRef = false, float signalClose = na) =>
    float slipPx = (useRef or dir == 0) ? 0.0 : e.cfg.slippage * e.cfg.mintick * dir
    float sizePrice = useRef ? refPrice : (not na(signalClose) ? signalClose : (na(e.prev_close) ? refPrice : e.prev_close))
    float eq = e.equity + e.open_profit
    float q = switch e.cfg.default_qty_type
        "fixed"             => e.cfg.default_qty_value
        "percent_of_equity" =>
            float cash = eq * e.cfg.default_qty_value * 0.01
            float reserved = e.cfg.commission_type == "percent" ? cash / (1.0 + e.cfg.commission_value / 100.0) : cash
            reserved / math.max(sizePrice + slipPx, 1e-10)
        "cash"              => e.cfg.default_qty_value / math.max(sizePrice, 1e-10)
        => e.cfg.default_qty_value
    _stepFloor(e, q)
_defaultQtyFrozen(PTEngine e, float frozenEq, float refPrice, int dir, bool useRef, float signalClose = na) =>
    float slipPx = (useRef or dir == 0) ? 0.0 : e.cfg.slippage * e.cfg.mintick * dir
    float sizePrice = useRef ? refPrice : (not na(signalClose) ? signalClose : (na(e.prev_close) ? refPrice : e.prev_close))
    float q = switch e.cfg.default_qty_type
        "fixed"             => e.cfg.default_qty_value
        "percent_of_equity" =>
            float cash = frozenEq * e.cfg.default_qty_value * 0.01
            float reserved = e.cfg.commission_type == "percent" ? cash / (1.0 + e.cfg.commission_value / 100.0) : cash
            reserved / math.max(sizePrice + slipPx, 1e-10)
        "cash"              => e.cfg.default_qty_value / math.max(sizePrice, 1e-10)
        => e.cfg.default_qty_value
    _stepFloor(e, q)
_snapEntryLimit(PTEngine e, float px, int dir) =>
    na(px) or e.cfg.mintick <= 0 ? px : dir == 1 ? math.floor(math.round(px * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick) : math.ceil(math.round(px * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick)
_snapEntryStop(PTEngine e, float px, int dir) =>
    na(px) or e.cfg.mintick <= 0 ? px : dir == 1 ? math.ceil(math.round(px * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick) : math.floor(math.round(px * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick)
_preComputeEntryQty(PTEngine e, float qty, int dir, float limit, float stop, float signalClose = na) =>
    na(qty) ? _defaultQty(e, not na(limit) ? _snapEntryLimit(e, limit, dir) : na, dir, not na(limit), signalClose) : qty
_placeOrModify(array<Order> q, Order o) =>
    bool replaced = false
    for i = 0 to (array.size(q) == 0 ? na : array.size(q) - 1)
        Order ex = array.get(q, i)
        if ex.id == o.id
            array.set(q, i, o)
            replaced := true
            break
    if not replaced
        array.push(q, o)
_rateForEngine(PTEngine e, float curr_rate) =>
    if not na(curr_rate)
        curr_rate
    else if na(e.cfg.currency) or e.cfg.currency == "" or syminfo.currency == e.cfg.currency
        1.0
    else
        float r = request.currency_rate(syminfo.currency, e.cfg.currency)
        na(r) ? 1.0 : r
_refreshPosition(PTEngine e, float refPrice, float rate, float pointvalue) =>
    float net = 0.0
    float notionalSum = 0.0
    float up = 0.0
    float longSum = 0.0
    float shortSum = 0.0
    for lg in e.legs
        float signed = lg.qty * lg.dir
        net += signed
        notionalSum += signed * lg.avg_price
        up += signed * (refPrice - lg.avg_price) * pointvalue * rate
        if lg.dir == 1
            longSum += lg.qty
        else
            shortSum += lg.qty
    e.position_size := net
    e.position_avg_price := net != 0 ? notionalSum / net : na
    e.open_profit := net != 0 ? up : 0.0
    // position_entry_name: "" when flat (mirrors strategy.position_entry_name)
    if net == 0
        e.position_entry_name := ""
    // Update max-contracts snapshot in the same pass — mirrors TV's
    // strategy.max_contracts_held and avoids a second leg walk in onBar's tail.
    e.max_contracts_held_all := math.max(e.max_contracts_held_all, int(math.abs(net)))
    e.max_contracts_held_long := math.max(e.max_contracts_held_long, int(longSum))
    e.max_contracts_held_short := math.max(e.max_contracts_held_short, int(shortSum))
// ── §3 · Order lifecycle & public order API ──────────────────────────────────
//@function exit
//@description Creates price-based orders to exit from an open position. If unfilled exit orders with the same id exist, calls to this command modify those orders. This command can generate more than one type of exit order, depending on the specified parameters. However, it does not create market orders. To exit from a position with a market order, use `strategy.close`() or `strategy.close_all`(). If a call to this command contains a profit or limit argument, it creates take-profit orders to exit from applicable trades at the determined price levels or better values (higher for long trades and lower for short ones). If the call contains loss or stop arguments, it creates stop-loss orders to exit from applicable trades at the determined levels or worse values (lower for long trades and higher for short ones). Calling this command with profit or limit and loss or stop arguments creates an order bracket with both order types. This command can create trailing stop orders when its call specifies a trail_price or trail_points argument and a trail_offset argument. A trailing stop order activates when the price moves trail_points ticks past the entry price or touches the trail_price level. Once activated, the stop follows trail_offset ticks behind the market price each time the trade's profit reaches a new high. The stop does not move when the trade does not achieve a new best value. Each call to this command reserves a portion of the position to close until the strategy fills or cancels its orders. For example, if there is an open position of 50 contracts and a `strategy.exit`() call specifies a qty of 20, that call's orders reserve 20 contracts out of the position. A second call can close a maximum of 30 contracts, even if its qty is 50 and one of its orders executes first. This behavior does not affect the orders from other commands, such as `strategy.close`() or `strategy.order`(). If a call to this command occurs before a created entry order's execution, the strategy waits and does not create the exit orders until after the entry order executes. Mirrors `strategy.exit()`.
//@param e Engine instance.
//@param id The identifier of the orders, which corresponds to an exit ID in the strategy's trades after an order fills. Strategy commands can reference the order ID to cancel or modify pending exit orders. The Strategy Tester and the chart display the order ID unless the command includes a comment* argument that applies to the filled order.
//@param from_entry Parameter `from_entry`. Default: `""`
//@param qty Optional. The number of contracts/lots/shares/units to close when an exit order fills. If specified, the command uses this value instead of qty_percent to determine the order size. The exit orders reserve this quantity from the position, meaning other calls to this command cannot close this portion until the strategy fills or cancels those orders. The default is na, which means the order size depends on the qty_percent value.
//@param qty_percent Parameter `qty_percent`. Default: `100`
//@param profit Optional. The take-profit distance, expressed in ticks. If specified, the command creates a limit order to exit the trade profit ticks away from the entry price in the favorable direction. The order executes at the calculated price or a better value. If this parameter and limit are not na, the command places a take-profit order only at the price level expected to trigger an exit first. The default is na.
//@param limit Optional. The take-profit price. If this parameter and profit are not na, the command places a take-profit order only at the price level expected to trigger an exit first. The default is na.
//@param loss Optional. The stop-loss distance, expressed in ticks. If specified, the command creates a stop order to exit the trade loss ticks away from the entry price in the unfavorable direction. The order executes at the calculated price or a worse value. If this parameter and stop are not na, the command places a stop-loss order only at the price level expected to trigger an exit first. The default is na.
//@param stop Optional. The stop-loss price. If this parameter and loss are not na, the command places a stop-loss order only at the price level expected to trigger an exit first. The default is na.
//@param trail_price Optional. The price of the trailing stop activation level. If the value is more favorable than the entry price, the command creates a trailing stop when the market price reaches that value. If less favorable than the entry price, the command creates the trailing stop immediately when the current market price is equal to or more favorable than the value. If this parameter and trail_points are not na, the command sets the activation level using the value expected to activate the stop first. The default is na.
//@param trail_points Optional. The trailing stop activation distance, expressed in ticks. If the value is positive, the command creates a trailing stop order when the market price moves trail_points ticks away from the trade's entry price in the favorable direction. If the value is negative, the command creates the trailing stop immediately when the market price is equal to or more favorable than the level trail_points ticks away from the entry price in the unfavorable direction. The default is na.
//@param trail_offset Optional. The trailing stop offset. When the market price reaches the activation level determined by the trail_price or trail_points parameter, or exceeds the level in the favorable direction, the command creates a trailing stop with an initial value trail_offset ticks away from that level in the unfavorable direction. After activation, the trailing stop moves toward the market price each time the trade's profit reaches a better value, maintaining the specified distance behind the best price. The default is na.
//@param comment Parameter `comment`. Default: `""`
//@param comment_profit Parameter `comment_profit`. Default: `""`
//@param comment_loss Parameter `comment_loss`. Default: `""`
//@param comment_trailing Parameter `comment_trailing`. Default: `""`
//@param alert_message Parameter `alert_message`. Default: `""`
//@param alert_profit Parameter `alert_profit`. Default: `""`
//@param alert_loss Parameter `alert_loss`. Default: `""`
//@param alert_trailing Parameter `alert_trailing`. Default: `""`
//@param disable_alert True → this exit's fills fire no alert payload: all stored alert_* fields are blanked (consumer emitters stay silent). Default false.
//@param oca_name OCA group name for the bracket. Default: `""` (no group)
//@param oca_type OCA group behavior: `0` none, `1` cancel siblings on fill, `2` reduce siblings. Default: `0`
//@returns None.
export exit(PTEngine e, string id, string from_entry = "", float qty = na, float qty_percent = 100, float profit = na, float limit = na, float loss = na, float stop = na, float trail_price = na, float trail_points = na, float trail_offset = na, string oca_name = "", int oca_type = 0, string comment = "", string comment_profit = "", string comment_loss = "", string comment_trailing = "", string alert_message = "", string alert_profit = "", string alert_loss = "", string alert_trailing = "", bool disable_alert = false) =>
    string _am = disable_alert ? "" : alert_message
    string _ap = disable_alert ? "" : alert_profit
    string _al = disable_alert ? "" : alert_loss
    string _at = disable_alert ? "" : alert_trailing
    ExitOrder x = ExitOrder.new(id, from_entry, qty, qty_percent, profit, loss, limit, stop, trail_price, trail_points, trail_offset, array.new<string>(), array.new<bool>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<bool>(), array.new<int>(), oca_name, oca_type, comment, comment_profit, comment_loss, comment_trailing, _am, _ap, _al, _at, e.bar_index + 1, -1, 0.0, false, e.flat_gen)
    bool replaced = false
    for i = 0 to (array.size(e.exits) == 0 ? na : array.size(e.exits) - 1)
        ExitOrder ex = array.get(e.exits, i)
        if ex.id == id
            for li = 0 to (array.size(e.legs) == 0 ? na : array.size(e.legs) - 1)
                OpenTrade lg = array.get(e.legs, li)
                if from_entry == "" or from_entry == lg.entry_id
                    string seqKey = str.tostring(lg.seq)
                    int oldIdx = _rowOf(ex, seqKey)
                    if oldIdx >= 0
                        int newIdx = _trailIdx(x, seqKey)
                        array.set(x.t_init, newIdx, array.get(ex.t_init, oldIdx))
                        array.set(x.t_used, newIdx, array.get(ex.t_used, oldIdx))
                        array.set(x.t_fired, newIdx, array.get(ex.t_fired, oldIdx))
                        array.set(x.t_abar, newIdx, array.get(ex.t_abar, oldIdx))
            if ex.flat_gen_at_place == e.flat_gen
                x.c_init := ex.c_init
                x.ever_fired := ex.ever_fired
                x.ever_bound := ex.ever_bound
            else
                x.c_init := 0.0
                x.ever_fired := false
                x.ever_bound := false
            // TV law: a same-(id,from_entry) re-issue REPLACES in place.
            // The re-placement bar's INTRABAR path stays governed by the OLD
            // level (stashed in prev_stop/prev_loss) — the new level arms for
            // the next bar's walk. place_bar keeps the ORIGINAL (walk ordering).
            x.prev_stop := ex.stop
            x.prev_loss := ex.loss
            x.place_bar := ex.place_bar
            x.repl_bar := e.bar_index + 1
            array.set(e.exits, i, x)
            replaced := true
            break
    if not replaced
        array.push(e.exits, x)
    _reserveExits(e)
_commission(PTEngine e, float price, float qty, float rate) =>
    float notional = price * qty * rate
    switch e.cfg.commission_type
        "percent"              => notional * e.cfg.commission_value / 100.0
        "per_contract"         => math.abs(qty) * e.cfg.commission_value
        "cash_per_contract"    => math.abs(qty) * e.cfg.commission_value
        "cash_per_order"       => e.cfg.commission_value
        "cash_per_trade"       => 0.0
        => 0.0
_fillPrice(PTEngine e, float openPx, int dir) =>
    if e.cfg.slippage == 0
        openPx
    else
        float scale = math.round(1.0 / e.cfg.mintick)
        // TV law: tick count comes from TRUE DIVISION (price / mintick);
        // the multiply form flips boundary fills a full tick to float noise.
        float ticks = math.floor(openPx / e.cfg.mintick + 0.5)
        dir >= 0 ? (ticks + e.cfg.slippage) / scale : (ticks - e.cfg.slippage) / scale
_openLeg(PTEngine e, Order od, float fillPrice, int t, float comm) =>
    e._next_seq += 1
    // position_entry_name: the entry that OPENED the position (flat book
    // before this fill) — mirrors strategy.position_entry_name.
    if array.size(e.legs) == 0
        e.position_entry_name := od.id
    e.realized_equity_peak := na(e.realized_equity_peak) ? e.equity : math.max(e.realized_equity_peak, e.equity)
    // TV lot law: explicit qty is re-floored to the mincontract grid by the
    // TV engine itself (division form, not multiply — ULP-tie safety).
    float legQty = od.qty
    if e.cfg.qty_step > 0
        // TV lot law: the grid floor is ULP-TOLERANT (a value within ε of the
        // grid snaps up, never shaves a full lot). _stepRoundQty implements the
        // snap-then-floor behavior.
        legQty := _stepRoundQty(e, od.qty)
    array.push(e.legs, OpenTrade.new(od.id, od.dir, legQty, fillPrice, t, comm, e.bar_index, 0.0, 0.0, od.comment, e._next_seq, e.equity, e.realized_equity_peak))
_closeLeg(PTEngine e, int legIdx, float fillPrice, int t, string exitId, float rate, float pointvalue, string exitComment = "", bool deferComm = false, int closerDir = 0) =>
    OpenTrade lg = array.get(e.legs, legIdx)
    float adverse = lg.dir == 1 ? lg.avg_price - fillPrice : fillPrice - lg.avg_price
    if adverse > 0
        lg.max_drawdown := math.max(lg.max_drawdown, lg.qty * adverse * pointvalue * rate)
    float favorable = lg.dir == 1 ? fillPrice - lg.avg_price : lg.avg_price - fillPrice
    if favorable > 0
        lg.max_runup := math.max(lg.max_runup, lg.qty * favorable * pointvalue * rate)
    float profit = (fillPrice - lg.avg_price) * lg.qty * lg.dir * pointvalue * rate
    float exitComm = _commission(e, fillPrice, lg.qty, rate)
    float cashComm = e.cfg.commission_type == "cash_per_trade" ? e.cfg.commission_value : 0.0
    float recComm = exitComm + cashComm + lg.entry_commission
    float netProfit = profit - exitComm - cashComm - lg.entry_commission
    float pp = lg.avg_price > 0 ? netProfit / (lg.avg_price * lg.qty * pointvalue * rate) * 100.0 : 0.0
    float denomAtClose = lg.avg_price * lg.qty * pointvalue * rate
    bool _sw = closerDir != 0 and lg.dir != closerDir
    array.push(e.closed, ClosedTrade.new(lg.entry_time, t, lg.avg_price, fillPrice, lg.qty, _sw ? closerDir : lg.dir, netProfit, pp, recComm, _sw ? exitId : lg.entry_id, _sw ? lg.entry_id : exitId, lg.entry_bar_index, e.bar_index, lg.max_drawdown, lg.max_runup, denomAtClose, lg.entry_comment, exitComment))
    e._commission_total += exitComm + cashComm
    if netProfit > 0
        e.wintrades += 1
        e.grossprofit += netProfit
    else if netProfit < 0
        e.losstrades += 1
        e.grossloss += math.abs(netProfit)
    else
        e.eventrades += 1
    if deferComm
        e.equity += profit
    else
        e.equity += profit - exitComm - cashComm
    e.realized_equity_peak := na(e.realized_equity_peak) ? e.equity : math.max(e.realized_equity_peak, e.equity)
    e.realized_equity_trough := na(e.realized_equity_trough) ? e.equity : math.min(e.realized_equity_trough, e.equity)
    float legDD = not na(lg.max_equity_before) and not na(lg.entry_equity) ? lg.max_equity_before - (lg.entry_equity - lg.max_drawdown) : na
    if not na(legDD) and legDD > e.max_dd_value
        e.max_dd_value := legDD
        e.max_dd_peak := lg.max_equity_before
    bool lastOfSeq = true
    for mi = 0 to (array.size(e.legs) == 0 ? na : array.size(e.legs) - 1)
        if mi != legIdx and array.get(e.legs, mi).seq == lg.seq
            lastOfSeq := false
    array.remove(e.legs, legIdx)
    if array.size(e.legs) == 0
        e.flat_gen += 1
    if lastOfSeq
        _stripLegRows(e, lg.entry_id, str.tostring(lg.seq))
    deferComm ? exitComm + cashComm : 0.0
// ── Risk guard helpers (declared before all call sites — Pine order law) ──
_riskBlocked(PTEngine e) => e.risk_halt_perm or e.risk_halt_today
_closedNet(PTEngine e) =>
    float s = 0.0
    for tr in e.closed
        s += tr.profit
    s
_opOpenDenom(PTEngine e, OpenTrade lg) =>
    lg.avg_price * lg.qty * syminfo.pointvalue * e._last_rate
_riskIntradayHalt(PTEngine e, float px, int t, float rate, float pointvalue, string alertMsg = "", string exitId = "risk") =>
    e.risk_last_alert := alertMsg
    e.risk_halt_today := true
    array.clear(e.queue)
    array.clear(e.exits)
    while array.size(e.legs) > 0
        _closeLeg(e, 0, px, t, exitId, rate, pointvalue, exitId)
_riskPermHalt(PTEngine e, float px, int t, float rate, float pointvalue, string alertMsg = "") =>
    e.risk_last_alert := alertMsg
    e.risk_halt_perm := true
    e.risk_halt_today := true
    array.clear(e.queue)
    array.clear(e.exits)
    while array.size(e.legs) > 0
        _closeLeg(e, 0, px, t, "risk", rate, pointvalue, "risk")
_countFill(PTEngine e, float px, int t, float rate, float pointvalue) =>
    e.day_filled_orders += 1
    if e.risk_max_filled_orders > 0 and e.day_filled_orders >= e.risk_max_filled_orders and not _riskBlocked(e)
        _riskIntradayHalt(e, px, t, rate, pointvalue, e.risk_alert_fo)
// TV law: R2 max_intraday_loss (cash type) measures how far equity has
// fallen below the DAY'S START equity (day_start - current), NOT the
// drawdown from the intraday peak (day_max - current). Percent type keeps
// the peak-drawdown basis (day_max - current). Applies to every R2
// cash-type guard.
_riskCheckIntraday(PTEngine e, float px, int t, float rate, float pointvalue) =>
    if not e.risk_halt_perm and not e.risk_halt_today and not na(e.risk_intraday_value) and array.size(e.legs) > 0
        float mvs = 0.0
        float spent = 0.0
        float net = 0.0
        for lg in e.legs
            mvs += lg.qty * px
            spent += lg.qty * lg.avg_price
            net += lg.qty * lg.dir
        float openP = net == 0 ? 0.0 : (net > 0 ? mvs - spent : spent - mvs)
        float eqPx = e.equity + openP
        // The intraday peak is anchored at the day's start equity: a na peak
        // initializes to day_start, not the current mark.
        float _anchor = na(e.day_start_equity) ? eqPx : e.day_start_equity
        e.day_max_equity := na(e.day_max_equity) ? math.max(_anchor, eqPx) : math.max(e.day_max_equity, eqPx)
        float idLimit = e.risk_intraday_is_pct == 1 ? e.day_max_equity * e.risk_intraday_value / 100.0 : e.risk_intraday_value
        float _r2loss = e.risk_intraday_is_pct == 1 ? (e.day_max_equity - eqPx) : ((na(e.day_start_equity) ? _anchor : e.day_start_equity) - eqPx)
        if _r2loss >= idLimit and idLimit > 0
            if e.risk_intraday_is_pct == 1 and eqPx <= 0
                _riskPermHalt(e, px, t, rate, pointvalue, e.risk_alert_id)
            else
                _riskIntradayHalt(e, px, t, rate, pointvalue, e.risk_alert_id, "Close Position (Max intraday Loss)")
// Intrabar R2 evaluation at walk nodes, WITHOUT ratcheting day_max (the peak
// is close-anchored; ratcheting at intrabar nodes would inflate it on spike
// bars). Runs even on rollover bars: day_max may be na at the walk, so it is
// anchored to day_start first.
_riskCheckIntradayNoPeak(PTEngine e, float px, int t, float rate, float pointvalue) =>
    if not e.risk_halt_perm and not e.risk_halt_today and not na(e.risk_intraday_value) and array.size(e.legs) > 0
        float mvs = 0.0
        float spent = 0.0
        float net = 0.0
        for lg in e.legs
            mvs += lg.qty * px
            spent += lg.qty * lg.avg_price
            net += lg.qty * lg.dir
        float openP = net == 0 ? 0.0 : (net > 0 ? mvs - spent : spent - mvs)
        float eqPx = e.equity + openP
        if na(e.day_max_equity)
            float _anchor = na(e.day_start_equity) ? eqPx : e.day_start_equity
            e.day_max_equity := math.max(_anchor, eqPx)
        float idLimit = e.risk_intraday_is_pct == 1 ? e.day_max_equity * e.risk_intraday_value / 100.0 : e.risk_intraday_value
        float _r2loss = e.risk_intraday_is_pct == 1 ? (e.day_max_equity - eqPx) : ((na(e.day_start_equity) ? e.day_max_equity : e.day_start_equity) - eqPx)
        if _r2loss >= idLimit and idLimit > 0
            if e.risk_intraday_is_pct == 1 and eqPx <= 0
                _riskPermHalt(e, px, t, rate, pointvalue, e.risk_alert_id)
            else
                _riskIntradayHalt(e, px, t, rate, pointvalue, e.risk_alert_id, "Close Position (Max intraday Loss)")
_closeMarketNow(PTEngine e, Order od, float px, int t, float curr_rate, float pointvalue) =>
    string target = str.replace(od.id, "__close__", "")
    float closeQty = od.qty
    bool closedAny = false
    if array.size(e.legs) > 0
        bool lifo = e.cfg.close_entries_rule == "LIFO"
        int li = lifo ? array.size(e.legs) - 1 : 0
        while (lifo ? li >= 0 : li < array.size(e.legs)) and (na(closeQty) or closeQty > PT_QTY_EPS)
            OpenTrade lg = array.get(e.legs, li)
            if target == "" or lg.entry_id == target
                float q = na(closeQty) ? _stepFloor(e, lg.qty * od.qty_percent / 100.0) : math.min(closeQty, lg.qty)
                float fillPx = _fillPrice(e, px, -lg.dir)
                string _tvCloseComment = od.comment == "" ? "Close entry(s) order " + target : od.comment
                if na(closeQty) or q >= lg.qty
                    _closeLeg(e, li, fillPx, t, "close", curr_rate, pointvalue, _tvCloseComment)
                    li += lifo ? -1 : 0
                else
                    float ecPart = lg.entry_commission * q / lg.qty
                    float maePart = lg.max_drawdown * q / lg.qty
                    float mfePart = lg.max_runup * q / lg.qty
                    array.set(e.legs, li, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - q, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                    array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, q, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                    _closeLeg(e, array.size(e.legs) - 1, fillPx, t, "close", curr_rate, pointvalue, od.comment)
                    li += lifo ? -1 : 1
                closedAny := true
                closeQty := na(closeQty) ? na : closeQty - q
            else
                li += lifo ? -1 : 1
    if closedAny
        _countFill(e, px, t, curr_rate, pointvalue)
_firstCloseIdx(PTEngine e) =>
    e.cfg.close_entries_rule == "LIFO" ? array.size(e.legs) - 1 : 0
_openLegRaw(PTEngine e, string id, int dir, float qty, float fillPrice, int t, float rate, float pointvalue, string comment = "", string alert_message = "") =>
    float remaining = qty
    while remaining > 0
        int ci = _firstCloseIdx(e)
        if array.size(e.legs) == 0 or array.get(e.legs, ci).dir == dir
            break
        OpenTrade lg = array.get(e.legs, ci)
        if remaining >= lg.qty
            _closeLeg(e, ci, fillPrice, t, id, rate, pointvalue, comment)
            remaining -= lg.qty
        else
            float ecPart = lg.entry_commission * remaining / lg.qty
            float maePart = lg.max_drawdown * remaining / lg.qty
            float mfePart = lg.max_runup * remaining / lg.qty
            array.set(e.legs, ci, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - remaining, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
            array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, remaining, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
            _closeLeg(e, array.size(e.legs) - 1, fillPrice, t, id, rate, pointvalue, comment)
            remaining := 0
    if remaining > 0
        _openLeg(e, Order.new(id, dir, remaining, na, na, false, true, 100.0, "", 0, false, -1, comment, alert_message, na), fillPrice, t, _commission(e, fillPrice, remaining, rate))
_liveNet(PTEngine e) =>
    float net = 0.0
    for lg in e.legs
        net += lg.qty * lg.dir
    net
_ocaSiblings(PTEngine e, Order filled, float q, float px) =>
    if filled.oca_name != "" and filled.oca_type != 0 and array.size(e.queue) > 0
        for i = array.size(e.queue) - 1 to 0
            Order od = array.get(e.queue, i)
            if od.id != filled.id and od.oca_name == filled.oca_name and od.oca_type == filled.oca_type
                if filled.oca_type == 1
                    array.remove(e.queue, i)
                else if filled.oca_type == 2
                    od.qty := (na(od.qty) ? _defaultQty(e, px, od.dir, false, od.signal_close) : od.qty) - q
                    if od.qty <= PT_QTY_EPS
                        array.remove(e.queue, i)
_fillEntryOrder(PTEngine e, Order od, float px, int t, float rate, float pointvalue) =>
    bool filled = false
    bool _useRef = not na(od.limit)
    if od.is_entry
        float ln = _liveNet(e)
        bool opposite = ln != 0 and math.sign(ln) != od.dir
        if opposite
            float _frozenEq = not na(od.signal_equity) ? od.signal_equity : e.equity + e.open_profit
            if na(od.qty) and e.cfg.process_orders_on_close
                _refreshPosition(e, px, rate, pointvalue)
            float _sizeEq = e.cfg.process_orders_on_close ? e.equity + e.open_profit : _frozenEq
            // TV law: default sizing uses the FILL price (px), not prev_close.
            // od.signal_close (frozen at signal bar) takes precedence if set.
            float _revQty = na(od.qty) ? _defaultQtyFrozen(e, _sizeEq, px, od.dir, _useRef, na(od.signal_close) ? px : od.signal_close) : od.qty
            while array.size(e.legs) > 0
                // TV same-bar cross law: when a BUY
                // entry fill closes a SHORT leg that entered on the SAME bar,
                // the closed-trade row is booked from the long side:
                // (entry_id=buy order, exit_id=short leg, dir=+1) — regardless
                // of placement order, exactness, or leg count. Sells closing
                // same-bar longs already book (long leg, sell order). Later-bar
                // closes by opposite entries book normal (leg, closer).
                OpenTrade _cl = array.get(e.legs, _firstCloseIdx(e))
                bool _xswap = od.dir == 1 and _cl.dir == -1 and _cl.entry_bar_index == e.bar_index
                _closeLeg(e, _firstCloseIdx(e), px, t, od.id, rate, pointvalue, od.comment, false, _xswap ? 1 : 0)
            float q = _revQty
            // R5: entry() clamps against max_position_size; if even the min qty
            // violates the cap the order is REJECTED (not filled). Raw order()
            // path below is exempt (TV locks this). Reversal closed first, so
            // live net is 0 here — room is the full cap.
            if not na(e.risk_max_pos) and e.risk_max_pos > 0
                q := math.min(q, e.risk_max_pos)
            _refreshPosition(e, px, rate, pointvalue)
            float _mr = (od.dir == 1 ? e.cfg.margin_long : e.cfg.margin_short) / 100.0
            if q > PT_QTY_EPS and _mr > 0.0
                float _needed = math.abs(q * od.dir) * px * pointvalue * _mr
                float _eq = e.equity + e.open_profit
                if _needed - _eq > math.abs(_eq) * 1e-11
                    q := 0.0
            if q > PT_QTY_EPS
                float comm = _commission(e, px, q, rate)
                e.equity -= comm
                e._commission_total += comm
                _openLeg(e, Order.new(od.id, od.dir, q, na, na, false, true, 100.0, "", 0, false, -1, od.comment, od.alert_message, od.signal_close), px, t, comm)
                _ocaSiblings(e, od, q, px)
                _countFill(e, px, t, rate, pointvalue)
            filled := true
        else
            int sameDirEntries = 0
            bool sameIdLeg = false
            for lg in e.legs
                if lg.dir == od.dir
                    sameDirEntries += 1
                if lg.entry_id == od.id
                    sameIdLeg := true
            // Pyramiding: N allows N same-direction entries; the (N+1)-th is
            // rejected. Uniform across market, limit and stop fills.
            if sameDirEntries >= math.max(e.cfg.pyramiding, 1) and not sameIdLeg
                filled := true
            else
                float _frozenEqP = not na(od.signal_equity) ? od.signal_equity : e.equity + e.open_profit
                if na(od.qty) and e.cfg.process_orders_on_close
                    _refreshPosition(e, px, rate, pointvalue)
                    _frozenEqP := e.equity + e.open_profit
                float _sizeEqP = _frozenEqP
                float q = na(od.qty) ? _defaultQtyFrozen(e, _sizeEqP, px, od.dir, _useRef, na(od.signal_close) ? px : od.signal_close) : od.qty
                // R5 clamp: entry() total |position| may not exceed the cap;
                // no room left → reject (TV: minimum-qty violation).
                if not na(e.risk_max_pos) and e.risk_max_pos > 0
                    float room = e.risk_max_pos - math.abs(ln)
                    q := room <= PT_QTY_EPS ? 0.0 : math.min(q, room)
                float _mr = (od.dir == 1 ? e.cfg.margin_long : e.cfg.margin_short) / 100.0
                if q > PT_QTY_EPS and _mr > 0.0
                    float _needed = math.abs(ln + q * od.dir) * px * pointvalue * _mr
                    float _eq = e.equity + e.open_profit
                    if _needed - _eq > math.abs(_eq) * 1e-11
                        q := 0.0
                if q > PT_QTY_EPS
                    float comm = _commission(e, px, q, rate)
                    e.equity -= comm
                    e._commission_total += comm
                    _openLeg(e, Order.new(od.id, od.dir, q, na, na, false, true, 100.0, "", 0, false, -1, od.comment, od.alert_message, od.signal_close), px, t, comm)
                    _ocaSiblings(e, od, q, px)
                    _countFill(e, px, t, rate, pointvalue)
                filled := true
    else
        float _frozenEqO = not na(od.signal_equity) ? od.signal_equity : e.equity + e.open_profit
        float q = na(od.qty) ? _defaultQtyFrozen(e, _frozenEqO, px, od.dir, _useRef, na(od.signal_close) ? px : od.signal_close) : od.qty
        float comm = _commission(e, px, q, rate)
        e.equity -= comm
        e._commission_total += comm
        _openLegRaw(e, od.id, od.dir, q, px, t, rate, pointvalue, od.comment)
        _ocaSiblings(e, od, q, px)
        _countFill(e, px, t, rate, pointvalue)
        filled := true
    filled
//@function order
//@description Creates a new order to open, add to, or exit from a position. If an unfilled order with the same id exists, a call to this command modifies that order. The resulting order's type depends on the limit and stop parameters. If the call does not contain limit or stop arguments, it creates a market order that executes on the next tick. If the call specifies a limit value but no stop value, it places a limit order that executes after the market price reaches the limit value or a better price (lower for buy orders and higher for sell orders). If the call specifies a stop value but no limit value, it places a stop order that executes after the market price reaches the stop value or a worse price (higher for buy orders and lower for sell orders). If the call contains limit and stop arguments, it creates a stop-limit order, which generates a limit order at the limit price only after the market price reaches the stop value or a worse price. Orders from this command, unlike those from `strategy.entry`(), are not affected by the pyramiding parameter of the strategy() declaration statement. Strategies can open any number of trades in the same direction with calls to this function. This command does not automatically reverse open positions because it does not exclusively create entry orders like `strategy.entry`() does. For example, if there is an open long position of five shares, an order from this command with a qty of 5 and a direction of `strategy.short` triggers the sale of five shares, which closes the position. In PineTunnel, market orders fill at the next bar's open, or at the signal bar's close when `process_orders_on_close` = true. Mirrors `strategy.order()`.
//@param e Engine instance.
//@param id The identifier of the order, which corresponds to an entry or exit ID in the strategy's trades after the order fills. If the strategy opens a new position after filling the order, the order's ID becomes the `strategy.position_entry_name` value. Strategy commands can reference the order ID to cancel or modify pending orders and generate exit orders for specific open trades. The Strategy Tester and the chart display the order ID unless the command specifies a comment value.
//@param dir Parameter `dir`.
//@param qty Optional. The number of contracts/shares/lots/units to trade when the order fills. The default is na, which means that the command uses the default_qty_type and default_qty_value parameters of the strategy() declaration statement to determine the quantity.
//@param limit Optional. The limit price of the order. If specified, the command creates a limit or stop-limit order, depending on whether the stop value is also specified. The default is na, which means the resulting order is not of the limit or stop-limit type.
//@param stop Optional. The stop price of the order. If specified, the command creates a stop or stop-limit order, depending on whether the limit value is also specified. The default is na, which means the resulting order is not of the stop or stop-limit type.
//@param oca_name Parameter `oca_name`. Default: `""`
//@param oca_type Parameter `oca_type`. Default: `0`
//@param comment Parameter `comment`. Default: `""`
//@param alert_message Parameter `alert_message`. Default: `""`
//@returns None.
//@param disable_alert True → this order's fills fire no alert payload (stored message blanked). Default: `false`.
//@param signal_close Optional. Frozen close of the signal bar for equity marking/sizing. Default: `na` (uses `e.prev_close`).
export order(PTEngine e, string id, int dir, float qty = na, float limit = na, float stop = na, string oca_name = "", int oca_type = 0, string comment = "", string alert_message = "", bool disable_alert = false, float signal_close = na) =>
    if _riskBlocked(e)
        bool(na)
    else if e.cfg.direction_filter == "long" and dir == -1
        bool(na)
    else if e.cfg.direction_filter == "short" and dir == 1
        bool(na)
    else
        string _alertStored = disable_alert ? "" : alert_message
        if not na(signal_close)
            _refreshPosition(e, signal_close, _rateForEngine(e, na), syminfo.pointvalue)
        // TV law: process_orders_on_close=true → MARKET orders fill at the CLOSE
        // of the signal bar, but AFTER the intrabar walk evaluates exits. Queue
        // the order so onBar's walk runs first. Limit/stop entries always queue.
        // TV law: default sizing (qty=na) uses the FILL price. Defer sizing to
        // fill time for market orders under POOC (same as entry()).
        bool _deferSizeO = e.cfg.process_orders_on_close and na(limit) and na(stop) and na(qty)
        float _qtyAtPlaceO = _deferSizeO ? qty : _preComputeEntryQty(e, qty, dir, limit, stop, signal_close)
        _placeOrModify(e.queue, Order.new(id, dir, _qtyAtPlaceO, _snapEntryLimit(e, limit, dir), _snapEntryStop(e, stop, dir), true, false, 100.0, oca_name, oca_type, false, -1, comment, _alertStored, e.equity + e.open_profit, signal_close, e.bar_index + 1))
        true
 
//@function entry
//@description Creates a new order to open or add to a position. If an unfilled order with the same id exists, a call to this command modifies that order. The resulting order's type depends on the limit and stop parameters. If the call does not contain limit or stop arguments, it creates a market order that executes on the next tick. If the call specifies a limit value but no stop value, it places a limit order that executes after the market price reaches the limit value or a better price (lower for buy orders and higher for sell orders). If the call specifies a stop value but no limit value, it places a stop order that executes after the market price reaches the stop value or a worse price (higher for buy orders and lower for sell orders). If the call contains limit and stop arguments, it creates a stop-limit order, which generates a limit order at the limit price only after the market price reaches the stop value or a worse price. Orders from this command, unlike those from `strategy.order`(), are affected by the pyramiding parameter of the strategy() declaration statement. Pyramiding specifies the number of concurrent open entries allowed per position. For example, with pyramiding = 3, the strategy can have up to three open trades, and the command cannot create orders to open additional trades until at least one existing trade closes. By default, when a strategy executes an order from this command in the opposite direction of the current market position, it reverses that position. For example, if there is an open long position of five shares, an order from this command with a qty of 5 and a direction of `strategy.short` triggers the sale of 10 shares to close the long position and open a new five-share short position. Users can change this behavior by specifying an allowed direction with the `strategy.risk_allow_entry_in`() function. In PineTunnel, market orders fill at the next bar's open, or at the signal bar's close when `process_orders_on_close` = true. Mirrors `strategy.entry()`.
//@param e Engine instance.
//@param id The identifier of the order, which corresponds to an entry ID in the strategy's trades after the order fills. If the strategy opens a new position after filling the order, the order's ID becomes the `strategy.position_entry_name` value. Strategy commands can reference the order ID to cancel or modify pending orders and generate exit orders for specific open trades. The Strategy Tester and the chart display the order ID unless the command specifies a comment value.
//@param dir Parameter `dir`.
//@param qty Optional. The number of contracts/shares/lots/units in the resulting open trade when the order fills. The default is na, which means that the command uses the default_qty_type and default_qty_value parameters of the strategy() declaration statement to determine the quantity.
//@param limit Optional. The limit price of the order. If specified, the command creates a limit or stop-limit order, depending on whether the stop value is also specified. The default is na, which means the resulting order is not of the limit or stop-limit type.
//@param stop Optional. The stop price of the order. If specified, the command creates a stop or stop-limit order, depending on whether the limit value is also specified. The default is na, which means the resulting order is not of the stop or stop-limit type.
//@param oca_name Parameter `oca_name`. Default: `""`
//@param oca_type Parameter `oca_type`. Default: `0`
//@param comment Parameter `comment`. Default: `""`
//@param alert_message Parameter `alert_message`. Default: `""`
//@returns None.
//@param disable_alert True → this order's fills fire no alert payload (stored message blanked). Default: `false`.
//@param signal_close Optional. Frozen close of the signal bar for equity marking/sizing. Default: `na` (uses `e.prev_close`).
export entry(PTEngine e, string id, int dir, float qty = na, float limit = na, float stop = na, string oca_name = "", int oca_type = 0, string comment = "", string alert_message = "", bool disable_alert = false, float signal_close = na) =>
    if _riskBlocked(e)
        bool(na)
    else if e.cfg.direction_filter == "long" and dir == -1
        bool(na)
    else if e.cfg.direction_filter == "short" and dir == 1
        bool(na)
    else
        string _alertStored = disable_alert ? "" : alert_message
        if not na(signal_close)
            _refreshPosition(e, signal_close, _rateForEngine(e, na), syminfo.pointvalue)
        // TV law: process_orders_on_close=true → MARKET entries fill at the CLOSE
        // of the signal bar, but AFTER the intrabar walk evaluates exits. Queue
        // the order so onBar's walk runs first (brackets fire intrabar before
        // the market entry reverses/closes existing legs). Limit/stop entries
        // always queue (they need future bars).
        bool _deferSize = e.cfg.process_orders_on_close and na(limit) and na(stop) and na(qty)
        float _qtyAtPlace = _deferSize ? qty : _preComputeEntryQty(e, qty, dir, limit, stop, signal_close)
        _placeOrModify(e.queue, Order.new(id, dir, _qtyAtPlace, _snapEntryLimit(e, limit, dir), _snapEntryStop(e, stop, dir), false, true, 100.0, oca_name, oca_type, false, -1, comment, _alertStored, e.equity + e.open_profit, signal_close, e.bar_index + 1))
        true
 
//@function close
//@description Creates an order to exit from the part of a position opened by entry orders with a specific identifier. If multiple entries in the position share the same ID, the orders from this command apply to all those entries, starting from the first open trade, when its calls use that ID as the id argument. This command always generates market orders. To exit from a position using price-based orders (e.g., stop-loss orders), use the `strategy.exit`() command. In PineTunnel, market orders fill at the next bar's open, or at the signal bar's close when `process_orders_on_close` = true. Mirrors `strategy.close()`.
//@param e Engine instance.
//@param from_entry Parameter `from_entry`. Default: `""`
//@param qty Optional. The number of contracts/lots/shares/units to close when an exit order fills. If specified, the command uses this value instead of qty_percent to determine the order size. The default is na, which means the order size depends on the qty_percent value.
//@param qty_percent Parameter `qty_percent`. Default: `100`
//@param immediately If `true`, close at the current bar's `close` price immediately. If `false`, queue a market close for the next bar.
//@param comment Parameter `comment`. Default: `""`
//@param alert_message Parameter `alert_message`. Default: `""`
//@returns None.
//@param disable_alert True → this close's fills fire no alert payload. Default: `false`.
export close(PTEngine e, string from_entry = "", float qty = na, float qty_percent = 100, bool immediately = false, string comment = "", string alert_message = "", bool disable_alert = false) =>
    string _alertStored = disable_alert ? "" : alert_message
    // TV law: process_orders_on_close=true → market closes fill at the CLOSE of
    // the call bar, but AFTER the intrabar walk evaluates exits. Queue the close
    // so brackets fire intrabar before the market close kills the legs.
    // immediately=true forces same-bar immediate fill regardless of poc.
    if immediately
        float rate = _rateForEngine(e, na)
        _closeMarketNow(e, Order.new("__close__" + from_entry, 0, qty, na, na, false, false, qty_percent, "", 0, false, -1, comment, _alertStored, na), close, time, rate, syminfo.pointvalue)
        true
    else
        _placeOrModify(e.queue, Order.new("__close__" + from_entry, 0, qty, na, na, false, false, qty_percent, "", 0, false, -1, comment, _alertStored, na))
        true
 
//@function close_all
//@description Creates an order to close an open position completely, regardless of the identifiers of the entry orders that opened or added to it. This command always generates market orders. To exit from a position using price-based orders (e.g., stop-loss orders), use the `strategy.exit`() command. In PineTunnel, market orders fill at the next bar's open, or at the signal bar's close when `process_orders_on_close` = true. Mirrors `strategy.close_all()`.
//@param e Engine instance.
//@param immediately If `true`, close at the current bar's `close` price immediately. If `false`, queue a market close for the next bar.
//@param comment Parameter `comment`. Default: `""`
//@param alert_message Parameter `alert_message`. Default: `""`
//@returns None.
//@param disable_alert True → these fills fire no alert payload. Default: `false`.
export close_all(PTEngine e, bool immediately = false, string comment = "", string alert_message = "", bool disable_alert = false) =>
    string _alertStored = disable_alert ? "" : alert_message
    // TV law: process_orders_on_close=true → market closes fill at the CLOSE of
    // the call bar, but AFTER the intrabar walk evaluates exits. Queue the close
    // so brackets fire intrabar before the market close kills the legs.
    // immediately=true forces same-bar immediate fill regardless of poc.
    if immediately
        float rate = _rateForEngine(e, na)
        _closeMarketNow(e, Order.new("__close__", 0, na, na, na, false, false, 100.0, "", 0, false, -1, comment, _alertStored, na), close, time, rate, syminfo.pointvalue)
        true
    else if array.size(e.legs) > 0
        for i = 0 to array.size(e.legs) - 1
            OpenTrade lg = array.get(e.legs, i)
            _placeOrModify(e.queue, Order.new("__close__" + lg.entry_id, 0, na, na, na, false, false, 100.0, "", 0, false, -1, comment, _alertStored, na))
        true
 
//@function cancel
//@description Cancels a pending or unfilled order with a specific identifier. If multiple unfilled orders share the same ID, calling this command with that ID as the id argument cancels all of them. If a script calls this command with an id representing the ID of a filled order, it has no effect. This command is most useful when working with price-based orders (e.g., limit orders). Calls to this command can also cancel market orders, but only if they execute on the same ticks as the order placement commands. PineTunnel evaluates fills on bar boundaries, so this call always removes the order before it can fill. Mirrors `strategy.cancel()`.
//@param e Engine instance.
//@param id The identifier of the unfilled order to cancel.
//@returns None.
export cancel(PTEngine e, string id) =>
    if array.size(e.queue) > 0
        for i = array.size(e.queue) - 1 to 0
            if array.get(e.queue, i).id == id
                array.remove(e.queue, i)
    if array.size(e.exits) > 0
        for i = array.size(e.exits) - 1 to 0
            if array.get(e.exits, i).id == id
                array.remove(e.exits, i)
 
//@function cancel_all
//@description Cancels all pending or unfilled orders, regardless of their identifiers. This command is most useful when working with price-based orders (e.g., limit orders). Calls to this command can also cancel market orders, but only if they execute on the same ticks as the order placement commands. PineTunnel evaluates fills on bar boundaries, so this call always removes the order before it can fill. Mirrors `strategy.cancel_all()`.
//@param e Engine instance.
//@returns None.
// TV law: strategy.cancel_all() cancels pending ENTRY orders (queue) but
// does NOT cancel active EXIT brackets.
// The bracket survives cancel_all and may fire during the walk before a
// same-bar close_all fills. Only cancel(id) removes a specific exit.
export cancel_all(PTEngine e) =>
    array.clear(e.queue)
 
//@function risk_max_drawdown
//@description The purpose of this rule is to determine maximum drawdown. The rule affects the whole strategy. Once the maximum drawdown value is reached, all pending orders are cancelled, all open positions are closed and no new orders can be placed. Mirrors `strategy.risk.max_drawdown()`.
//@param e Engine instance.
//@param value A required parameter. The maximum drawdown value. It is specified either in money (base currency), or in percentage of maximum equity. For % of equity the range of allowed values is from 0 to 100.
//@param type Parameter `type`. Default: `"cash"`
//@param alert_message Alert placeholder, stored for consumer-side alert() use. Default: `""` (mirrors TV).
//@returns None.
export risk_max_drawdown(PTEngine e, float value, string type = "cash", string alert_message = "") =>
    e.risk_max_dd_value := value
    e.risk_max_dd_is_pct := type == "percent" ? 1 : 0
    e.risk_alert_dd := alert_message
 
//@function risk_max_intraday_loss
//@description The maximum loss value allowed during a day. It is specified either in money (base currency), or in percentage of maximum intraday equity (0 -100). Mirrors `strategy.risk.max_intraday_loss()`.
//@param e Engine instance.
//@param value A required parameter. The maximum loss value. It is specified either in money (base currency), or in percentage of maximum intraday equity. For % of equity the range of allowed values is from 0 to 100.
//@param type Parameter `type`. Default: `"cash"`
//@param alert_message Alert placeholder, stored for consumer-side alert() use. Default: `""` (mirrors TV).
//@returns None.
export risk_max_intraday_loss(PTEngine e, float value, string type = "cash", string alert_message = "") =>
    e.risk_intraday_value := value
    e.risk_intraday_is_pct := type == "percent" ? 1 : 0
    e.risk_alert_id := alert_message
 
//@function risk_max_intraday_filled_orders
//@description The purpose of this rule is to determine maximum number of filled orders per 1 day (per 1 bar, if chart resolution is higher than 1 day). The rule affects the whole strategy. Once the maximum number of filled orders is reached, all pending orders are cancelled, all open positions are closed and no new orders can be placed till the end of the current trading session. Mirrors `strategy.risk.max_intraday_filled_orders()`.
//@param e Engine instance.
//@param count A required parameter. The maximum number of filled orders per 1 day.
//@param alert_message Alert placeholder, stored for consumer-side alert() use. Default: `""` (mirrors TV).
//@returns None.
export risk_max_intraday_filled_orders(PTEngine e, int count, string alert_message = "") =>
    e.risk_max_filled_orders := count
    e.risk_alert_fo := alert_message
 
//@function risk_max_cons_loss_days
//@description The purpose of this rule is to cancel all pending orders, close all open positions and stop placing orders after a specified number of consecutive days with losses. The rule affects the whole strategy. Mirrors `strategy.risk.max_cons_loss_days()`.
//@param e Engine instance.
//@param count A required parameter. The allowed number of consecutive days with losses.
//@param alert_message Alert placeholder, stored for consumer-side alert() use. Default: `""` (mirrors TV).
//@returns None.
export risk_max_cons_loss_days(PTEngine e, int count, string alert_message = "") =>
    e.risk_max_cons_loss := count
    e.risk_alert_cl := alert_message
 
//@function risk_max_position_size
//@description The purpose of this rule is to determine maximum size of a market position. The rule affects the following function: `strategy.entry`(). The 'entry' quantity can be reduced (if needed) to such number of contracts/shares/lots/units, so the total position size doesn't exceed the value specified in '`strategy.risk.max_position_size`'. If minimum possible quantity still violates the rule, the order will not be placed. Mirrors `strategy.risk.max_position_size()`.
//@param e Engine instance.
//@param contracts A required parameter. Maximum number of contracts/shares/lots/units in a position.
//@returns None.
export risk_max_position_size(PTEngine e, float contracts) =>
    e.risk_max_pos := contracts
 
//@function risk_allow_entry_in
//@description This function can be used to specify in which market direction the `strategy.entry`() function is allowed to open positions. Mirrors `strategy.risk.allow_entry_in()`.
//@param e Engine instance.
//@param value The allowed direction. Possible values: `strategy.direction.all`, `strategy.direction.long`, `strategy.direction.short`
//@returns None.
export risk_allow_entry_in(PTEngine e, string value) =>
    e.cfg.direction_filter := value == "all" ? "both" : value
 
// ── §4 · Exit levels, margin engine & intrabar walk ──────────────────────────
_exitLevelsR(PTEngine e, float tpRaw, float slRaw, float profitTicks, OpenTrade lg) =>
    float tp = na
    if not na(tpRaw)
        if not na(profitTicks) and e.cfg.mintick > 0
            float scale = math.round(1.0 / e.cfg.mintick)
            tp := (math.round(lg.avg_price * scale) + lg.dir * profitTicks) / scale
        else
            tp := _roundTickDir(e, tpRaw, lg.dir)
    float sl = not na(slRaw) ? _roundTick(e, slRaw) : na
    [tpRaw, slRaw, tp, sl]
_exitLevels(PTEngine e, ExitOrder x, OpenTrade lg) =>
    float tpRaw = not na(x.limit)  ? x.limit  : not na(x.profit) ? lg.avg_price + lg.dir * x.profit * e.cfg.mintick : na
    float slRaw = not na(x.stop)   ? x.stop   : not na(x.loss)   ? lg.avg_price - lg.dir * x.loss  * e.cfg.mintick : na
    _exitLevelsR(e, tpRaw, slRaw, x.profit, lg)
// Re-issue law: on the bar where an exit was re-issued (repl_bar == current),
// the intrabar path is governed by the OLD order params (prev_*); the new
// level arms for the next bar.
_exitLevelsFor(PTEngine e, ExitOrder x, OpenTrade lg) =>
    if x.repl_bar == e.bar_index and not na(x.prev_stop)
        float slRaw = not na(x.prev_stop) ? x.prev_stop : not na(x.prev_loss) ? lg.avg_price - lg.dir * x.prev_loss * e.cfg.mintick : na
        float tpRaw = not na(x.limit)  ? x.limit  : not na(x.profit) ? lg.avg_price + lg.dir * x.profit * e.cfg.mintick : na
        _exitLevelsR(e, tpRaw, slRaw, x.profit, lg)
    else
        _exitLevels(e, x, lg)
_roundMt(PTEngine e, float price) =>
    float mt = e.cfg.mintick
    if mt > 0
        float units = price / mt
        float frac = units - math.floor(units)
        float ticks = frac < 0.5 - 1e-6 ? math.floor(units + 0.5 + 1e-9) : math.floor(units + 0.5)
        ticks / math.round(1.0 / mt)
    else
        price
_exitStopPrice(PTEngine e, float rawLevel, float openPx, bool gapThrough, int legDir, bool isTrail = false) =>
    if e.cfg.slippage == 0
        gapThrough ? openPx : isTrail ? _roundMt(e, rawLevel) : e.cfg.mintick > 0 ? (legDir == 1 ? math.floor(math.round(rawLevel * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick) : math.ceil(math.round(rawLevel * math.round(1.0 / e.cfg.mintick), 7)) / math.round(1.0 / e.cfg.mintick)) : rawLevel
    else if gapThrough
        _fillPrice(e, openPx, legDir == 1 ? -1 : 1)
    else if e.cfg.mintick > 0
        float scale = math.round(1.0 / e.cfg.mintick)
        float ticks = math.round(rawLevel * scale)
        legDir == 1 ? math.floor(ticks - e.cfg.slippage) / scale : math.ceil(ticks + e.cfg.slippage) / scale
    else
        float slip = e.cfg.slippage * e.cfg.mintick
        legDir == 1 ? rawLevel - slip : rawLevel + slip
_activationLevel(PTEngine e, ExitOrder x, OpenTrade lg) =>
    float byPrice  = x.trail_price
    float byPoints = lg.avg_price + lg.dir * x.trail_points * e.cfg.mintick
    na(byPrice) ? byPoints : na(byPoints) ? byPrice : lg.dir == 1 ? math.min(byPrice, byPoints) : math.max(byPrice, byPoints)
_marginCheck(PTEngine e, float price, int t, float rate, float pointvalue, float closeVal, bool atOpen = false, bool canDefer = true, bool wholeContracts = false) =>
    bool deferred = false
    float net = _liveNet(e)
    // margin_long/short = 0 means margin checking is DISABLED (TV default):
    // positions are never margin-liquidated, even when equity goes negative.
    if net != 0
        bool isLong = net > 0
        float mPct = isLong ? e.cfg.margin_long : e.cfg.margin_short
        bool marginEnabled = mPct > 0.0
        if marginEnabled and (isLong ? mPct < 100.0 : mPct > 0.0)
            float ratio = mPct / 100.0
            float mvs = 0.0
            float moneySpent = 0.0
            for lg in e.legs
                mvs += lg.qty * price
                moneySpent += lg.qty * lg.avg_price
            float openProfit = isLong ? mvs - moneySpent : moneySpent - mvs
            float eqNow = e.equity + openProfit
            float margin = mvs * ratio
            float avail = eqNow - margin
            bool triggered = false
            float equityTicks = 0.0
            float marginTicks = 0.0
            bool bigEq = eqNow >= 1e7 and e.cfg.mintick > 0
            if bigEq
                equityTicks := math.floor(eqNow / e.cfg.mintick)
                marginTicks := margin / e.cfg.mintick
                if marginTicks >= 1e10
                    marginTicks := 10.0 * math.round(marginTicks / 10.0)
                else
                    marginTicks := math.floor(marginTicks + 0.5)
                triggered := equityTicks < marginTicks
            else
                triggered := avail < 0.0
            if triggered
                float loss = avail / ratio
                float rfactor = wholeContracts ? 1.0 : (e.cfg.qty_step > 0 ? 1.0 / e.cfg.qty_step : 1.0)
                float coverLots = 0.0
                if bigEq and marginTicks >= 1e10
                    float shortfall = (marginTicks - equityTicks) * e.cfg.mintick
                    float bigLoss = shortfall / ratio
                    coverLots := math.max(0.0, math.floor(bigLoss / (price * pointvalue) * rfactor))
                else
                    float rawCover = math.abs(loss) / (price * pointvalue) * rfactor
                    float nearestCover = math.round(rawCover)
                    coverLots := math.abs(rawCover - nearestCover) <= rawCover * math.pow(2.0, -26) + 1e-9 ? nearestCover : math.floor(rawCover)
                int mcLots = 0
                float marginCallSize = na
                if coverLots == 0.0 and rfactor > 1.0
                    mcLots := 0
                    marginCallSize := math.min(1.0, math.abs(net))
                else
                    mcLots := int(math.max(1.0, coverLots * 4.0) + 0.5)
                    marginCallSize := mcLots / rfactor
                if marginCallSize > math.abs(net)
                    marginCallSize := math.abs(net)
                bool canDeferHere = not atOpen and canDefer and mcLots == 1
                if canDeferHere
                    float cMvs = math.abs(net) * closeVal
                    float cOpenProfit = isLong ? cMvs - moneySpent : moneySpent - cMvs
                    float cEq = e.equity + cOpenProfit
                    float cMargin = cMvs * ratio
                    if cEq - cMargin < 0.0
                        e.mc_deferred := true
                        e.mc_deferred_short := not isLong
                        deferred := true
                if not deferred
                    float fillPx = _fillPrice(e, price, -net > 0 ? 1 : -1)
                    float remaining = marginCallSize
                    while remaining > PT_QTY_EPS and array.size(e.legs) > 0
                        OpenTrade lg = array.get(e.legs, 0)
                        if remaining >= lg.qty - PT_QTY_EPS
                            _closeLeg(e, 0, fillPx, t, "Close position order", rate, pointvalue, "Close position order")
                            remaining -= lg.qty
                        else
                            float ecPart = lg.entry_commission * remaining / lg.qty
                            float maePart = lg.max_drawdown * remaining / lg.qty
                            float mfePart = lg.max_runup * remaining / lg.qty
                            array.set(e.legs, 0, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - remaining, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                            array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, remaining, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                            _closeLeg(e, array.size(e.legs) - 1, fillPx, t, "Close position order", rate, pointvalue, "Close position order")
                            remaining := 0.0
                    e.margin_call_count += 1
                    e.margin_liquidated_total += marginCallSize
    deferred
closeMc(PTEngine e, float c, int t, float rate, float pointvalue) =>
    if e.mc_deferred
        e.mc_deferred := false
        _marginCheck(e, c, t, rate, pointvalue, c, true, false, true)
    _marginCheck(e, c, t, rate, pointvalue, c)
_exitComment(ExitOrder x, string kind) =>
    switch kind
        "profit"   => x.comment_profit   != "" ? x.comment_profit   : x.comment
        "loss"     => x.comment_loss     != "" ? x.comment_loss     : x.comment
        "trailing" => x.comment_trailing != "" ? x.comment_trailing : x.comment
        => x.comment
// TV post-close laws: (1) a bracket re-issued on a live position is
// fill-eligible at the SAME bar's close — "limit or better" books the close;
// (2) same-bar multi-leg closes book FIFO (oldest entry first); (3) stops
// never fire at the post-close pass.
export onBarPost(PTEngine e, float _o, float _h, float _l, float c, int t, float _rate, float pointvalue) =>
    // The post-close pass only evaluates fills against the close — OHLC args exist
    // for API symmetry with onBar. They must flow into the RETURN value: the
    // compiler dead-strips locals that never reach the output. The trailing
    // ternary always yields na, so the return contract is unchanged while
    // _o/_h/_l stay in the output dataflow.
    float _keep = nz(_o, _h) + _l
    if array.size(e.exits) > 0 and array.size(e.legs) > 0
        float close_r = _roundMt(e, c)
        // FIFO booking (oldest leg first) with full-close removal safety:
        // while-loop + manual index so _closeLeg's array.shift doesn't skip.
        int liO = 0
        while liO < array.size(e.legs)
            OpenTrade lg = array.get(e.legs, liO)
            string seqKey = str.tostring(lg.seq)
            ExitOrder x = na
            int ri = -1
            for xe in e.exits
                int _r = _rowOf(xe, seqKey)
                if _r >= 0 and not array.get(xe.t_fired, _r)
                    x := xe
                    ri := _r
                    break
            if na(x) or ri < 0
                liO += 1
                continue
            OpenTrade refLg = na
            if x.from_entry != ""
                for fl in e.legs
                    if fl.entry_id == x.from_entry
                        refLg := fl
                        break
            if na(refLg)
                refLg := array.get(e.legs, 0)
            [tpRaw, slRaw, tp, sl] = _exitLevels(e, x, refLg)
            bool isLong = lg.dir == 1
            // Limit-or-better at close; stops never fire post-close.
            bool limitAtClose = not na(tp) and (isLong ? tp <= close_r + PT_QTY_EPS : tp >= close_r - PT_QTY_EPS)
            if not limitAtClose
                liO += 1
                continue
            float res = _resAt(x, ri)
            float used = array.size(x.t_used) > ri ? array.get(x.t_used, ri) : 0.0
            float resRemaining = math.max(0.0, res - used)
            float rawQty = na(x.qty) ? math.min(resRemaining, lg.qty) : math.min(x.qty, lg.qty, resRemaining)
            float closeQty = math.min(rawQty, resRemaining)
            if closeQty <= PT_QTY_EPS
                liO += 1
                continue
            // TV books the close price when it is already beyond the limit.
            float xpx = isLong ? math.max(tp, close_r) : math.min(tp, close_r)
            string xc = _exitComment(x, "profit")
            bool isFull = closeQty >= lg.qty - PT_QTY_EPS
            if isFull
                _closeLeg(e, liO, xpx, t, x.id, _rate, pointvalue, xc)
            else
                float ecPart = lg.entry_commission * closeQty / lg.qty
                array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - closeQty, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown, lg.max_runup, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                array.set(e.legs, liO, OpenTrade.new(lg.entry_id, lg.dir, closeQty, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, lg.max_drawdown, lg.max_runup, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                _closeLeg(e, array.size(e.legs) - 1, xpx, t, x.id, _rate, pointvalue, xc)
            _ocaReduce(e, x, seqKey, math.max(0.0, closeQty - res))
            _ocaExitCancel(e, x, seqKey, closeQty)
            if array.size(x.t_used) > ri
                array.set(x.t_used, ri, array.get(x.t_used, ri) + closeQty)
            _consumeExitQty(e, x, closeQty, seqKey)
            _countFill(e, xpx, t, _rate, pointvalue)
            if not isFull
                liO += 1
        _reserveExits(e)
    _keep == _keep ? na : _keep
_intrabarWalk(PTEngine e, float o, float h, float l, float c, int t, float _rate, float pointvalue) =>
    bool hasPending = array.size(e.queue) > 0 or (array.size(e.exits) > 0 and array.size(e.legs) > 0)
    float _netBefore = _liveNet(e)
    bool _adverseFirst = false
    if _netBefore != 0
        bool _highFirst = math.abs(h - o) < math.abs(o - l)
        _adverseFirst := _netBefore > 0 ? not _highFirst : _highFirst
    if _adverseFirst and _netBefore != 0
        float _advPx = _netBefore > 0 ? l : h
        _marginCheck(e, _advPx, t, _rate, pointvalue, c, false, true)
    // Risk guard + adverse-extreme run every bar with a live book, even when
    // no orders are pending (the walk skips then — section B has no exits).
    if not hasPending and array.size(e.legs) > 0
        float _adv = _liveNet(e) > 0 ? l : h
        _riskCheckIntraday(e, _adv, t, _rate, pointvalue)
        _riskCheckIntraday(e, c, t, _rate, pointvalue)
    if hasPending
        float fla = e.cfg.fill_limits_assumption * e.cfg.mintick
        bool highFirst = math.abs(h - o) < math.abs(o - l)
        // TV law: trail activates at the OPEN when open is at/past the
        // activation level AND the first intrabar point is adverse (low
        // first for longs, high first for shorts) — TV arms at open−offset
        // before the walk. When the first point is favorable, the walk's
        // own pi=1 activation (arm at extreme−offset) matches TV.
        // Applies to every trail_points / trail_price exit, both directions.
        if array.size(e.legs) > 0 and array.size(e.exits) > 0
            for _xe in e.exits
                if _xe.place_bar != e.bar_index and not na(_xe.trail_offset) and (not na(_xe.trail_price) or not na(_xe.trail_points)) and array.size(_xe.t_legs) > 0
                    for _li2 = 0 to array.size(e.legs) - 1
                        OpenTrade _li = array.get(e.legs, _li2)
                        if _xe.from_entry == "" or _xe.from_entry == _li.entry_id
                            string _seqKey = str.tostring(_li.seq)
                            int _tIdx = _trailIdx(_xe, _seqKey)
                            if not array.get(_xe.t_act, _tIdx)
                                float _actLevel = _activationLevel(e, _xe, _li)
                                bool _firstAdverse = _li.dir == 1 ? not highFirst : highFirst
                                if not na(_actLevel) and _firstAdverse and (_li.dir == 1 ? o >= _actLevel : o <= _actLevel)
                                    float _mt = e.cfg.mintick
                                    float _armStop = _li.dir == 1 ? o - _xe.trail_offset * _mt : o + _xe.trail_offset * _mt
                                    _armStop := _mt > 0 ? int(_armStop / _mt + 0.5) * _mt : _armStop
                                    array.set(_xe.t_act, _tIdx, true)
                                    array.set(_xe.t_stop, _tIdx, _armStop)
                                    array.set(_xe.t_abar, _tIdx, e.bar_index)
                                    if _li.dir == 1 ? l <= _armStop : h >= _armStop
                                        float _res = _resAt(_xe, _tIdx)
                                        if _res > PT_QTY_EPS
                                            float _closeQty = math.min(_res, _li.qty)
                                            float _xpx = _exitStopPrice(e, _armStop, o, false, _li.dir, true)
                                            string _xc = _exitComment(_xe, "trailing")
                                            if _closeQty >= _li.qty - PT_QTY_EPS
                                                _closeLeg(e, _li2, _xpx, t, _xe.id, _rate, pointvalue, _xc)
                                            else
                                                float _ecPart = _li.entry_commission * _closeQty / _li.qty
                                                float _maePart = _li.max_drawdown * _closeQty / _li.qty
                                                float _mfePart = _li.max_runup * _closeQty / _li.qty
                                                array.set(e.legs, _li2, OpenTrade.new(_li.entry_id, _li.dir, _li.qty - _closeQty, _li.avg_price, _li.entry_time, _li.entry_commission - _ecPart, _li.entry_bar_index, _li.max_drawdown - _maePart, _li.max_runup - _mfePart, _li.entry_comment, _li.seq, _li.entry_equity, _li.max_equity_before))
                                                array.push(e.legs, OpenTrade.new(_li.entry_id, _li.dir, _closeQty, _li.avg_price, _li.entry_time, _ecPart, _li.entry_bar_index, _maePart, _mfePart, _li.entry_comment, _li.seq, _li.entry_equity, _li.max_equity_before))
                                                _closeLeg(e, array.size(e.legs) - 1, _xpx, t, _xe.id, _rate, pointvalue, _xc)
                                            _ocaReduce(e, _xe, _seqKey, math.max(0.0, _closeQty - _res))
                                            _ocaExitCancel(e, _xe, _seqKey, _closeQty)
                                            int _uIdx = _rowOf(_xe, _seqKey)
                                            if _uIdx >= 0
                                                array.set(_xe.t_used, _uIdx, array.get(_xe.t_used, _uIdx) + _closeQty)
                                            _consumeExitQty(e, _xe, _closeQty, _seqKey)
                                            _countFill(e, _xpx, t, _rate, pointvalue)
                                            int _dropIdx = _rowOf(_xe, _seqKey)
                                            if _dropIdx >= 0
                                                array.remove(_xe.t_legs, _dropIdx)
                                                array.remove(_xe.t_act, _dropIdx)
                                                array.remove(_xe.t_stop, _dropIdx)
                                                array.remove(_xe.t_res, _dropIdx)
                                                array.remove(_xe.t_init, _dropIdx)
                                                array.remove(_xe.t_used, _dropIdx)
                                                array.remove(_xe.t_fired, _dropIdx)
                                                array.remove(_xe.t_abar, _dropIdx)
        for pi = 1 to 3
            float p = pi == 1 ? (highFirst ? h : l) : pi == 2 ? (highFirst ? l : h) : c
            float pPrev = pi == 1 ? o : pi == 2 ? (highFirst ? h : l) : (highFirst ? l : h)
            bool entryFilled = false
            // TV law: limit/stop entries fill in price-path order, not queue order.
            // Long limits: highest limit first (hit first as price drops).
            // Long stops: lowest stop first (hit first as price rises).
            // Short limits: lowest limit first (hit first as price rises).
            // Short stops: highest stop first (hit first as price drops).
            // Approach: repeatedly find the most favorable eligible order and fill it.
            bool _entryLoop = true
            while _entryLoop
                _entryLoop := false
                Order _bestOd = na
                float _bestKey = na
                string _bestId = ""
                for qd in e.queue
                    if qd.dir != 0 and (not na(qd.limit) or not na(qd.stop)) and qd.place_bar != e.bar_index
                        float _sk = na
                        if not na(qd.limit) and na(qd.stop)
                            _sk := qd.dir == 1 ? -qd.limit : qd.limit
                        else if not na(qd.stop) and na(qd.limit)
                            _sk := qd.dir == 1 ? qd.stop : -qd.stop
                        else if not na(qd.stop) and not na(qd.limit)
                            _sk := qd.dir == 1 ? qd.stop : -qd.stop
                        if na(_bestKey) or (not na(_sk) and _sk < _bestKey)
                            _bestOd := qd
                            _bestKey := na(_sk) ? 0.0 : _sk
                            _bestId := qd.id
                if not na(_bestOd)
                    Order od = _bestOd
                    bool trig = false
                    float epx = na
                    if not na(od.limit) and na(od.stop)
                        if od.dir == 1 and p <= od.limit - fla
                            trig := true
                            epx := math.min(o, od.limit)
                        else if od.dir == -1 and p >= od.limit + fla
                            trig := true
                            epx := math.max(o, od.limit)
                    else if not na(od.stop) and na(od.limit)
                        if od.dir == 1 and p >= od.stop
                            trig := true
                            epx := math.max(o, od.stop)
                        else if od.dir == -1 and p <= od.stop
                            trig := true
                            epx := math.min(o, od.stop)
                    else if not od.sl_triggered
                        bool sHit = od.dir == 1 ? p >= od.stop : p <= od.stop
                        if sHit
                            od.sl_triggered := true
                            od.sl_bar := e.bar_index
                            float mkt = od.dir == 1 ? math.max(o, od.stop) : math.min(o, od.stop)
                            bool mktOk = od.dir == 1 ? mkt <= od.limit : mkt >= od.limit
                            if mktOk
                                trig := true
                                epx := mkt
                    else
                        bool lHit = od.dir == 1 ? p <= od.limit - fla : p >= od.limit + fla
                        if lHit
                            trig := true
                            epx := od.sl_bar == e.bar_index ? od.limit : od.dir == 1 ? math.min(o, od.limit) : math.max(o, od.limit)
                    if trig
                        if _fillEntryOrder(e, od, epx, t, _rate, pointvalue)
                            for di = array.size(e.queue) - 1 to 0
                                if array.get(e.queue, di).id == od.id
                                    array.remove(e.queue, di)
                            entryFilled := true
                            _entryLoop := true
                    // Not triggered at this point: stop scanning — the order
                    // is re-evaluated at the next point.
                    if not trig
                        _entryLoop := false
            if entryFilled
                _reserveExits(e)
            array<string> xids = array.new<string>()
            for xe in e.exits
                array.push(xids, xe.id)
            array<int> hitIdx = array.new<int>()
            array<float> hitDist = array.new<float>()
            if array.size(e.legs) > 0
                int _xi = 0
                for xe in e.exits
                    if xe.place_bar != e.bar_index and (array.size(xe.t_legs) > 0 or _staleSurvives(e, xe))
                        float _tp = na
                        float _sl = na
                        int _scanDir = 0
                        if array.size(xe.t_legs) > 0
                            OpenTrade _refLg = na
                            if xe.from_entry != ""
                                for fl in e.legs
                                    if fl.entry_id == xe.from_entry
                                        _refLg := fl
                                        break
                            if na(_refLg)
                                _refLg := array.get(e.legs, 0)
                            [_tpRaw, _slRaw, _tpL, _slL] = _exitLevelsFor(e, xe, _refLg)
                            _tp := _tpL
                            _sl := _slL
                            if xe.from_entry != "" and not na(_refLg) and _refLg.entry_id == xe.from_entry
                                xe.fz_tp := _tpL
                                xe.fz_sl := _slL
                                xe.fz_slraw := _slRaw
                                xe.fz_dir := _refLg.dir
                            _scanDir := _refLg.dir
                        else
                            // stale survivor: frozen own-leg levels (bound leg dead)
                            _tp := xe.fz_tp
                            _sl := xe.fz_sl
                            _scanDir := xe.fz_dir
                        bool hitTpS = not na(_tp) and (_scanDir == 1 ? p >= _tp + fla : p <= _tp - fla)
                        bool hitSlS = not na(_sl) and (_scanDir == 1 ? p <= _sl : p >= _sl)
                        if hitTpS or hitSlS
                            float _lvlHit = na
                            if hitTpS and hitSlS
                                _lvlHit := _scanDir == 1 ? math.max(_tp, _sl) : math.min(_tp, _sl)
                            else if hitTpS
                                _lvlHit := _tp
                            else
                                _lvlHit := _sl
                            array.push(hitIdx, _xi)
                            array.push(hitDist, math.abs(_lvlHit - o))
                    _xi += 1
                int hn = array.size(hitIdx)
                if hn > 1
                    // STABLE insertion sort by hitDist ascending — ties keep
                    // placement (scan) order. TV fills simultaneous same-level
                    // exits in placement order.
                    for a2 = 1 to hn - 1
                        int tidx = array.get(hitIdx, a2)
                        float tdst = array.get(hitDist, a2)
                        int b2 = a2 - 1
                        while b2 >= 0 and array.get(hitDist, b2) > tdst
                            array.set(hitIdx, b2 + 1, array.get(hitIdx, b2))
                            array.set(hitDist, b2 + 1, array.get(hitDist, b2))
                            b2 -= 1
                        array.set(hitIdx, b2 + 1, tidx)
                        array.set(hitDist, b2 + 1, tdst)
                    array<string> ordered = array.new<string>()
                    for a3 = 0 to hn - 1
                        array.push(ordered, array.get(xids, array.get(hitIdx, a3)))
                    for xi0 = 0 to array.size(xids) - 1
                        bool inHits = false
                        for a4 = 0 to hn - 1
                            if array.get(hitIdx, a4) == xi0
                                inHits := true
                                break
                        if not inHits
                            array.push(ordered, array.get(xids, xi0))
                    array.clear(xids)
                    for s2 in ordered
                        array.push(xids, s2)
            int xi = 0
            while xi < array.size(xids)
                ExitOrder x = na
                for xe in e.exits
                    if xe.id == array.get(xids, xi)
                        x := xe
                        break
                if not na(x) and array.size(e.legs) > 0 and x.place_bar != e.bar_index
                    array<string> _liveRows = array.new<string>()
                    for ri = 0 to (array.size(x.t_legs) == 0 ? na : array.size(x.t_legs) - 1)
                        if not array.get(x.t_fired, ri) or array.get(x.t_res, ri) > PT_QTY_EPS
                            array.push(_liveRows, array.get(x.t_legs, ri))
                    // Stale survivor (rows stripped by foreign sweeps, TV cross-fill
                    // law): fill FIFO across remaining legs at FROZEN own-leg levels,
                    // F2B-ordered among live fills. Qty'd brackets budget their
                    // remaining qty; qty-less budget c_init (single fire).
                    if array.size(_liveRows) == 0 and _staleSurvives(e, x) and x.fz_dir != 0
                        float _sbud = na(x.qty) ? _stepRoundQty(e, x.c_init) : _stepRoundQty(e, x.qty)
                        bool _shTp = not na(x.fz_tp) and (x.fz_dir == 1 ? p >= x.fz_tp + fla : p <= x.fz_tp - fla)
                        bool _shSl = not na(x.fz_sl) and (x.fz_dir == 1 ? p <= x.fz_sl : p >= x.fz_sl)
                        if (_shTp or _shSl) and _sbud > PT_QTY_EPS
                            if _shTp and _shSl
                                _shSl := false
                            int _sli = 0
                            while _sli < array.size(e.legs) and _sbud > PT_QTY_EPS
                                OpenTrade slg = array.get(e.legs, _sli)
                                float _sq = math.min(_sbud, slg.qty)
                                bool _sEx = slg.entry_bar_index != e.bar_index
                                bool _sSlGap = _sEx and (slg.dir == 1 ? o <= x.fz_sl : o >= x.fz_sl)
                                bool _sTpGap = _shTp and _sEx and (x.fz_dir == 1 ? o >= x.fz_tp : o <= x.fz_tp)
                                float _spx = _shTp ? (_sTpGap ? _roundMt(e, o) : x.fz_tp) : _exitStopPrice(e, x.fz_slraw, o, _sSlGap, slg.dir)
                                string _sxc = _exitComment(x, _shTp ? "profit" : "loss")
                                if _sq >= slg.qty - PT_QTY_EPS
                                    _closeLeg(e, _sli, _spx, t, x.id, _rate, pointvalue, _sxc)
                                else
                                    float _secP = slg.entry_commission * _sq / slg.qty
                                    float _smaeP = slg.max_drawdown * _sq / slg.qty
                                    float _smfeP = slg.max_runup * _sq / slg.qty
                                    array.set(e.legs, _sli, OpenTrade.new(slg.entry_id, slg.dir, slg.qty - _sq, slg.avg_price, slg.entry_time, slg.entry_commission - _secP, slg.entry_bar_index, slg.max_drawdown - _smaeP, slg.max_runup - _smfeP, slg.entry_comment, slg.seq, slg.entry_equity, slg.max_equity_before))
                                    array.push(e.legs, OpenTrade.new(slg.entry_id, slg.dir, _sq, slg.avg_price, slg.entry_time, _secP, slg.entry_bar_index, _smaeP, _smfeP, slg.entry_comment, slg.seq, slg.entry_equity, slg.max_equity_before))
                                    _closeLeg(e, array.size(e.legs) - 1, _spx, t, x.id, _rate, pointvalue, _sxc)
                                if not na(x.qty)
                                    x.qty := math.max(0.0, x.qty - _sq)
                                _countFill(e, _spx, t, _rate, pointvalue)
                                _sbud := math.max(0.0, _sbud - _sq)
                            bool _sdone = na(x.qty) or x.qty <= PT_QTY_EPS
                            if _sdone and array.size(e.exits) > 0
                                for _sdi = array.size(e.exits) - 1 to 0
                                    if array.get(e.exits, _sdi).id == x.id
                                        array.remove(e.exits, _sdi)
                    int _rowIter = 0
                    while _rowIter < array.size(_liveRows)
                        string seqKey = array.get(_liveRows, _rowIter)
                        int _thisRow = _rowOf(x, seqKey)
                        if _thisRow < 0
                            _rowIter += 1
                            continue
                        float _orderRemain = 1e18
                        if na(x.qty)
                            if x.qty_percent >= 100.0
                                float _earlierUsed = 0.0
                                for _xo2 in e.exits
                                    if _xo2.id == x.id
                                        break
                                    int _uRow = _rowOf(_xo2, seqKey)
                                    if _uRow >= 0
                                        _earlierUsed += _resOr(_xo2, _uRow)
                                _orderRemain := _stepRoundQty(e, (array.size(x.t_init) > _thisRow ? array.get(x.t_init, _thisRow) : 0.0) - _earlierUsed)
                            else
                                _orderRemain := _stepRoundQty(e, (array.size(x.t_res) > _thisRow ? array.get(x.t_res, _thisRow) : 0.0))
                        else
                            _orderRemain := _stepRoundQty(e, x.qty)
                        float res = _thisRow >= 0 ? _resAt(x, _thisRow) : 0.0
                        OpenTrade refLg = na
                        if x.from_entry != ""
                            for fl in e.legs
                                if fl.entry_id == x.from_entry
                                    refLg := fl
                                    break
                        if na(refLg) and array.size(e.legs) > 0
                            refLg := array.get(e.legs, 0)
                        int li = 0
                        while li < array.size(e.legs) and _orderRemain > PT_QTY_EPS
                            OpenTrade lg = array.get(e.legs, li)
                            if true
                                [_, slRaw, tp, sl] = _exitLevelsFor(e, x, refLg)
                                int rIdx = _thisRow
                                float rawQty = na(x.qty) ? math.min(_orderRemain, lg.qty) : math.min(x.qty, lg.qty)
                                float usedQty = rIdx >= 0 ? (array.size(x.t_used) == 0 ? 0.0 : array.get(x.t_used, rIdx)) : 0.0
                                float resRemaining = math.max(0.0, res - usedQty)
                                bool foreignLeg = x.from_entry != "" and lg.entry_id != x.from_entry
                                float closeQty = foreignLeg ? rawQty : math.min(rawQty, resRemaining)
                                bool hitTp = not na(tp) and (lg.dir == 1 ? p >= tp + fla : p <= tp - fla)
                                bool hitSl = not na(sl) and (lg.dir == 1 ? p <= sl : p >= sl)
                                if (hitTp or hitSl) and closeQty > PT_QTY_EPS
                                    bool existedAtOpen = lg.entry_bar_index != e.bar_index
                                    bool _slGap = existedAtOpen and (lg.dir == 1 ? o <= sl : o >= sl)
                                    bool _tpGap = existedAtOpen and (lg.dir == 1 ? o >= tp : o <= tp)
                                    float xpx = hitTp ? (_tpGap ? _roundMt(e, o) : tp) : _exitStopPrice(e, slRaw, o, _slGap, lg.dir)
                                    string xc = _exitComment(x, hitTp ? "profit" : "loss")
                                    bool fullClose = closeQty >= lg.qty - PT_QTY_EPS
                                    if fullClose
                                        _closeLeg(e, li, xpx, t, x.id, _rate, pointvalue, xc)
                                    else
                                        float ecPart = lg.entry_commission * closeQty / lg.qty
                                        float maePart = lg.max_drawdown * closeQty / lg.qty
                                        float mfePart = lg.max_runup * closeQty / lg.qty
                                        array.set(e.legs, li, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - closeQty, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                        array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, closeQty, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                        _closeLeg(e, array.size(e.legs) - 1, xpx, t, x.id, _rate, pointvalue, xc)
                                    _ocaReduce(e, x, seqKey, math.max(0.0, closeQty - res))
                                    _ocaExitCancel(e, x, seqKey, closeQty)
                                    int uIdx = _rowOf(x, seqKey)
                                    if uIdx >= 0 and array.size(x.t_used) > uIdx
                                        array.set(x.t_used, uIdx, array.get(x.t_used, uIdx) + closeQty)
                                    _consumeExitQty(e, x, closeQty, seqKey)
                                    _countFill(e, xpx, t, _rate, pointvalue)
                                    _orderRemain := math.max(0.0, _orderRemain - closeQty)
                                    continue
                                else if not na(x.trail_offset) and (not na(x.trail_price) or not na(x.trail_points)) and res > PT_QTY_EPS
                                    int idx = _trailIdx(x, seqKey)
                                    bool active = array.get(x.t_act, idx)
                                    float tStop = array.get(x.t_stop, idx)
                                    float mt = e.cfg.mintick
                                    float trP = p
                                    float trPPrev = pPrev
                                    bool favorable = lg.dir == 1 ? trP > trPPrev : trP < trPPrev
                                    if not active
                                        if favorable
                                            float actLevel = _activationLevel(e, x, refLg)
                                            if not na(actLevel) and (lg.dir == 1 ? trP >= actLevel : trP <= actLevel)
                                                array.set(x.t_act, idx, true)
                                                float armStop = lg.dir == 1 ? trP - x.trail_offset * mt : trP + x.trail_offset * mt
                                                array.set(x.t_stop, idx, mt > 0 ? int(armStop / mt + 0.5) * mt : armStop)
                                                array.set(x.t_abar, idx, e.bar_index)
                                    else
                                        if pi == 1 and array.get(x.t_abar, idx) != e.bar_index and (lg.dir == 1 ? o <= tStop : o >= tStop)
                                            bool _sgGap = true
                                            float xpx = _exitStopPrice(e, tStop, o, _sgGap, lg.dir, true)
                                            string xc = _exitComment(x, "trailing")
                                            if closeQty >= lg.qty - PT_QTY_EPS
                                                _closeLeg(e, li, xpx, t, x.id, _rate, pointvalue, xc)
                                            else
                                                float ecPart = lg.entry_commission * closeQty / lg.qty
                                                float maePart = lg.max_drawdown * closeQty / lg.qty
                                                float mfePart = lg.max_runup * closeQty / lg.qty
                                                array.set(e.legs, li, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - closeQty, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                                array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, closeQty, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                                _closeLeg(e, array.size(e.legs) - 1, xpx, t, x.id, _rate, pointvalue, xc)
                                            _ocaReduce(e, x, seqKey, math.max(0.0, closeQty - res))
                                            _ocaExitCancel(e, x, seqKey, closeQty)
                                            int uIdx = _rowOf(x, seqKey)
                                            if uIdx >= 0
                                                array.set(x.t_used, uIdx, array.get(x.t_used, uIdx) + closeQty)
                                            _consumeExitQty(e, x, closeQty, seqKey)
                                            _countFill(e, xpx, t, _rate, pointvalue)
                                            int dropIdx = _rowOf(x, seqKey)
                                            if dropIdx >= 0
                                                array.remove(x.t_legs, dropIdx)
                                                array.remove(x.t_act, dropIdx)
                                                array.remove(x.t_stop, dropIdx)
                                                array.remove(x.t_res, dropIdx)
                                                array.remove(x.t_init, dropIdx)
                                                array.remove(x.t_used, dropIdx)
                                                array.remove(x.t_fired, dropIdx)
                                                array.remove(x.t_abar, dropIdx)
                                            break
                                        if lg.dir == 1 ? trP <= tStop : trP >= tStop
                                            bool _tGap = false
                                            float xpx = _exitStopPrice(e, tStop, o, _tGap, lg.dir, true)
                                            string xc = _exitComment(x, "trailing")
                                            if closeQty >= lg.qty - PT_QTY_EPS
                                                _closeLeg(e, li, xpx, t, x.id, _rate, pointvalue, xc)
                                            else
                                                float ecPart = lg.entry_commission * closeQty / lg.qty
                                                float maePart = lg.max_drawdown * closeQty / lg.qty
                                                float mfePart = lg.max_runup * closeQty / lg.qty
                                                array.set(e.legs, li, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - closeQty, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                                array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, closeQty, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                                _closeLeg(e, array.size(e.legs) - 1, xpx, t, x.id, _rate, pointvalue, xc)
                                            _ocaReduce(e, x, seqKey, math.max(0.0, closeQty - res))
                                            _ocaExitCancel(e, x, seqKey, closeQty)
                                            int uIdx = _rowOf(x, seqKey)
                                            if uIdx >= 0
                                                array.set(x.t_used, uIdx, array.get(x.t_used, uIdx) + closeQty)
                                            _consumeExitQty(e, x, closeQty, seqKey)
                                            _countFill(e, xpx, t, _rate, pointvalue)
                                            int dropIdx = _rowOf(x, seqKey)
                                            if dropIdx >= 0
                                                array.remove(x.t_legs, dropIdx)
                                                array.remove(x.t_act, dropIdx)
                                                array.remove(x.t_stop, dropIdx)
                                                array.remove(x.t_res, dropIdx)
                                                array.remove(x.t_init, dropIdx)
                                                array.remove(x.t_used, dropIdx)
                                                array.remove(x.t_fired, dropIdx)
                                                array.remove(x.t_abar, dropIdx)
                                            break
                                        else if favorable
                                            float theo = lg.dir == 1 ? trP - x.trail_offset * mt : trP + x.trail_offset * mt
                                            theo := mt > 0 ? int(theo / mt + 0.5) * mt : theo
                                            if lg.dir == 1 ? theo > tStop : theo < tStop
                                                array.set(x.t_stop, idx, theo)
                            li += 1
                        _rowIter += 1
                xi += 1
            // TV law: R2 max_intraday_loss is evaluated INTRABAR at each
            // walk node on total equity (incl. open profit), NOT at close.
            // The node check must NOT ratchet day_max (peak is
            // close/day-start anchored); _riskCheckIntradayNoPeak
            // evaluates without touching day_max_equity.
            _riskCheckIntradayNoPeak(e, p, t, _rate, pointvalue)
            // MAE/MFE mark at this node for legs that SURVIVED the node's fills
            if array.size(e.legs) > 0
                for li = 0 to array.size(e.legs) - 1
                    OpenTrade lg = array.get(e.legs, li)
                    float adv = lg.dir == 1 ? lg.avg_price - p : p - lg.avg_price
                    if adv > 0
                        lg.max_drawdown := math.max(lg.max_drawdown, lg.qty * adv * pointvalue * _rate)
                    float fv = lg.dir == 1 ? p - lg.avg_price : lg.avg_price - p
                    if fv > 0
                        lg.max_runup := math.max(lg.max_runup, lg.qty * fv * pointvalue * _rate)
                    array.set(e.legs, li, lg)
        _reserveExits(e)
    // Refresh flat generation for exits that survived to bar close: exits
    // still present at bar close are legitimate working orders and must not
    // be killed later by a stale-generation check.
    if array.size(e.exits) > 0
        for _rx in e.exits
            _rx.flat_gen_at_place := e.flat_gen
// ── §5 · Bar driver ──────────────────────────────────────────────────────────
//@function onBar
//@description Advances the engine one bar. Must be called once per bar before any order/exit logic. Chart OHLCV are read from built-ins when not supplied.
//@param e Engine instance.
//@param o Parameter `o`. Default: `open`
//@param h Parameter `h`. Default: `high`
//@param l Parameter `l`. Default: `low`
//@param c Parameter `c`. Default: `close`
//@param t Parameter `t`. Default: `time`
//@param pointvalue Parameter `pointvalue`. Default: `syminfo.pointvalue`
//@param curr_rate Optional conversion-rate override. Default: `na` (auto-computed from `syminfo.currency` to `e.cfg.currency`).
//@returns Updated engine (mutated in place).
export onBar(PTEngine e, float o = open, float h = high, float l = low, float c = close, int t = time, float pointvalue = syminfo.pointvalue, float curr_rate = na) =>
    float _rate = _rateForEngine(e, curr_rate)
    e.bar_index += 1
    e._bar_h := h
    e._bar_l := l
    e._bar_c := c
    e._last_rate := _rate
    if barstate.isfirst
        e._first_close := close
    float _spyClose = request.security("SPY", "D", close, barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol = true)
    if bar_index == 0
        e._spy_first := _spyClose
    if barstate.islastconfirmedhistory
        e._spy_last := _spyClose
    if barstate.isconfirmed and not na(_spyClose) and _spyClose != nz(_spyClose[1], na)
        float _benchRet = _spyClose / _spyClose[1] - 1.0
        if not na(_benchRet)
            array.push(e._spy_rets, _benchRet)
    // ── Day rollover (risk guards) ──
    // Calendar day id from the bar timestamp (UTC). R2/R3 halts clear here;
    // R4 settles the ended day BEFORE the new one opens.
    int _riskDayId = math.floor(t / 86400000.0)
    if _riskDayId != e.risk_day
        if e.risk_day != -1
            if e.equity < e.day_start_equity
                e.consec_loss_days += 1
                e.last_loss_day := e.risk_day
            else
                e.consec_loss_days := 0
        e.risk_day := _riskDayId
        e.risk_halt_today := false
        e.day_filled_orders := 0
        e.day_start_equity := e.equity + e.open_profit
        e.day_max_equity := na
        // R4: N straight losing days → permanent halt (flatten at this bar's
        // open — the earliest price of the new session).
        if e.risk_max_cons_loss > 0 and e.consec_loss_days >= e.risk_max_cons_loss and not e.risk_halt_perm
            _riskPermHalt(e, o, t, _rate, pointvalue, e.risk_alert_cl)
    if e.cfg.process_orders_on_close
        // TV law: R1 max_drawdown is evaluated on REALIZED equity drawdown
        // (realized peak − current realized), NOT total equity incl. open
        // profit.
        if not e.risk_halt_perm and not na(e.risk_max_dd_value)
            float _realPeak = na(e.realized_equity_peak) ? e.cfg.initial_capital : e.realized_equity_peak
            float _ddLimit = e.risk_max_dd_is_pct == 1 ? _realPeak * e.risk_max_dd_value / 100.0 : e.risk_max_dd_value
            if _realPeak - e.equity >= _ddLimit
                _riskPermHalt(e, o, t, _rate, pointvalue, e.risk_alert_dd)
        // TV law: R2 max_intraday_loss also checks at the START of bar
        // processing (using the PREVIOUS bar's close equity), before the walk.
        // Cash type: day_start - current (how far below day open).
        // Percent type: day_max - current (drawdown from intraday peak).
        // R2 is a POSITION loss guard: no open position → no check.
        if not e.risk_halt_perm and not e.risk_halt_today and not na(e.risk_intraday_value) and array.size(e.legs) > 0
            float _preEqNow2 = e.equity + e.open_profit
            float _idLimit = e.risk_intraday_is_pct == 1 ? e.day_max_equity * e.risk_intraday_value / 100.0 : e.risk_intraday_value
            float _r2lossS = e.risk_intraday_is_pct == 1 ? (not na(e.day_max_equity) ? e.day_max_equity - _preEqNow2 : 0.0) : ((na(e.day_start_equity) ? _preEqNow2 : e.day_start_equity) - _preEqNow2)
            if _r2lossS >= _idLimit and _idLimit > 0
                if e.risk_intraday_is_pct == 1 and _preEqNow2 <= 0
                    _riskPermHalt(e, o, t, _rate, pointvalue, e.risk_alert_id)
                else
                    _riskIntradayHalt(e, o, t, _rate, pointvalue, e.risk_alert_id, "Close Position (Max intraday Loss)")
        _intrabarWalk(e, o, h, l, c, t, _rate, pointvalue)
    // Stale-exit fills live inside the walk, ordered with live fills at
    // frozen own-leg levels (TV interleaves stale and live bracket fills
    // within the bar).
    if array.size(e.queue) > 0
        float openFillPx = e.cfg.process_orders_on_close ? c : o
        array<string> qids = array.new<string>()
        for qd in e.queue
            array.push(qids, qd.id)
        int qi = 0
        while qi < array.size(qids)
            Order od = na
            for qd in e.queue
                if qd.id == array.get(qids, qi)
                    od := qd
                    break
            if not na(od) and od.dir == 0
                bool filled = false
                string target = str.replace(od.id, "__close__", "")
                float closeQty = od.qty
                bool closedAny = false
                if array.size(e.legs) > 0
                    bool lifo = e.cfg.close_entries_rule == "LIFO"
                    int li = lifo ? array.size(e.legs) - 1 : 0
                    while (lifo ? li >= 0 : li < array.size(e.legs)) and (na(closeQty) or closeQty > PT_QTY_EPS)
                        OpenTrade lg = array.get(e.legs, li)
                        if target == "" or lg.entry_id == target
                            float q = na(closeQty) ? _stepFloor(e, lg.qty * od.qty_percent / 100.0) : math.min(closeQty, lg.qty)
                            float px = _fillPrice(e, openFillPx, -lg.dir)
                            string _tvCloseComment = od.comment == "" ? "Close entry(s) order " + target : od.comment
                            if na(closeQty) or q >= lg.qty
                                _closeLeg(e, li, px, t, "close", _rate, pointvalue, _tvCloseComment)
                                li += lifo ? -1 : 0
                            else
                                float ecPart = lg.entry_commission * q / lg.qty
                                float maePart = lg.max_drawdown * q / lg.qty
                                float mfePart = lg.max_runup * q / lg.qty
                                array.set(e.legs, li, OpenTrade.new(lg.entry_id, lg.dir, lg.qty - q, lg.avg_price, lg.entry_time, lg.entry_commission - ecPart, lg.entry_bar_index, lg.max_drawdown - maePart, lg.max_runup - mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                array.push(e.legs, OpenTrade.new(lg.entry_id, lg.dir, q, lg.avg_price, lg.entry_time, ecPart, lg.entry_bar_index, maePart, mfePart, lg.entry_comment, lg.seq, lg.entry_equity, lg.max_equity_before))
                                _closeLeg(e, array.size(e.legs) - 1, px, t, "close", _rate, pointvalue, od.comment)
                                li += lifo ? -1 : 1
                            closedAny := true
                            closeQty := na(closeQty) ? na : closeQty - q
                        else
                            li += lifo ? -1 : 1
                if closedAny
                    _countFill(e, openFillPx, t, _rate, pointvalue)
                filled := true
                if filled
                    for di = array.size(e.queue) - 1 to 0
                        if array.get(e.queue, di).id == od.id
                            array.remove(e.queue, di)
            qi += 1
        qi := 0
        while qi < array.size(qids)
            Order od = na
            for qd in e.queue
                if qd.id == array.get(qids, qi)
                    od := qd
                    break
            if not na(od) and od.dir != 0
                bool filled = false
                if na(od.limit) and na(od.stop)
                    float px = _fillPrice(e, openFillPx, od.dir)
                    filled := _fillEntryOrder(e, od, px, t, _rate, pointvalue)
                if filled
                    for di = array.size(e.queue) - 1 to 0
                        if array.get(e.queue, di).id == od.id
                            array.remove(e.queue, di)
            qi += 1
    if array.size(e.legs) > 0
        _reserveExits(e)
        // TV law: R2 is NOT checked at the post-queue close — the start-of-bar
        // check (next bar's open) handles it at the correct time; a post-queue
        // check fires one bar early on entry bars.
        _marginCheck(e, o, t, _rate, pointvalue, c, true, false)
    if not e.cfg.process_orders_on_close
        _intrabarWalk(e, o, h, l, c, t, _rate, pointvalue)
    if array.size(e.legs) > 0
        for li = 0 to array.size(e.legs) - 1
            OpenTrade lg = array.get(e.legs, li)
            // TV law: don't mark MAE/MFE on the entry bar. The entry fills at
            // close (POOC=true), but the low/high happened before the fill.
            if lg.entry_bar_index != e.bar_index
                float adverse  = lg.dir == 1 ? lg.avg_price - l : h - lg.avg_price
                if adverse > 0
                    lg.max_drawdown := math.max(lg.max_drawdown, lg.qty * adverse * pointvalue * _rate)
                float favorable = lg.dir == 1 ? h - lg.avg_price : lg.avg_price - l
                if favorable > 0
                    lg.max_runup := math.max(lg.max_runup, lg.qty * favorable * pointvalue * _rate)
                float legDD = not na(lg.max_equity_before) and not na(lg.entry_equity) ? lg.max_equity_before - (lg.entry_equity - lg.max_drawdown) : na
                if not na(legDD) and legDD > e.max_dd_value
                    e.max_dd_value := legDD
                    e.max_dd_peak := lg.max_equity_before
            array.set(e.legs, li, lg)
    _refreshPosition(e, c, _rate, pointvalue)
    e.prev_close := c
    if e.cfg.history_cap > 0 and array.size(e.equity_series) >= e.cfg.history_cap
        array.shift(e.equity_series)
    array.push(e.equity_series, e.equity + e.open_profit)
    float eqNow = e.equity + e.open_profit
    if na(e.equity_peak)
        e.equity_peak := e.cfg.initial_capital
        e.equity_trough := e.cfg.initial_capital
    e.equity_peak := math.max(e.equity_peak, eqNow)
    e.equity_trough := math.min(e.equity_trough, eqNow)
    e.max_runup_value := math.max(e.max_runup_value, eqNow - e.equity_trough)
    if na(e.realized_equity_peak)
        e.realized_equity_peak := e.cfg.initial_capital
        e.realized_equity_trough := e.cfg.initial_capital
    e.realized_equity_peak := math.max(e.realized_equity_peak, e.equity)
    e.realized_equity_trough := math.min(e.realized_equity_trough, e.equity)
    // ── Risk guard evaluation (close-time) ──
    // R2 basis: intraday peak equity (anchored at the day's start equity).
    // na-anchor is day_start (same TV law as _riskCheckIntraday above).
    if na(e.day_max_equity)
        e.day_max_equity := na(e.day_start_equity) ? eqNow : math.max(e.day_start_equity, eqNow)
    e.day_max_equity := math.max(e.day_max_equity, eqNow)
    // R2 max_intraday_loss: checked at START of onBar (before walk), not here.
    // The close-time day_max_equity update stays for the NEXT bar's check.
    bool _adverseFirst2b = false
    float _netAfter = _liveNet(e)
    if _netAfter != 0
        bool _highFirstGeo = math.abs(h - o) < math.abs(o - l)
        _adverseFirst2b := _netAfter > 0 ? not _highFirstGeo : _highFirstGeo
    if not _adverseFirst2b and e.position_size != 0
        float advPx = e.position_size > 0 ? l : h
        _marginCheck(e, advPx, t, _rate, pointvalue, c, false, true)
    if e.position_size != 0 or e.mc_deferred
        closeMc(e, c, t, _rate, pointvalue)
//@function netprofit
//@description Total currency value of all completed trades. Mirrors `strategy.netprofit`.
//@param e Engine instance.
//@returns Profit/loss in account currency.
export netprofit(PTEngine e) => e.equity - e.cfg.initial_capital
//@function convert_to_account
//@description Converts the value from the currency that the symbol on the chart is traded in (syminfo.currency) to the currency used by the strategy (`strategy.account_currency`). Mirrors `strategy.convert_to_account()`.
//@param e Engine instance.
//@param value Value in symbol currency.
//@param rate Optional conversion-rate override. Default: `na` (auto-computed from `syminfo.currency` to `e.cfg.currency`).
//@returns Value in account currency.
export convert_to_account(PTEngine e, float value, float rate = na) => value * _rateForEngine(e, rate)
//@function convert_to_symbol
//@description Converts the value from the currency used by the strategy (`strategy.account_currency`) to the currency that the symbol on the chart is traded in (syminfo.currency). Mirrors `strategy.convert_to_symbol()`.
//@param e Engine instance.
//@param value Value in account currency.
//@param rate Optional conversion-rate override. Default: `na` (auto-computed).
//@returns Value in symbol currency.
export convert_to_symbol(PTEngine e, float value, float rate = na) => value / _rateForEngine(e, rate)
//@function default_entry_qty
//@description Calculates the default quantity, in units, of an entry order from `strategy.entry`() or `strategy.order`() if it were to fill at the specified fill_price value. The calculation depends on several strategy properties, including default_qty_type, default_qty_value, currency, and other parameters in the strategy() function and their representation in the "Properties" tab of the strategy's settings. Mirrors `strategy.default_entry_qty()`.
//@param e Engine instance.
//@param fill_price Assumed fill price.
//@returns Quantity.
export default_entry_qty(PTEngine e, float fill_price) => _defaultQty(e, fill_price)
_capitalHeld(PTEngine e, float price) =>
    float s = 0.0
    for lg in e.legs
        s += lg.qty * price * (lg.dir == 1 ? e.cfg.margin_long : e.cfg.margin_short) / 100.0
    s
//@function capital_held
//@description Cash tied up in the current position(s). Mirrors `strategy.capital_held`.
//@param e Engine instance.
//@param price Parameter `price`. Default: `na` (uses the last onBar close, like TV's zero-arg builtin).
//@returns Capital in account currency.
export capital_held(PTEngine e, float price = na) =>
    float px = na(price) ? e._bar_c : price
    float result = na
    if e.cfg.margin_long != 100.0 or e.cfg.margin_short != 100.0
        result := array.size(e.legs) == 0 ? 0.0 : _capitalHeld(e, px)
    result
// ── §6 · Analytics engine — statistics & performance table ───────────────────
const float INFINITY_CAP = 999.0
const float MS_PER_DAY = 86400000.0
const float MS_PER_YEAR = 31556952000.0
const int LOSS_DURATION_HISTORY_LIMIT = 100
//@type MTMStats
//@description Indicator-grade backtest statistics container with 50+ metric fields. Populated by runStats() from engine trade and equity data.
export type MTMStats
    //@field totalTrades Number of closed trades.
    int totalTrades
    //@field winTrades Number of winning trades.
    int winTrades
    //@field lossTrades Number of losing trades.
    int lossTrades
    //@field evenTrades Number of break-even trades.
    int evenTrades
    //@field winRate Winning trades / total trades (0-1).
    float winRate
    //@field lossRate Losing trades / total trades (0-1).
    float lossRate
    //@field beRate Break-even trades / total trades (0-1).
    float beRate
    //@field avgWinPct Average win percentage (positive)
    float avgWinPct
    //@field avgLossPct Average loss percentage (positive number)
    float avgLossPct
    //@field avgTradePct Average trade percentage (expectancy)
    float avgTradePct
    //@field profitFactor Gross profit / Gross loss
    float profitFactor
    //@field payoffRatio Average win / Average loss
    float payoffRatio
    //@field expectancy Expected return per trade (%)
    float expectancy
    //@field rExpectancy Expected return per trade in R-multiples (1R = avgLossPct)
    float rExpectancy
    //@field grossProfit Total profit from winning trades ($)
    float grossProfit
    //@field grossLoss Total loss from losing trades ($)
    float grossLoss
    //@field netProfit Net profit ($)
    float netProfit
    //@field netProfitPct Net profit as percentage of initial capital
    float netProfitPct
    //@field compEffect Additional net profit generated by compounding ($)
    float compEffect
    //@field sharpe Annualized Sharpe ratio
    float sharpe
    //@field sortino Annualized Sortino ratio
    float sortino
    //@field calmar Calmar/MAR ratio (CAGR / MaxDD)
    float calmar
    //@field martin Martin ratio (CAGR / Ulcer Index)
    float martin
    //@field maxDrawdown Maximum drawdown ($)
    float maxDrawdown
    //@field maxDrawdownPct Maximum drawdown (%)
    float maxDrawdownPct
    //@field currentDrawdown Current drawdown ($)
    float currentDrawdown
    //@field currentDrawdownPct Current drawdown (%)
    float currentDrawdownPct
    //@field avgDrawdownPct Average drawdown (%)
    float avgDrawdownPct
    //@field maxEquity Peak equity reached ($)
    float maxEquity
    //@field minEquity Minimum equity reached ($)
    float minEquity
    //@field cagr Compound Annual Growth Rate (%)
    float cagr
    //@field monthlyReturn Average monthly return (%)
    float monthlyReturn
    //@field maxConsecWins Maximum consecutive winning trades
    int maxConsecWins
    //@field maxConsecLosses Maximum consecutive losing trades
    int maxConsecLosses
    //@field avgTradeDuration Average trade duration (ms)
    float avgTradeDuration
    //@field avgWinDuration Average winning trade duration (ms)
    float avgWinDuration
    //@field avgLossDuration Average losing trade duration (ms)
    float avgLossDuration
    //@field timeInMarketPct Percent of backtest period spent in trades
    float timeInMarketPct
    //@field tradesPerMonth Average trades per month
    float tradesPerMonth
    //@field tradesPerYear Average trades per year
    float tradesPerYear
    //@field skewness Return distribution skewness
    float skewness
    //@field kurtosis Return distribution Pearson kurtosis (normal ≈ 3)
    float kurtosis
    //@field var95 Value at Risk at 95% confidence (%)
    float var95
    //@field cvar95 Conditional VaR at 95% confidence (%)
    float cvar95
    //@field totalCommission Total commission paid across all trades ($)
    float totalCommission
    //@field ulcerIndex Ulcer Index (RMS of drawdowns)
    float ulcerIndex
    //@field riskOfRuin Probability of account ruin
    float riskOfRuin
    //@field pValue Statistical significance p-value
    float pValue
    //@field zScore Z-score of win rate vs expected
    float zScore
    //@field alpha Excess return vs benchmark (%)
    float alpha
    //@field beta Correlation with benchmark
    float beta
    //@field buyHoldReturn Simple Buy & Hold return (%)
    float buyHoldReturn
    //@field equityRSquared Coefficient of determination (R²) of equity curve
    float equityRSquared
    //@field firstTradeTime Timestamp of first trade entry
    int firstTradeTime
    //@field lastTradeTime Timestamp of last trade exit
    int lastTradeTime
    //@field tradingPeriodDays Total number of days in trading period
    float tradingPeriodDays
    //@field sqn System Quality Number
    float sqn
    //@field initialCapital Starting capital ($)
    float initialCapital
    //@field riskFreeRate Annual risk-free rate decimal carried from UltratestInput (Sharpe/Sortino/alpha tooltips)
    float riskFreeRate = 0.02
    //@field avgCommissionPct Mean per-trade commission as % of entry notional
    float avgCommissionPct = na
//@type MTMConfig
//@description Table configuration settings. Stores visual styling and display options for backtest tables.
export type MTMConfig
    //@field colorBullish Color for positive/good values
    color colorBullish
    //@field colorBearish Color for negative/bad values
    color colorBearish
    //@field colorText Primary text color
    color colorText
    //@field colorTextMuted Muted/secondary text color
    color colorTextMuted
    //@field colorBg Table background color
    color colorBg
    //@field colorHeader Header background color
    color colorHeader
    //@field colorBorder Border color
    color colorBorder
    //@field textSize Text size for all tables
    string textSize
    //@field commissionInfo Commission info string for display
    string commissionInfo
    //@field showComplementary Show complementary row in main table
    bool showComplementary
    //@field showRExpectancy Show R-expectancy (R-multiple) instead of %
    bool showRExpectancy
    //@field costInput Commission cost per trade (for footer display)
    float costInput
//@type UltratestInput — Data passed from the calling indicator/strategy
type UltratestInput
    array<float> equityPerBar
    array<float> returnsPerBar
    array<float> tradeResults
    float initialCapital
    int firstTradeTime
    int lastTradeTime
    int winTrades
    int lossTrades
    int beTrades
    float totalProfit
    float totalLoss
    float avgWin
    float avgLoss
    float expectancy
    int totalTradeDuration
    array<int> winDurations
    array<int> lossDurations
    float maxDrawdown
    float maxDrawdownPeak = na
    array<float> riskMultipliers
    array<float> betaStrategyReturns
    array<float> betaSpxReturns
    float peakEquity
    bool isBullish
    float firstBarClose
    float spxFirstClose
    float spxLastClose
    bool costBool
    float costAmount
    float totalCommission
    float riskFreeRate = 0.02
    float liveEquity = na
    float avgCommissionPct = na
//@type ThresholdConfig — Threshold values and colors for metric rendering
type ThresholdConfig
    float sharpeExc
    float sharpeGood
    float sharpeOk
    color sharpeBear
    color sharpeNeutral
    color sharpeOrange
    color sharpeBull
    float ddSevere
    float ddMod
    float ddMild
    color ddSevereColor
    color ddModColor
    color ddOrange
    color ddGoodColor
    float rorHigh
    float rorMod
    float rorLow
    color rorHighColor
    color rorModColor
    color rorOrange
    color rorLowColor
    float r2Poor
    float r2Mod
    float r2Good
    color r2PoorColor
    color r2ModColor
    color r2Orange
    color r2GoodColor
    float kurtHigh
    float kurtMod
    float kurtOk
    color kurtHighColor
    color kurtModColor
    color kurtOrange
    color kurtGoodColor
    float skewVNeg
    float skewModNeg
    float skewPos
    float skewVPos
    color skewVNegColor
    color skewModNegColor
    color skewNeutral
    color skewPosColor
    float payoffPoor
    float payoffBE
    float payoffGood
    color payoffPoorColor
    color payoffBEColor
    color payoffOrange
    color payoffGoodColor
    float pfPoor
    float pfBE
    float pfGood
    color pfPoorColor
    color pfBEColor
    color pfOrange
    color pfGoodColor
    float ulcerHigh
    float ulcerLow
    color ulcerHighColor
    color ulcerModColor
    color ulcerOrange
    color ulcerLowColor
    float wrLow
    float wrOk
    float wrHigh
    color wrLowColor
    color wrOkColor
    color wrOrange
    color wrHighColor
    float cagrPoor
    float cagrOk
    float cagrGood
    color cagrPoorColor
    color cagrOkColor
    color cagrOrange
    color cagrGoodColor
    float pInsig
    float pMod
    float pSig
    color pInsigColor
    color pModColor
    color pOrange
    color pSigColor
    float calmarPoor
    float calmarBE
    float calmarGood
    color calmarPoorColor
    color calmarBEColor
    color calmarOrange
    color calmarGoodColor
    float betaHigh
    float betaLow
    color betaHighColor
    color betaLowColor
    color betaGoodColor
calcRiskFreePerTrade(float riskFreeRate, float tradesPerYear, bool useGeometric = true) =>
    if riskFreeRate <= 0.0 or tradesPerYear <= 0.0
        0.0
    else if useGeometric
        math.pow(1.0 + riskFreeRate, 1.0 / tradesPerYear) - 1.0
    else
        riskFreeRate / tradesPerYear
calcSharpe(array<float> returns, float tradesPerYear, float riskFreeRate) =>
    int n = array.size(returns)
    if n < 2 or tradesPerYear <= 0.0
        na
    else
        float meanReturn = array.avg(returns)
        float stdDev = array.stdev(returns, biased = false)
        float riskFreePerTrade = calcRiskFreePerTrade(riskFreeRate, tradesPerYear, true)
        if nz(stdDev, 0.0) <= 0.0
            meanReturn > riskFreePerTrade ? INFINITY_CAP : (meanReturn < riskFreePerTrade ? -INFINITY_CAP : na)
        else
            float excessReturn = meanReturn - riskFreePerTrade
            float sharpe = excessReturn / stdDev
            sharpe := sharpe * math.sqrt(tradesPerYear)
            math.abs(sharpe) >= INFINITY_CAP ? (sharpe > 0.0 ? INFINITY_CAP : -INFINITY_CAP) : sharpe
calcSortino(array<float> returns, float tradesPerYear, float riskFreeRate) =>
    int n = array.size(returns)
    if n < 2 or tradesPerYear <= 0.0 or na(tradesPerYear)
        na
    else
        float meanReturn = array.avg(returns)
        float riskFreePerTrade = calcRiskFreePerTrade(riskFreeRate, tradesPerYear, true)
        float sumSqDown = 0.0
        int downsideCount = 0
        for i = 0 to n - 1
            float ret = array.get(returns, i)
            if ret < riskFreePerTrade
                float deviation = ret - riskFreePerTrade
                sumSqDown += deviation * deviation
                downsideCount += 1
        if downsideCount == 0
            meanReturn > riskFreePerTrade ? INFINITY_CAP : na
        else
            float downsideDev = math.sqrt(sumSqDown / n)
            if downsideDev <= 0.0
                meanReturn > riskFreePerTrade ? INFINITY_CAP : na
            else
                float excessReturn = meanReturn - riskFreePerTrade
                float sortino = excessReturn / downsideDev
                sortino := sortino * math.sqrt(tradesPerYear)
                math.abs(sortino) >= INFINITY_CAP ? (sortino > 0.0 ? INFINITY_CAP : -INFINITY_CAP) : sortino
calcProfitFactor(float grossProfit, float grossLoss) =>
    if grossLoss <= 0.0
        grossProfit > 0.0 ? INFINITY_CAP : 1.0
    else
        float pfRaw = grossProfit / grossLoss
        pfRaw >= INFINITY_CAP ? INFINITY_CAP : pfRaw
calcExpectancy(float winRate, float avgWinPct, float avgLossPct, float lossRate) =>
    float effectiveLossRate = na(lossRate) ? 1.0 - winRate : lossRate
    (winRate * avgWinPct) - (effectiveLossRate * avgLossPct)
calcRiskOfRuin(int wins, int losses, float avgWinPct, float avgLossPct, float riskPerTrade, int evenTrades) =>
    int decisive = wins + losses
    int total = decisive + evenTrades
    int minSamples = math.max(30, int(math.ceil(100.0 / math.max(avgLossPct, 0.5))))
    if decisive == 0 or avgLossPct <= 0.0 or total < minSamples
        na
    else if losses == 0
        0.0
    else if wins == 0
        1.0
    else
        float wR = float(wins) / float(decisive)
        float payoff = avgWinPct / avgLossPct
        float beRate = total > 0 ? float(evenTrades) / float(total) : 0.0
        if wR <= 0.0 or wR >= 1.0 or payoff <= 0.0 or riskPerTrade <= 0.0
            na
        else
            float p = wR
            float q = 1.0 - p
            float b = payoff
            float advantage = p * b - q
            float riskFrac = riskPerTrade / 100.0
            float units = riskFrac > 0.0 ? 1.0 / math.max(riskFrac, 0.0001) : na
            float beAdj = 1.0 - math.min(math.max(beRate, 0.0), 1.0) * 0.15
            float effectiveUnits = units * beAdj
            if advantage <= 0.0
                1.0
            else if advantage >= 0.999999
                0.0
            else
                float numerator = 1.0 - advantage
                float denominator = 1.0 + advantage
                float ratio = denominator > 0.0 ? numerator / denominator : 0.0
                float ror = ratio > 0.0 and effectiveUnits > 0.0 ? math.pow(ratio, effectiveUnits) : 0.0
                math.max(0.0, math.min(1.0, ror)) * 100.0
calcPValueGeneric(int wins, int total, float expectedWinRate = na, int minSampleSize = 30, bool useContinuityCorrection = true) =>
    if total < minSampleSize
        na
    else
        float observedWR = float(wins) / float(total)
        float expWR = na(expectedWinRate) ? 0.5 : expectedWinRate
        expWR := math.max(0.01, math.min(0.99, expWR))
        float stdError = math.sqrt((expWR * (1.0 - expWR)) / float(total))
        if stdError <= 0.0001
            na
        else
            float continuityAdj = 0.5 / float(total)
            float adjustedObserved = useContinuityCorrection ? (observedWR > expWR ? observedWR - continuityAdj : observedWR + continuityAdj) : observedWR
            float zScore = (adjustedObserved - expWR) / stdError
            float absZ = math.abs(zScore)
            float a1 = 0.254829592
            float a2 = -0.284496736
            float a3 = 1.421413741
            float a4 = -1.453152027
            float a5 = 1.061405429
            float p = 0.3275911
            float t = 1.0 / (1.0 + p * absZ)
            float erf = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * math.exp(-absZ * absZ)
            float cdf = 0.5 * (1.0 + (zScore >= 0.0 ? erf : -erf))
            math.min(1.0, 2.0 * math.min(cdf, 1.0 - cdf))
calcPValue(int wins, int total, float avgWinPct, float avgLossPct) =>
    if avgLossPct <= 0.0
        calcPValueGeneric(wins, total)
    else
        float payoffRatio = avgWinPct / avgLossPct
        float expectedWR = 1.0 / (1.0 + payoffRatio)
        calcPValueGeneric(wins, total, expectedWR)
calcBeta(array<float> strategyReturns, array<float> marketReturns) =>
    int n = math.min(array.size(strategyReturns), array.size(marketReturns))
    if n < 2
        na
    else
        array<float> sRet = n < array.size(strategyReturns) ? array.slice(strategyReturns, 0, n) : strategyReturns
        array<float> mRet = n < array.size(marketReturns) ? array.slice(marketReturns, 0, n) : marketReturns
        float cov = array.covariance(sRet, mRet, true)
        float varM = array.variance(mRet, true)
        varM > 0.0 ? cov / varM : na
calcUlcerIndex(array<float> drawdowns) =>
    int n = array.size(drawdowns)
    if n == 0
        na
    else
        float sumSq = 0.0
        for i = 0 to n - 1
            float dd = array.get(drawdowns, i)
            sumSq += dd * dd
        math.sqrt(sumSq / n)
calcSkewness(array<float> returns) =>
    int n = array.size(returns)
    if n < 4
        na
    else
        float mean = array.avg(returns)
        float sumSquared = 0.0, float sumCubed = 0.0
        for i = 0 to n - 1
            float diff = array.get(returns, i) - mean
            float diffSq = diff * diff
            sumSquared += diffSq
            sumCubed += diffSq * diff
        float m2 = sumSquared / float(n)
        float m3 = sumCubed / float(n)
        float b1 = m2 > 0.0 ? m3 / math.pow(m2, 1.5) : 0.0
        float correction = math.sqrt(float(n) * float(n - 1)) / float(n - 2)
        correction * b1
calcKurtosis(array<float> returns) =>
    int n = array.size(returns)
    if n < 4
        na
    else
        float mean = array.avg(returns)
        float sumSquared = 0.0, float sumQuad = 0.0
        for i = 0 to n - 1
            float diff = array.get(returns, i) - mean
            float diffSq = diff * diff
            sumSquared += diffSq
            sumQuad += diffSq * diffSq
        float variance = sumSquared / float(n - 1)
        float stdDev = math.sqrt(variance)
        if stdDev <= 0.0
            na
        else
            float s4 = math.pow(stdDev, 4)
            float term1Num = float(n) * float(n + 1) * sumQuad
            float term1Den = float(n - 1) * float(n - 2) * float(n - 3) * s4
            float term2Num = 3.0 * math.pow(float(n - 1), 2)
            float term2Den = float(n - 2) * float(n - 3)
            float excessKurtosis = (term1Den == 0.0 or term2Den == 0.0) ? na : (term1Num / term1Den) - (term2Num / term2Den)
            na(excessKurtosis) ? na : excessKurtosis + 3.0
//@type RollingStats — Rolling window analysis results
type RollingStats
    int windowSize
    float expectancyMin
    float expectancyMax
    float sharpeMin
    float sharpeMax
    float sortinoMin
    float sortinoMax
    float expectancyMean
    float expectancyStdDev
calcRollingStats(array<float> returns, int windowSize = 0, float tradesPerYear = na, float riskFreeRate = 0.02) =>
    int n = array.size(returns)
    if n < 1
        RollingStats.new(0, na, na, na, na, na, na, na, na)
    else
        int window = windowSize > 0 ? windowSize : math.max(1, int(math.ceil(float(n) / 12.0)))
        float tpy = tradesPerYear
        array<float> expValues = array.new<float>()
        float expMin = 999999.0, float expMax = -999999.0
        float sharpeMin = 999999.0, float sharpeMax = -999999.0
        float sortinoMin = 999999.0, float sortinoMax = -999999.0
        float rfPerTrade = tpy > 0 and riskFreeRate > 0 ? math.pow(1.0 + riskFreeRate, 1.0 / tpy) - 1.0 : 0.0, float annualFactor = tpy > 0 ? math.sqrt(tpy) : 1.0
        int startIdx = 0
        while startIdx + window <= n
            int actualEnd = startIdx + window - 1
            array<float> windowSlice = array.slice(returns, startIdx, actualEnd + 1)
            float windowMean = array.avg(windowSlice)
            float windowExp = windowMean * 100.0
            expMin := math.min(expMin, windowExp)
            expMax := math.max(expMax, windowExp)
            array.push(expValues, windowExp)
            float windowStdev = nz(array.stdev(windowSlice, biased = false), 0.0), float windowSharpe = na
            if windowStdev > 0.0
                windowSharpe := ((windowMean - rfPerTrade) / windowStdev) * annualFactor
            else if windowMean - rfPerTrade > 0
                windowSharpe := INFINITY_CAP
            if not na(windowSharpe)
                sharpeMin := math.min(sharpeMin, windowSharpe)
                sharpeMax := math.max(sharpeMax, windowSharpe)
            float downsideVar = 0.0
            int downsideCount = 0
            for ret in windowSlice
                if ret < rfPerTrade
                    float diff = ret - rfPerTrade
                    downsideVar += diff * diff
                    downsideCount += 1
            float windowSortino = na
            if downsideCount > 0
                float downsideDev = math.sqrt(downsideVar / float(window))
                if downsideDev > 0.0
                    windowSortino := ((windowMean - rfPerTrade) / downsideDev) * annualFactor
            else if windowMean > rfPerTrade
                windowSortino := INFINITY_CAP
            if not na(windowSortino)
                sortinoMin := math.min(sortinoMin, windowSortino)
                sortinoMax := math.max(sortinoMax, windowSortino)
            startIdx += window
        expMin := expMin == 999999.0 ? na : expMin
        expMax := expMax == -999999.0 ? na : expMax
        sharpeMin := sharpeMin == 999999.0 ? na : sharpeMin
        sharpeMax := sharpeMax == -999999.0 ? na : sharpeMax
        sortinoMin := sortinoMin == 999999.0 ? na : sortinoMin
        sortinoMax := sortinoMax == -999999.0 ? na : sortinoMax
        float expMean = array.avg(expValues), float expStdDev = array.stdev(expValues)
        RollingStats.new(
             window,
             expMin, expMax,
             sharpeMin, sharpeMax,
             sortinoMin, sortinoMax,
             expMean, expStdDev)
_calcTailRisk(array<float> sorted, float tailProb) =>
    int n = array.size(sorted)
    if n == 0
        [na, na]
    else
        int varIdx = int(math.floor(float(n) * tailProb))
        varIdx := math.max(0, math.min(n - 1, varIdx))
        float varVal = math.max(0.0, -array.get(sorted, varIdx)) * 100.0
        int tailCount = math.max(1, varIdx)
        float sumTail = array.sum(array.slice(sorted, 0, tailCount))
        float cvarVal = math.max(0.0, -(sumTail / float(tailCount))) * 100.0
        [varVal, cvarVal]
calcHistoricalVaR(array<float> returns, float confidence = 95.0) =>
    int n = array.size(returns)
    if n < 2
        na
    else
        array<float> sorted = array.copy(returns)
        array.sort(sorted)
        float tailProb = (100.0 - confidence) / 100.0
        [varVal, _] = _calcTailRisk(sorted, tailProb)
        varVal
calcCVaR(array<float> returns, float confidence = 0.95) =>
    int n = array.size(returns)
    if n < 2
        na
    else
        array<float> sorted = array.copy(returns)
        array.sort(sorted)
        float tailProb = 1.0 - confidence
        [_, cvarVal] = _calcTailRisk(sorted, tailProb)
        cvarVal
calcEquityRSquared(array<float> equity) =>
    int n = array.size(equity)
    if n < 3
        na
    else
        int effN = n - 1
        float nF = float(effN)
        float nM1 = float(effN - 1)
        float sumX = nF * nM1 / 2.0
        float sumX2 = nM1 * (2.0 * nM1 + 1.0) * nF / 6.0
        float sumY = 0.0, sumY2 = 0.0, sumXY = 0.0
        for i = 1 to n - 1
            float yi = array.get(equity, i)
            float xi = float(i - 1)
            sumY += yi
            sumY2 += yi * yi
            sumXY += xi * yi
        float denom = nF * sumX2 - sumX * sumX
        if denom == 0.0
            na
        else
            float slope = (nF * sumXY - sumX * sumY) / denom
            float intercept = (sumY - slope * sumX) / nF
            float ssTot = sumY2 - sumY * sumY / nF
            float ssRes = sumY2 - 2.0 * slope * sumXY - 2.0 * intercept * sumY + slope * slope * sumX2 + 2.0 * slope * intercept * sumX + nF * intercept * intercept
            ssTot == 0.0 ? na : math.max(0.0, math.min(1.0, 1.0 - (ssRes / ssTot)))
getThresholdConfig(color bear, color neutral, color orange, color bull) =>
    ThresholdConfig.new(
        1.0, 0.5, 0.3, bear, neutral, orange, bull,
        30.0, 20.0, 0.0, bear, orange, orange, bull,
        0.25, 0.1, 0.05, bear, neutral, orange, bull,
        0.3, 0.5, 0.8, bear, neutral, orange, bull,
        6.0, 4.0, 3.0, bear, neutral, orange, bull,
        -1.5, -0.5, 0.5, 1.5, bear, neutral, neutral, bull,
        0.8, 1.0, 1.5, bear, neutral, orange, bull,
        0.8, 1.0, 1.5, bear, neutral, orange, bull,
        10.0, 5.0, bear, neutral, orange, bull,
        0.30, 0.40, 0.50, bear, neutral, orange, bull,
        0.0, 10.0, 20.0, bear, neutral, orange, bull,
        0.5, 0.05, 0.01, bear, neutral, orange, bull,
        0.0, 0.5, 1.0, bear, neutral, orange, bull,
        1.3, 0.7, bear, orange, bull
    )
//@type ComplementaryData — Pre-calculated metrics for complementary row
type ComplementaryData
    float payoffRatio
    float avgTradePct
    float avgWinPct
    float avgLossPct
    float avgRisk
    float martin
    float rollingExpMin
    float rollingExpMax
    float rollingSortMin
    float rollingSortMax
    float rollingSharpeMin
    float rollingSharpeMax
    float rollingExpMean
    float rollingExpStdDev
    int rollingWindowSize
    float avgWinDurationMs
    float maxEquityPct
    float alpha
    float buyHoldValue
    float beta
    float minEquityPct
    float avgLossDurationMs
    float currentDDPct
    float sqn
    float kurtosis
    float skewness
    int nMoments
    float var95
    float ulcerIndex
    float compEffectPct
    float initialCapital
    float compEffect
    array<float> riskMultipliers
const float MS_PER_MONTH = 2629746000.0
const float MS_PER_HOUR = 3600000.0
const float MS_PER_MINUTE = 60000.0
const float MS_PER_SECOND = 1000.0
//@enum FormatMode
//@description Enum for value formatting modes.
enum FormatMode
    number
    percent
    ratio
    pvalue
capValue(float value) =>
    na(value) ? na : math.min(value, INFINITY_CAP)
formatValue(float value, FormatMode mode = FormatMode.number, int decimals = 2, bool showSign = true, float infinityThreshold = 999) =>
    if na(value)
        "-"
    else
        string format = decimals == 0 ? "#" : decimals == 1 ? "#.#" : decimals == 3 ? "#.###" : decimals == 4 ? "#.####" : "#.##"
        switch mode
            FormatMode.percent => (showSign and value > 0.0 ? "+" : "") + str.tostring(value, format) + "%"
            FormatMode.ratio  => value >= infinityThreshold ? "∞" : str.tostring(value, format)
            FormatMode.pvalue => str.tostring(value, "0.000")
            => str.tostring(value, format)
formatCapped(float val, FormatMode mode, int decimals = 2, bool showSign = false) =>
    na(val) or val >= INFINITY_CAP ? "-" : formatValue(val, mode, decimals, showSign)
formatDuration(float durationMs) =>
    if nz(durationMs, 0.0) < 0.0
        "-"
    else
        float remaining = durationMs
        int years = int(math.floor(remaining / MS_PER_YEAR))
        remaining -= float(years) * MS_PER_YEAR
        int months = int(math.floor(remaining / MS_PER_MONTH))
        remaining -= float(months) * MS_PER_MONTH
        int days = int(math.floor(remaining / MS_PER_DAY))
        remaining -= float(days) * MS_PER_DAY
        int hours = int(math.floor(remaining / MS_PER_HOUR))
        remaining -= float(hours) * MS_PER_HOUR
        int minutes = int(math.floor(remaining / MS_PER_MINUTE))
        remaining -= float(minutes) * MS_PER_MINUTE
        int seconds = int(math.floor(remaining / MS_PER_SECOND))
        string result = switch
            years > 0 =>
                string sec = months > 0 ? str.tostring(months) + "mo" : (days > 0 ? str.tostring(days) + "d" : "")
                str.trim(str.replace_all(str.tostring(years) + "y" + " " + sec, "  ", " "))
            months > 0 =>
                string sec = days > 0 ? str.tostring(days) + "d" : (hours > 0 ? str.tostring(hours) + "h" : "")
                str.trim(str.replace_all(str.tostring(months) + "mo" + " " + sec, "  ", " "))
            days > 0 =>
                string sec = hours > 0 ? str.tostring(hours) + "h" : (minutes > 0 ? str.tostring(minutes) + "m" : "")
                str.trim(str.replace_all(str.tostring(days) + "d" + " " + sec, "  ", " "))
            hours > 0 =>
                string sec = minutes > 0 ? str.tostring(minutes) + "m" : (seconds > 0 ? str.tostring(seconds) + "s" : "")
                str.trim(str.replace_all(str.tostring(hours) + "h" + " " + sec, "  ", " "))
            minutes > 0 =>
                string sec = seconds > 0 ? str.tostring(seconds) + "s" : ""
                str.trim(str.replace_all(str.tostring(minutes) + "m" + " " + sec, "  ", " "))
            => seconds > 0 ? str.tostring(seconds) + "s" : "<1s"
        str.trim(result)
formatIntelligentFrequency(float tradesPerMonth) =>
    if na(tradesPerMonth) or tradesPerMonth <= 0
        "0"
    else
        float perYear = tradesPerMonth * 12.0
        float perWeek = perYear / 52.0
        float perDay = perWeek / 7.0
        float perHour = perDay / 24.0
        float perMinute = perHour / 60.0
        float perSecond = perMinute / 60.0
        if perSecond >= 1.0
            formatValue(perSecond, FormatMode.number, 1, false) + "/s"
        else if perMinute >= 1.0
            formatValue(perMinute, FormatMode.number, 1, false) + "/min"
        else if perHour >= 1.0
            formatValue(perHour, FormatMode.number, 1, false) + "/hr"
        else if perDay >= 1.0
            formatValue(perDay, FormatMode.number, 1, false) + "/d"
        else if perWeek >= 1.0
            formatValue(perWeek, FormatMode.number, 1, false) + "/wk"
        else if tradesPerMonth >= 1.0
            formatValue(tradesPerMonth, FormatMode.number, 1, false) + "/mo"
        else
            formatValue(perYear, FormatMode.number, 2, false) + "/yr"
getPnLColor(float val, color bullColor, color bearColor, color muted = color.gray) =>
    na(val) ? muted : val > 0.0 ? bullColor : val < 0.0 ? bearColor : muted
_expStabilityColor(float mean, float stddev, bool isRMode, color bearColor) =>
    float absMean = not na(mean) ? math.abs(mean) : 0.0
    float cv = absMean > 0.0001 ? stddev / absMean : na
    float spread = not na(stddev) ? stddev * 2.0 : na
    not na(cv) and cv < 1.0 ? color.orange : not na(spread) and spread < (isRMode ? 0.2 : 0.1) ? color.orange : bearColor
_hdrCell(table t, int c, int r, string txt, MTMConfig cfg, string tt = na) =>
    table.cell(t, c, r, txt, bgcolor = cfg.colorHeader, text_color = cfg.colorText, text_size = cfg.textSize, tooltip = tt, text_formatting=text.format_bold)
_hdrCellC(table t, int c, int r, string txt, MTMConfig cfg, string tt = na) =>
    table.cell(t, c, r, txt, bgcolor = cfg.colorHeader, text_color = cfg.colorText, text_size = cfg.textSize, text_halign = text.align_center, tooltip = tt, text_formatting=text.format_bold)
_valCell(table t, int c, int r, string txt, color col, MTMConfig cfg, string tt = na) =>
    table.cell(t, c, r, txt, bgcolor = cfg.colorBg, text_color = col, text_size = cfg.textSize, tooltip = tt, text_formatting=text.format_bold)
_renderSectionHeaders(table bt, MTMConfig config) =>
    _hdrCellC(bt, 0, 0, "Performance Metrics", config)
    table.merge_cells(bt, 0, 0, 6, 0)
    _hdrCellC(bt, 7, 0, "Trade Statistics", config)
    table.merge_cells(bt, 7, 0, 14, 0)
    _hdrCellC(bt, 15, 0, "Risk Metrics", config)
    table.merge_cells(bt, 15, 0, 22, 0)
_renderColumnHeaders(table bt, MTMConfig config) =>
    string expHeader = config.showRExpectancy ? "R-Expect" : "Expectancy"
    array<string> headers = array.from(
         "Net Profit", "Payoff", "Sample Size", "Profit Factor", "CAGR", expHeader, "Monthly",
        "Avg Duration", "Max CW", "Max CL", "Win", "BE", "Loss", "Frequency", "Exposure",
        "Sharpe", "Sortino", "Max DD", "RoR", "R²", "MAR", "CVaR", "p-value")
    for i = 0 to 22
        _hdrCell(bt, i, 1, array.get(headers, i), config)
_renderPerformanceMetrics(table bt, MTMStats stats, MTMConfig config) =>
    float yearsElapsed = stats.tradingPeriodDays / (MS_PER_YEAR / MS_PER_DAY)
    color npColor = stats.netProfitPct > 20.0 ? config.colorBullish : stats.netProfitPct > 0.0 ? color.orange : config.colorBearish
    _valCell(bt, 0, 2, formatValue(stats.netProfitPct, FormatMode.percent), npColor, config, na)
    color wlColor = na(stats.payoffRatio) ? config.colorTextMuted : stats.payoffRatio > 1.5 ? config.colorBullish : stats.payoffRatio > 1.0 ? color.orange : config.colorBearish
    _valCell(bt, 1, 2, formatValue(stats.payoffRatio, FormatMode.number, 2, false), wlColor, config, na)
    color ssColor = stats.totalTrades >= 30 ? config.colorBullish : config.colorBearish
    _valCell(bt, 2, 2, str.tostring(stats.totalTrades), ssColor, config, na)
    color pfColor = stats.profitFactor >= 1.5 ? config.colorBullish : stats.profitFactor > 1.0 ? color.orange : config.colorBearish
    _valCell(bt, 3, 2, formatValue(stats.profitFactor, FormatMode.ratio, 2, false), pfColor, config, na)
    float cappedCagr = capValue(stats.cagr)
    string cagrDisplay = formatCapped(cappedCagr, FormatMode.percent)
    color cagrColor = na(cappedCagr) or cappedCagr >= INFINITY_CAP ? config.colorTextMuted : cappedCagr >= 10.0 ? config.colorBullish : cappedCagr > 0.0 ? color.orange : config.colorBearish
    _valCell(bt, 4, 2, cagrDisplay, cagrColor, config, na)
    float cappedExpectancy = capValue(stats.avgTradePct)
    string expDisplay = formatCapped(cappedExpectancy, FormatMode.percent)
    color expColor = na(cappedExpectancy) or cappedExpectancy >= INFINITY_CAP ? config.colorTextMuted : cappedExpectancy > 0.20 ? config.colorBullish : cappedExpectancy > 0.0 ? color.orange : config.colorBearish
    if config.showRExpectancy
        float rExp = stats.rExpectancy
        expDisplay := na(rExp) ? "-" : str.tostring(rExp, "#.###") + "R"
        expColor := na(rExp) ? config.colorTextMuted : rExp > 0.2 ? config.colorBullish : rExp > 0.0 ? color.orange : config.colorBearish
    _valCell(bt, 5, 2, expDisplay, expColor, config, na)
    float cappedMonthly = capValue(stats.monthlyReturn)
    string monthDisplay = formatCapped(cappedMonthly, FormatMode.percent)
    color monthColor = na(cappedMonthly) or cappedMonthly >= INFINITY_CAP ? config.colorTextMuted : cappedMonthly > 0.0 ? config.colorBullish : config.colorBearish
    _valCell(bt, 6, 2, monthDisplay, monthColor, config, na)
_renderTradeStats(table bt, MTMStats stats, MTMConfig config) =>
    _valCell(bt, 7, 2, formatDuration(stats.avgTradeDuration), config.colorTextMuted, config, na)
    _valCell(bt, 8, 2, str.tostring(stats.maxConsecWins), config.colorTextMuted, config, na)
    _valCell(bt, 9, 2, str.tostring(stats.maxConsecLosses), config.colorTextMuted, config, na)
    _valCell(bt, 10, 2, str.tostring(math.round(stats.winRate * 100)) + "%", config.colorTextMuted, config, na)
    float beRate = stats.totalTrades > 0 ? (float(stats.evenTrades) / float(stats.totalTrades)) * 100.0 : 0.0
    _valCell(bt, 11, 2, str.tostring(math.round(beRate)) + "%", config.colorTextMuted, config, na)
    _valCell(bt, 12, 2, str.tostring(math.round(stats.lossRate * 100)) + "%", config.colorTextMuted, config, na)
    string freqStr = formatIntelligentFrequency(stats.tradesPerMonth)
    _valCell(bt, 13, 2, freqStr, config.colorTextMuted, config, na)
    _valCell(bt, 14, 2, formatValue(stats.timeInMarketPct, FormatMode.percent, 2, false), config.colorTextMuted, config, na)
_renderRiskMetrics(table bt, MTMStats stats, MTMConfig config, ThresholdConfig tc) =>
    color sharpeColor = na(stats.sharpe) ? config.colorTextMuted : stats.sharpe >= INFINITY_CAP ? tc.sharpeBull : stats.sharpe > tc.sharpeExc ? tc.sharpeBull : stats.sharpe > tc.sharpeGood ? tc.sharpeOrange : stats.sharpe > tc.sharpeOk ? tc.sharpeNeutral : tc.sharpeBear
    string sharpeStr = na(stats.sharpe) ? "-" : stats.sharpe >= INFINITY_CAP ? "∞" : formatValue(stats.sharpe, FormatMode.number, 2, false)
    _valCell(bt, 15, 2, sharpeStr, sharpeColor, config, na)
    color sortinoColor = na(stats.sortino) ? config.colorTextMuted : stats.sortino >= INFINITY_CAP ? tc.sharpeBull : stats.sortino > tc.sharpeExc ? tc.sharpeBull : stats.sortino > tc.sharpeGood ? tc.sharpeOrange : stats.sortino > tc.sharpeOk ? tc.sharpeNeutral : tc.sharpeBear
    string sortinoStr = na(stats.sortino) ? "-" : stats.sortino >= INFINITY_CAP ? "∞" : formatValue(stats.sortino, FormatMode.number, 2, false)
    _valCell(bt, 16, 2, sortinoStr, sortinoColor, config, na)
    color ddColor = stats.maxDrawdownPct > tc.ddSevere ? tc.ddSevereColor : stats.maxDrawdownPct > tc.ddMod ? tc.ddModColor : stats.maxDrawdownPct > tc.ddMild ? tc.ddOrange : tc.ddGoodColor
    _valCell(bt, 17, 2, formatValue(-stats.maxDrawdownPct, FormatMode.percent, 2, false), ddColor, config, na)
    color rorColor = na(stats.riskOfRuin) ? config.colorTextMuted : stats.riskOfRuin > tc.rorHigh * 100.0 ? tc.rorHighColor : stats.riskOfRuin > tc.rorMod * 100.0 ? tc.rorModColor : stats.riskOfRuin > tc.rorLow * 100.0 ? tc.rorOrange : tc.rorLowColor
    _valCell(bt, 18, 2, formatValue(stats.riskOfRuin, FormatMode.percent, 2, false), rorColor, config, na)
    float r2 = stats.equityRSquared
    string r2Str = na(r2) ? "-" : formatValue(r2 * 100.0, FormatMode.percent, 1, false)
    color r2Color = na(r2) ? config.colorTextMuted : r2 > tc.r2Good ? tc.r2GoodColor : r2 > tc.r2Mod ? tc.r2Orange : r2 > tc.r2Poor ? tc.r2ModColor : tc.r2PoorColor
    _valCell(bt, 19, 2, r2Str, r2Color, config, na)
    float cappedCalmar = capValue(stats.calmar)
    string calmarDisplay = formatCapped(cappedCalmar, FormatMode.number, 2, false)
    color marColor = na(cappedCalmar) or cappedCalmar >= INFINITY_CAP ? config.colorTextMuted : cappedCalmar > tc.calmarGood ? tc.calmarGoodColor : cappedCalmar > tc.calmarBE ? tc.calmarOrange : cappedCalmar > tc.calmarPoor ? tc.calmarBEColor : tc.calmarPoorColor
    _valCell(bt, 20, 2, calmarDisplay, marColor, config, na)
    color cvarColor = na(stats.cvar95) ? config.colorTextMuted : stats.cvar95 > 5.0 ? config.colorBearish : config.colorBullish
    _valCell(bt, 21, 2, formatValue(stats.cvar95, FormatMode.percent, 2, false), cvarColor, config, na)
    color pColor = na(stats.pValue) ? config.colorTextMuted : stats.pValue > tc.pInsig ? tc.pInsigColor : stats.pValue > tc.pMod ? tc.pModColor : stats.pValue > tc.pSig ? tc.pOrange : tc.pSigColor
    _valCell(bt, 22, 2, formatValue(stats.pValue), pColor, config, na)
_renderComplementaryHeaders(table bt, MTMConfig config, float winRate = 0.5) =>
    bool useSortino = winRate <= 0.5
    string rollMetricLabel = useSortino ? "Rolling Sortino" : "Rolling Sharpe"
    string expHeader = config.showRExpectancy ? "Rolling R-Expect" : "Rolling Expectancy"
    _hdrCell(bt, 0, 3, "Compounding", config)
    _hdrCell(bt, 1, 3, "Avg Win", config)
    _hdrCell(bt, 2, 3, "Avg Trade", config)
    _hdrCell(bt, 3, 3, "Avg Loss", config)
    _hdrCell(bt, 4, 3, "Martin", config)
    _hdrCell(bt, 5, 3, expHeader, config)
    table.merge_cells(bt, 5, 3, 6, 3)
    _hdrCell(bt, 7, 3, "Avg W Dur", config)
    _hdrCell(bt, 8, 3, "Max Eq", config)
    _hdrCell(bt, 9, 3, "Alpha", config)
    _hdrCell(bt, 10, 3, "Buy & Hold", config)
    table.merge_cells(bt, 10, 3, 11, 3)
    _hdrCell(bt, 12, 3, "Beta", config)
    _hdrCell(bt, 13, 3, "Min Eq", config)
    _hdrCell(bt, 14, 3, "Avg L Dur", config)
    _hdrCell(bt, 15, 3, rollMetricLabel, config)
    table.merge_cells(bt, 15, 3, 16, 3)
    _hdrCell(bt, 17, 3, "Curr DD", config)
    _hdrCell(bt, 18, 3, "SQN", config)
    _hdrCell(bt, 19, 3, "Kurtosis", config)
    _hdrCell(bt, 20, 3, "Skewness", config)
    _hdrCell(bt, 21, 3, "VaR", config)
    _hdrCell(bt, 22, 3, "Ulcer", config)
_renderComplementaryRow(table bt, MTMStats stats, MTMConfig config, ComplementaryData cData) =>
    float compPct = na(cData.compEffect) or stats.netProfitPct == 0.0 or cData.initialCapital <= 0 ? na : (cData.compEffect / cData.initialCapital) * 100.0
    string compStr = na(compPct) ? "-" : (compPct > 0 ? "+" : "") + str.tostring(compPct, "#.#") + "%"
    color compColor = na(compPct) ? config.colorTextMuted : compPct > 0 ? config.colorBullish : config.colorBearish
    _valCell(bt, 0, 4, compStr, compColor, config, na)
    color avgWinColor = stats.avgWinPct > 0 ? config.colorBullish : config.colorBearish
    _valCell(bt, 1, 4, formatValue(stats.avgWinPct, FormatMode.percent), avgWinColor, config, na)
    color avgTradeColor = stats.avgTradePct > 0 ? config.colorBullish : stats.avgTradePct < 0 ? config.colorBearish : color.orange
    _valCell(bt, 2, 4, formatValue(stats.avgTradePct, FormatMode.percent), avgTradeColor, config, na)
    color alColor = stats.avgLossPct > 0.0 ? config.colorBearish : config.colorBullish
    _valCell(bt, 3, 4, formatValue(-stats.avgLossPct, FormatMode.percent, 2, false), alColor, config, na)
    float cappedMartin = capValue(stats.martin)
    string martinStr = formatCapped(cappedMartin, FormatMode.number, 2, false)
    color martinColor = na(cappedMartin) or cappedMartin >= INFINITY_CAP ? config.colorTextMuted : getPnLColor(nz(cappedMartin, 0.0), config.colorBullish, config.colorBearish, config.colorTextMuted)
    _valCell(bt, 4, 4, martinStr, martinColor, config, na)
    if not na(cData.rollingExpMin) and not na(cData.rollingExpMax)
        string expRangeStr = "-"
        color expRangeColor = config.colorTextMuted
        float globalExp = stats.avgTradePct
        float oneR = stats.avgLossPct > 0.0001 ? stats.avgLossPct : na
        float expMean = cData.rollingExpMean
        float expStdDev = cData.rollingExpStdDev
        if config.showRExpectancy and not na(oneR)
            float rMin = cData.rollingExpMin / oneR
            float rMax = cData.rollingExpMax / oneR
            expRangeStr := "[" + str.tostring(rMin, "#.###") + "R - " + str.tostring(rMax, "#.###") + "R]"
            expRangeColor := not na(expMean) and expMean > 0 ? config.colorBullish : rMin > 0 ? color.orange : rMin > -0.5 ? color.orange : _expStabilityColor(expMean, expStdDev, true, config.colorBearish)
        else
            expRangeStr := "[" + formatValue(cData.rollingExpMin, FormatMode.percent, 2, false) + " - " + formatValue(cData.rollingExpMax, FormatMode.percent, 2, false) + "]"
            float halfGlobal = not na(globalExp) and globalExp > 0 ? globalExp * 0.5 : na
            expRangeColor := not na(expMean) and expMean > 0 ? config.colorBullish : not na(halfGlobal) and cData.rollingExpMin > halfGlobal ? config.colorBullish : cData.rollingExpMin > 0 ? color.orange : _expStabilityColor(expMean, expStdDev, false, config.colorBearish)
        _valCell(bt, 5, 4, expRangeStr, expRangeColor, config, na)
        table.merge_cells(bt, 5, 4, 6, 4)
    else
        _valCell(bt, 5, 4, "-", config.colorTextMuted, config)
        table.merge_cells(bt, 5, 4, 6, 4)
    _valCell(bt, 7, 4, formatDuration(stats.avgWinDuration), config.colorTextMuted, config, na)
    float maxEqPctForDisp = cData.maxEquityPct
    string maxEqStr = na(maxEqPctForDisp) ? "-" : formatValue(maxEqPctForDisp, FormatMode.percent)
    _valCell(bt, 8, 4, maxEqStr, config.colorBullish, config, na)
    float cappedAlpha = capValue(cData.alpha)
    color alphaColor = na(cappedAlpha) or cappedAlpha >= INFINITY_CAP ? config.colorTextMuted : getPnLColor(nz(cappedAlpha, 0.0), config.colorBullish, config.colorBearish, config.colorTextMuted)
    _valCell(bt, 9, 4, formatCapped(cappedAlpha, FormatMode.percent), alphaColor, config, na)
    string buyHoldStr = formatValue(cData.buyHoldValue, FormatMode.percent)
    color buyHoldColor = getPnLColor(nz(cData.buyHoldValue, 0.0), config.colorBullish, config.colorBearish, config.colorTextMuted)
    buyHoldColor := na(cData.buyHoldValue) ? config.colorTextMuted : buyHoldColor
    _valCell(bt, 10, 4, buyHoldStr, buyHoldColor, config, na)
    table.merge_cells(bt, 10, 4, 11, 4)
    float cappedBeta = capValue(cData.beta)
    color betaColor = na(cappedBeta) or cappedBeta >= INFINITY_CAP ? config.colorTextMuted : cappedBeta >= 1.3 ? config.colorBearish : cappedBeta >= 0.7 ? color.orange : config.colorBullish
    _valCell(bt, 12, 4, formatCapped(cappedBeta, FormatMode.number, 2, false), betaColor, config, na)
    float minEqPctRaw = cData.minEquityPct
    float cappedMinEq = capValue(minEqPctRaw)
    string minEqStr = formatCapped(cappedMinEq, FormatMode.percent)
    color minEqColor = na(cappedMinEq) or cappedMinEq >= INFINITY_CAP ? config.colorTextMuted : cappedMinEq >= 0 ? config.colorBullish : config.colorBearish
    _valCell(bt, 13, 4, minEqStr, minEqColor, config, na)
    _valCell(bt, 14, 4, formatDuration(stats.avgLossDuration), config.colorTextMuted, config, na)
    bool useSortinoForCell = stats.winRate <= 0.5
    float _rMinForCell = useSortinoForCell ? cData.rollingSortMin : cData.rollingSharpeMin
    float _rMaxForCell = useSortinoForCell ? cData.rollingSortMax : cData.rollingSharpeMax
    if not na(_rMinForCell) and not na(_rMaxForCell)
        float globalMetric2 = useSortinoForCell ? stats.sortino : stats.sharpe
        string minStr2 = _rMinForCell >= INFINITY_CAP ? "∞" : formatValue(_rMinForCell, FormatMode.number, 2, false)
        string maxStr2 = _rMaxForCell >= INFINITY_CAP ? "∞" : formatValue(_rMaxForCell, FormatMode.number, 2, false)
        string sortRangeStr = "[" + minStr2 + " - " + maxStr2 + "]"
        float halfGlobal2 = na(globalMetric2) or globalMetric2 <= 0 ? na : globalMetric2 * 0.5
        float metricRange2 = _rMaxForCell - _rMinForCell
        color sortRangeColor = config.colorTextMuted
        if not na(globalMetric2) and globalMetric2 > 0
            sortRangeColor := config.colorBullish
        else if not na(halfGlobal2) and _rMinForCell > halfGlobal2
            sortRangeColor := config.colorBullish
        else if _rMinForCell > 0
            sortRangeColor := color.orange
        else if metricRange2 < 1.0
            sortRangeColor := color.orange
        else
            sortRangeColor := config.colorBearish
        string ttForMetric = na
        _valCell(bt, 15, 4, sortRangeStr, sortRangeColor, config, ttForMetric)
        table.merge_cells(bt, 15, 4, 16, 4)
    else
        _valCell(bt, 15, 4, "-", config.colorTextMuted, config)
        table.merge_cells(bt, 15, 4, 16, 4)
    string curDDStr = formatValue(-stats.currentDrawdownPct, FormatMode.percent, 2, false)
    color curDDColor = stats.currentDrawdownPct > 0 ? config.colorBearish : config.colorBullish
    _valCell(bt, 17, 4, curDDStr, curDDColor, config, na)
    string sqnStr = na(stats.sqn) ? "-" : formatValue(stats.sqn, FormatMode.number, 2, false)
    color sqnColor = na(stats.sqn) ? config.colorTextMuted : stats.sqn > 2.5 ? config.colorBullish : stats.sqn > 1.6 ? color.orange : stats.sqn > 0 ? config.colorText : config.colorBearish
    _valCell(bt, 18, 4, sqnStr, sqnColor, config, na)
    color kurtColor = cData.kurtosis > 6.0 ? config.colorBearish : cData.kurtosis > 4.0 ? color.orange : cData.kurtosis > 3.0 ? color.orange : config.colorBullish
    _valCell(bt, 19, 4, formatValue(cData.kurtosis, FormatMode.number, 2, false), kurtColor, config, na)
    color skewColor = cData.skewness < -1.5 ? config.colorBearish : cData.skewness < -0.5 ? color.orange : cData.skewness > 0.5 ? config.colorBullish : color.orange
    _valCell(bt, 20, 4, formatValue(cData.skewness, FormatMode.number, 2, false), skewColor, config, na)
    color varColor = config.colorBearish
    _valCell(bt, 21, 4, formatValue(cData.var95, FormatMode.percent, 2, false), varColor, config, na)
    color ulcerColor = cData.ulcerIndex < 5.0 ? config.colorBullish : config.colorBearish
    _valCell(bt, 22, 4, formatValue(cData.ulcerIndex, FormatMode.number, 2, false), ulcerColor, config, na)
_renderFooter(table bt, MTMConfig config, string periodStart, string periodEnd, string periodDuration, string footerLabel, string footerTooltip, string commissionInfo) =>
    int footerRow = config.showComplementary ? 5 : 3
    _hdrCell(bt, 0, footerRow, "Backtest Period: " + periodStart + " - " + periodEnd, config, periodDuration)
    table.merge_cells(bt, 0, footerRow, 6, footerRow)
    _hdrCell(bt, 7, footerRow, footerLabel, config, footerTooltip)
    table.merge_cells(bt, 7, footerRow, 14, footerRow)
    _hdrCell(bt, 15, footerRow, "Commission Cost: " + commissionInfo, config)
    table.merge_cells(bt, 15, footerRow, 22, footerRow)
// runStats — computes the full MTMStats set from an UltratestInput snapshot,
// renders the 23-column performance table on the last bar, and caches the
// result (useCache=false forces recomputation, used by the per-engine cache).
runStats(UltratestInput inp, MTMConfig config, bool useCache = true) =>
    float rf = inp.riskFreeRate
    var bool statsReady = false
    var MTMStats cachedStats = na
    var ComplementaryData cachedCompData = na
    var table cachedTable = na
    if not useCache
        statsReady := false
        cachedStats := na
        cachedCompData := na
        cachedTable := na
    bool atLastBar = barstate.islastconfirmedhistory or barstate.islast
    if atLastBar and not statsReady
        int nTrades = inp.winTrades + inp.lossTrades + inp.beTrades
        float totalTradesF = float(nTrades)
        float winTradesF = float(inp.winTrades)
        float lossTradesF = float(inp.lossTrades)
        float winRate = nTrades > 0 ? winTradesF / totalTradesF : na
        float lossRate = nTrades > 0 ? lossTradesF / totalTradesF : na
        float beRate = nTrades > 0 ? float(inp.beTrades) / totalTradesF : 0.0
        float avgWinPct = inp.avgWin
        float avgLossPct = inp.avgLoss
        float avgTradePct = inp.expectancy
        float pf = calcProfitFactor(inp.totalProfit, inp.totalLoss)
        float absAvgLoss = math.abs(avgLossPct)
        float payoff = inp.lossTrades == 0 ? (inp.winTrades > 0 ? INFINITY_CAP : na) : (absAvgLoss > 0.0 ? nz(avgWinPct, 0.0) / absAvgLoss : na)
        float expectancy = nTrades > 0 ? calcExpectancy(winRate, avgWinPct, math.abs(avgLossPct), lossRate) : na
        float rExpectancy = math.abs(avgLossPct) > 0.0001 ? expectancy / math.abs(avgLossPct) : na
        float tradingPeriodMs = float(inp.lastTradeTime - inp.firstTradeTime)
        float tradingPeriodDays = tradingPeriodMs / MS_PER_DAY
        float tradingPeriodYears = tradingPeriodMs / MS_PER_YEAR
        float tradesPerYear = tradingPeriodMs > 0.0 and nTrades > 0 ? float(nTrades) / (tradingPeriodMs / MS_PER_YEAR) : 0.0
        tradesPerYear := tradesPerYear > 0.0 and tradesPerYear < 12000000.0 ? tradesPerYear : 0.0
        float tradesPerMonth = tradingPeriodMs > 0.0 and nTrades > 0 ? float(nTrades) / (tradingPeriodMs / MS_PER_MONTH) : 0.0
        tradesPerMonth := tradesPerMonth > 0.0 and tradesPerMonth < 1000000.0 ? tradesPerMonth : 0.0
        int nEq = array.size(inp.equityPerBar)
        float lastEq = nEq > 0 ? array.get(inp.equityPerBar, nEq - 1) : na
        float netProfitPct = not na(lastEq) ? (lastEq / inp.initialCapital - 1.0) * 100.0 : na
        float sumTradeReturns = 0.0
        for i = 0 to (array.size(inp.tradeResults) == 0 ? na : array.size(inp.tradeResults) - 1)
            sumTradeReturns += array.get(inp.tradeResults, i)
        float compEffect = not na(lastEq) ? (lastEq - inp.initialCapital) - (inp.initialCapital * sumTradeReturns) : na
        float cagr = na
        if not na(lastEq) and inp.initialCapital > 0.0 and tradingPeriodMs > 0.0
            cagr := lastEq < 0.0 ? na : lastEq == 0.0 ? -100.0 : (math.pow(lastEq / inp.initialCapital, MS_PER_YEAR / tradingPeriodMs) - 1.0) * 100.0
        float monthlyReturn = inp.initialCapital <= 0.0 or not na(lastEq) and lastEq < 0.0 or tradingPeriodMs <= 0.0 ? na : not na(lastEq) and lastEq == 0.0 ? -100.0 : not na(lastEq) ? (math.pow(lastEq / inp.initialCapital, MS_PER_MONTH / tradingPeriodMs) - 1.0) * 100.0 : na
        float sharpe = na
        float sortino = na
        if nTrades >= 2 and tradesPerYear > 0.0
            sharpe := calcSharpe(inp.tradeResults, tradesPerYear, rf)
            sortino := calcSortino(inp.tradeResults, tradesPerYear, rf)
        float maxDDPct = inp.maxDrawdown > 0.0 ? inp.maxDrawdown : 0.0
        float peakEq = nEq > 0 ? array.max(inp.equityPerBar) : na
        float maxDDPeak = not na(inp.maxDrawdownPeak) and inp.maxDrawdownPeak > 0.0 ? inp.maxDrawdownPeak : peakEq
        float currentDDPct = 0.0
        float avgDDPctFinal = 0.0
        if nEq >= 2
            float ddPeak = array.get(inp.equityPerBar, 0)
            float ddSum = 0.0
            int ddCount = 0
            for i = 0 to nEq - 1
                float eqVal = array.get(inp.equityPerBar, i)
                if eqVal > ddPeak
                    ddPeak := eqVal
                float ddPct = ddPeak > 0.0 ? ((ddPeak - eqVal) / ddPeak) * 100.0 : 0.0
                if ddPct > 0.0
                    ddSum += ddPct
                    ddCount += 1
            avgDDPctFinal := ddCount > 0 ? ddSum / float(ddCount) : 0.0
            float currentEquityDD = array.get(inp.equityPerBar, nEq - 1)
            currentDDPct := ddPeak > 0.0 ? ((ddPeak - currentEquityDD) / ddPeak) * 100.0 : 0.0
        float _rorRisk = nz(math.abs(avgLossPct), 1.0)
        float ror = calcRiskOfRuin(inp.winTrades, inp.lossTrades, avgWinPct, math.abs(avgLossPct), _rorRisk, inp.beTrades)
        float pValue = calcPValue(inp.winTrades, nTrades, avgWinPct, math.abs(avgLossPct))
        float zScore = na
        float var95 = calcHistoricalVaR(inp.tradeResults, 95.0)
        float cvar95 = calcCVaR(inp.tradeResults, 0.95)
        float beta = calcBeta(inp.betaStrategyReturns, inp.betaSpxReturns)
        float buyHoldReturn = na
        if not na(inp.firstBarClose) and inp.firstBarClose > 0
            buyHoldReturn := (close / inp.firstBarClose - 1.0) * 100.0
        float spxCagr = na
        if not na(inp.spxFirstClose) and not na(inp.spxLastClose) and inp.spxFirstClose > 0 and tradingPeriodYears > 0
            spxCagr := (math.pow(inp.spxLastClose / inp.spxFirstClose, 1.0 / tradingPeriodYears) - 1.0) * 100.0
        float buyHoldCagr = na
        if not na(buyHoldReturn) and tradingPeriodYears > 0 and buyHoldReturn > -100.0
            buyHoldCagr := (math.pow(1.0 + buyHoldReturn / 100.0, 1.0 / tradingPeriodYears) - 1.0) * 100.0
        float benchmarkCagr = na(spxCagr) ? buyHoldCagr : spxCagr
        float alpha = na(cagr) or na(benchmarkCagr) ? na : cagr - benchmarkCagr
        float equityRSquared = calcEquityRSquared(inp.equityPerBar)
        float calmar = maxDDPct > 0 ? cagr / maxDDPct : na
        array<float> ddArray = array.new<float>()
        float runPeak = inp.initialCapital
        for i = 0 to nEq - 1
            float eqVal = array.get(inp.equityPerBar, i)
            if eqVal > runPeak
                runPeak := eqVal
            float dd = runPeak > 0 ? (runPeak - eqVal) / runPeak * 100.0 : 0.0
            array.push(ddArray, dd)
        float ulcer = calcUlcerIndex(ddArray)
        float martin = ulcer > 0 ? (cagr - rf * 100.0) / ulcer : na
        float sqn = na
        if nTrades >= 2 and array.size(inp.tradeResults) >= 2
            float tradeMean = array.avg(inp.tradeResults)
            float tradeStdev = array.stdev(inp.tradeResults, biased = false)
            if nz(tradeStdev, 0.0) <= 0.0
                sqn := tradeMean > 0.0 ? INFINITY_CAP : tradeMean < 0.0 ? -INFINITY_CAP : na
            else
                sqn := math.sqrt(float(nTrades)) * tradeMean / tradeStdev
        array<float> returnsForMoments = inp.tradeResults
        float skewness = calcSkewness(returnsForMoments)
        float kurtosis = calcKurtosis(returnsForMoments)
        RollingStats rs = calcRollingStats(inp.tradeResults, 0, tradesPerYear, rf)
        float rollingExpMin = rs.expectancyMin
        float rollingExpMax = rs.expectancyMax
        float rollingSortMin = rs.sortinoMin
        float rollingSortMax = rs.sortinoMax
        float rollingSharpeMin = rs.sharpeMin
        float rollingSharpeMax = rs.sharpeMax
        int maxConsecWins = 0, int maxConsecLosses = 0, int curWins = 0, int curLosses = 0
        int nTr = array.size(inp.tradeResults)
        for i = 0 to (nTr == 0 ? na : nTr - 1)
            float tr = array.get(inp.tradeResults, i)
            if tr > 0.0
                curWins += 1, curLosses := 0
                maxConsecWins := math.max(maxConsecWins, curWins)
            else if tr < 0.0
                curLosses += 1, curWins := 0
                maxConsecLosses := math.max(maxConsecLosses, curLosses)
            else
                curWins := 0, curLosses := 0
        float timeInMarketPct = tradingPeriodMs > 0.0 ? math.min(100.0, (float(inp.totalTradeDuration) / tradingPeriodMs) * 100.0) : na
        cachedStats := MTMStats.new(
             totalTrades = nTrades,
             winTrades = inp.winTrades,
             lossTrades = inp.lossTrades,
             evenTrades = inp.beTrades,
             winRate = nTrades > 0 ? winTradesF / totalTradesF : na,
             lossRate = nTrades > 0 ? lossTradesF / totalTradesF : na,
             beRate = beRate,
             avgWinPct = avgWinPct,
             avgLossPct = math.abs(avgLossPct),
             avgTradePct = avgTradePct,
             profitFactor = pf,
             payoffRatio = payoff,
             expectancy = expectancy,
             rExpectancy = rExpectancy,
             grossProfit = inp.totalProfit,
             grossLoss = inp.totalLoss,
             netProfit = not na(lastEq) ? lastEq - inp.initialCapital : na,
             netProfitPct = netProfitPct,
             compEffect = nTrades > 0 ? compEffect : na,
             sharpe = sharpe,
             sortino = sortino,
             calmar = calmar,
             martin = martin,
             maxDrawdown = maxDDPct * maxDDPeak / 100.0,
             maxDrawdownPct = maxDDPct,
             currentDrawdown = currentDDPct * (nEq > 0 ? array.get(inp.equityPerBar, nEq - 1) : na) / 100.0,
             currentDrawdownPct = currentDDPct,
             avgDrawdownPct = avgDDPctFinal,
             maxEquity = not na(peakEq) ? peakEq : na,
             minEquity = nEq > 0 ? array.min(inp.equityPerBar) : na,
             cagr = cagr,
             monthlyReturn = monthlyReturn,
             maxConsecWins = maxConsecWins,
             maxConsecLosses = maxConsecLosses,
             avgTradeDuration = float(inp.totalTradeDuration) / totalTradesF,
             avgWinDuration = array.size(inp.winDurations) > 0 ? array.avg(inp.winDurations) : na,
             avgLossDuration = array.size(inp.lossDurations) > 0 ? array.avg(inp.lossDurations) : na,
             timeInMarketPct = timeInMarketPct,
             tradesPerMonth = tradesPerMonth,
             tradesPerYear = tradesPerYear,
             skewness = skewness,
             kurtosis = kurtosis,
             var95 = var95,
             cvar95 = cvar95,
             totalCommission = inp.totalCommission,
             ulcerIndex = ulcer,
             riskOfRuin = ror,
             pValue = pValue,
             zScore = zScore,
             alpha = alpha,
             beta = beta,
             buyHoldReturn = buyHoldReturn,
             equityRSquared = equityRSquared,
             firstTradeTime = inp.firstTradeTime,
             lastTradeTime = inp.lastTradeTime,
             tradingPeriodDays = tradingPeriodDays,
             sqn = sqn,
             initialCapital = inp.initialCapital,
             riskFreeRate = inp.riskFreeRate,
             avgCommissionPct = inp.avgCommissionPct)
        float compEffectPct = not na(compEffect) and inp.initialCapital > 0 ? (compEffect / inp.initialCapital) * 100.0 : na
        int nMoments = array.size(returnsForMoments)
        array<float> riskMult = array.size(inp.riskMultipliers) > 0 ? inp.riskMultipliers : array.new_float(1, 1.0)
        cachedCompData := ComplementaryData.new(
             payoffRatio = payoff,
             avgTradePct = avgTradePct,
             avgWinPct = avgWinPct,
             avgLossPct = -math.abs(avgLossPct),
             avgRisk = 1.0,
             martin = martin,
             rollingExpMin = rollingExpMin,
             rollingExpMax = rollingExpMax,
             rollingSortMin = rollingSortMin,
             rollingSortMax = rollingSortMax,
             rollingSharpeMin = rollingSharpeMin,
             rollingSharpeMax = rollingSharpeMax,
             rollingExpMean = rs.expectancyMean,
             rollingExpStdDev = rs.expectancyStdDev,
             rollingWindowSize = rs.windowSize,
             avgWinDurationMs = array.size(inp.winDurations) > 0 ? array.avg(inp.winDurations) : na,
             maxEquityPct = not na(peakEq) ? (peakEq / inp.initialCapital - 1.0) * 100.0 : na,
             alpha = alpha,
             buyHoldValue = buyHoldReturn,
             beta = beta,
             minEquityPct = nEq > 0 ? (array.min(inp.equityPerBar) / inp.initialCapital - 1.0) * 100.0 : na,
             avgLossDurationMs = array.size(inp.lossDurations) > 0 ? array.avg(inp.lossDurations) : na,
             currentDDPct = currentDDPct,
             sqn = sqn,
             kurtosis = kurtosis,
             skewness = skewness,
             nMoments = nMoments,
             var95 = var95,
             ulcerIndex = ulcer,
             compEffectPct = compEffectPct,
             initialCapital = inp.initialCapital,
             compEffect = compEffect,
             riskMultipliers = riskMult)
        if not na(inp.liveEquity)
            float liveNP = inp.liveEquity - inp.initialCapital
            cachedStats.netProfit := liveNP
            cachedStats.netProfitPct := inp.initialCapital > 0 ? liveNP / inp.initialCapital * 100.0 : na
            float livePeak = math.max(nz(cachedStats.maxEquity, inp.liveEquity), inp.liveEquity)
            float liveDD = livePeak - inp.liveEquity
            cachedStats.currentDrawdownPct := livePeak > 0.0 ? (liveDD / livePeak) * 100.0 : 0.0
            cachedStats.maxEquity := livePeak
            if not na(cachedStats.compEffect)
                cachedStats.compEffect := liveNP - inp.initialCapital * sumTradeReturns
        statsReady := true
    if statsReady and not na(cachedStats) and cachedStats.totalTrades > 0
        if na(cachedTable)
            cachedTable := table.new(position.bottom_center, 23, 8,
                 border_color = config.colorBorder,
                 border_width = 1,
                 frame_width = 1,
                 bgcolor = config.colorHeader,
                 force_overlay = true)
        ThresholdConfig tc = getThresholdConfig(config.colorBearish, color.orange, color.orange, config.colorBullish)
        _renderSectionHeaders(cachedTable, config)
        _renderColumnHeaders(cachedTable, config)
        _renderPerformanceMetrics(cachedTable, cachedStats, config)
        _renderTradeStats(cachedTable, cachedStats, config)
        _renderRiskMetrics(cachedTable, cachedStats, config, tc)
        if config.showComplementary
            _renderComplementaryHeaders(cachedTable, config, cachedStats.winRate)
            _renderComplementaryRow(cachedTable, cachedStats, config, cachedCompData)
        string periodStart = inp.firstTradeTime > 0 ? str.format_time(inp.firstTradeTime, "MM-dd-yyyy") : "Start"
        string periodEnd = inp.lastTradeTime > 0 ? str.format_time(inp.lastTradeTime, "MM-dd-yyyy") : "End"
        string periodDuration = formatDuration(float(inp.lastTradeTime - inp.firstTradeTime))
        string commissionDisplay = na(cachedStats.avgCommissionPct) ? "0.00%" : formatValue(cachedStats.avgCommissionPct, FormatMode.percent, 2, false)
        // Watermark — one 50/50 pick per script load, identical mechanism to
        // the Deeptest framework label: alternates between the engine name
        // and the © line across reloads.
        string frameworkLabel = "PineTunnel Backtesting Engine", string footerTooltipText = "PineTunnel — © Fractalyst"
        var bool footerPrimaryIsText = false
        if not footerPrimaryIsText
            footerPrimaryIsText := math.round(math.random(0.0, 1.0)) == 1
        string footerLabel = footerPrimaryIsText ? frameworkLabel : footerTooltipText
        _renderFooter(cachedTable, config, periodStart, periodEnd, periodDuration, footerLabel, footerTooltipText, commissionDisplay)
    cachedStats
// _toStatsInput — converts engine state (closed trades, equity series, FX
// frozen denominators) into the UltratestInput snapshot runStats() consumes.
_toStatsInput(PTEngine e, float spxFirstClose = na, float spxLastClose = na, array<float> betaStrategyReturns = na, array<float> betaSpxReturns = na, float firstBarClose = na, bool isBullish = true) =>
    int nClosed = array.size(e.closed)
    array<float> tradeResults = array.new<float>()
    array<float> equityPerTrade = array.new<float>()
    array<int>   winDurations = array.new<int>()
    array<int>   lossDurations = array.new<int>()
    float winSum = 0.0
    float lossSum = 0.0
    float allSum = 0.0
    float sumTradeReturns = 0.0
    int   totalTradeDuration = 0
    float equityCursor = e.cfg.initial_capital
    float maxEquity = e.cfg.initial_capital
    float minEquity = e.cfg.initial_capital
    float totalCommPct = 0.0
    int commPctCount = 0
    array.push(equityPerTrade, equityCursor)
    if nClosed > 0
        for i = 0 to nClosed - 1
            ClosedTrade tr = array.get(e.closed, i)
            float eqBefore = equityCursor
            float pnlPct = eqBefore > 0 ? (tr.profit / eqBefore) * 100.0 : 0.0
            equityCursor += tr.profit
            array.push(tradeResults, pnlPct / 100.0)
            array.push(equityPerTrade, equityCursor)
            allSum += pnlPct
            sumTradeReturns += pnlPct / 100.0
            maxEquity := math.max(maxEquity, equityCursor)
            minEquity := math.min(minEquity, equityCursor)
            int dur = tr.exit_time - tr.entry_time
            totalTradeDuration += dur
            if tr.profit > 0
                winSum += pnlPct
                array.push(winDurations, dur)
            else if tr.profit < 0
                lossSum += pnlPct
                array.push(lossDurations, dur)
                if array.size(lossDurations) > LOSS_DURATION_HISTORY_LIMIT
                    array.shift(lossDurations)
            float notional = math.abs(tr.entry_price * tr.dir * tr.qty)
            if notional > 0.0
                totalCommPct += (math.abs(tr.commission) / notional) * 100.0
                commPctCount += 1
    float avgCommissionPct = commPctCount > 0 ? totalCommPct / float(commPctCount) : na
    array<float> returnsPerBar = array.new<float>()
    int nEq = array.size(equityPerTrade)
    if nEq >= 2
        for i = 1 to nEq - 1
            float prev = array.get(equityPerTrade, i - 1)
            float cur  = array.get(equityPerTrade, i)
            array.push(returnsPerBar, prev != 0.0 ? cur / prev - 1.0 : 0.0)
    float avgWin = e.wintrades > 0 ? winSum / float(e.wintrades) : 0.0
    float avgLoss = e.losstrades > 0 ? lossSum / float(e.losstrades) : 0.0
    float expectancy = nClosed > 0 ? allSum / float(nClosed) : 0.0
    float bhAnchor = not na(firstBarClose) ? firstBarClose : e._first_close
    float maxDDValue = e.max_dd_value
    float maxDDPeak = not na(e.max_dd_peak) and e.max_dd_peak > 0 ? e.max_dd_peak : e.cfg.initial_capital
    float maxDrawdownPct = maxDDPeak > 0 and maxDDValue > 0 ? maxDDValue / maxDDPeak * 100.0 : 0.0
    UltratestInput.new(
         equityPerBar = equityPerTrade,
         returnsPerBar = returnsPerBar,
         tradeResults = tradeResults,
         initialCapital = e.cfg.initial_capital,
         firstTradeTime = nClosed > 0 ? array.get(e.closed, 0).entry_time : 0,
         lastTradeTime = nClosed > 0 ? array.get(e.closed, nClosed - 1).exit_time : 0,
         winTrades = e.wintrades,
         lossTrades = e.losstrades,
         beTrades = e.eventrades,
         totalProfit = e.grossprofit,
         totalLoss = e.grossloss,
         avgWin = avgWin,
         avgLoss = avgLoss,
         expectancy = expectancy,
         totalTradeDuration = totalTradeDuration,
         winDurations = winDurations,
         lossDurations = lossDurations,
         maxDrawdown = maxDrawdownPct,
         maxDrawdownPeak = maxDDPeak,
         riskMultipliers = array.new<float>(),
         betaStrategyReturns = na(betaStrategyReturns) ? array.new<float>() : betaStrategyReturns,
         betaSpxReturns = na(betaSpxReturns) ? (array.size(e._spy_rets) > 0 ? e._spy_rets : array.new<float>()) : betaSpxReturns,
         peakEquity = maxEquity,
         isBullish = isBullish,
         firstBarClose = bhAnchor,
         spxFirstClose = na(spxFirstClose) ? e._spy_first : spxFirstClose,
         spxLastClose = na(spxLastClose) ? e._spy_last : spxLastClose,
         costBool = e.cfg.commission_value > 0,
         costAmount = e.cfg.commission_value,
         totalCommission = e._commission_total,
         riskFreeRate = e.cfg.risk_free_rate / 100.0,
         liveEquity = e.equity + e.open_profit,
         avgCommissionPct = avgCommissionPct)
// ptStats — per-engine statistics cache keyed by makePT()'s unique engine id.
// Multiple engines on one chart each keep their own MTMStats + table.
ptStats(PTEngine e, MTMConfig config, float spxFirstClose = na, float spxLastClose = na, array<float> betaStrategyReturns = na, array<float> betaSpxReturns = na, float firstBarClose = na, bool isBullish = true) =>
    var array<PTEngine> _stEngines = array.new<PTEngine>()
    var array<MTMStats> _stStats   = array.new<MTMStats>()
    MTMStats result = na
    int hitIdx = -1
    for i = 0 to (array.size(_stEngines) == 0 ? na : array.size(_stEngines) - 1)
        if hitIdx == -1 and array.get(_stEngines, i)._id == e._id
            hitIdx := i
    if hitIdx >= 0
        result := array.get(_stStats, hitIdx)
    else
        result := runStats(_toStatsInput(e, spxFirstClose, spxLastClose, betaStrategyReturns, betaSpxReturns, firstBarClose, isBullish), config, useCache = false)
        array.push(_stEngines, e)
        array.push(_stStats, result)
    result
//@function makeStatsConfig
//@description Builds the MTMConfig styling/display options for the performance table. Defaults match the shared PineWork visual theme.
//@returns MTMConfig instance.
makeStatsConfig(color colorBullish = #00b9ff, color colorBearish = #ff0051, color colorText = color.white, color colorTextMuted = color.gray, color colorBg = #0b0f13, color colorHeader = #191e2c, color colorBorder = #000000, string textSize = size.auto, string commissionInfo = "0.00%", bool showComplementary = true, bool showRExpectancy = true, float costInput = 0.0) =>
    MTMConfig.new(colorBullish, colorBearish, colorText, colorTextMuted, colorBg, colorHeader, colorBorder, textSize, commissionInfo, showComplementary, showRExpectancy, costInput)
// ── §7 · Exported constants — TV-parity names ────────────────────────────────
//@description A named constant for use with the direction parameter of the `strategy.entry` and `strategy.order` commands. It specifies that the command creates a buy order. Mirrors `strategy.long`.
export const int long        =  1
//@description A named constant for use with the direction parameter of the `strategy.entry` and `strategy.order` commands. It specifies that the command creates a sell order. Mirrors `strategy.short`.
export const int short       = -1
//@description This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration statement. It is only relevant when no value is used for the ‘qty’ parameter in `strategy.entry`() or `strategy.order`() function calls. It specifies that an amount of cash in the `strategy.account_currency` will be used to enter trades. Mirrors `strategy.cash`.
export const string cash     = "cash"
//@description This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration statement. It is only relevant when no value is used for the ‘qty’ parameter in `strategy.entry`() or `strategy.order`() function calls. It specifies that a number of contracts/shares/lots will be used to enter trades. Mirrors `strategy.fixed`.
export const string fixed    = "fixed"
//@description This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration statement. It is only relevant when no value is used for the ‘qty’ parameter in `strategy.entry`() or `strategy.order`() function calls. It specifies that a percentage (0-100) of equity will be used to enter trades. Mirrors `strategy.percent_of_equity`.
export const string percent_of_equity = "percent_of_equity"
//@description It allows strategy to open only long positions. Mirrors `strategy.direction.long`.
export const string direction_long  = "long"
//@description It allows strategy to open only short positions. Mirrors `strategy.direction.short`.
export const string direction_short = "short"
//@description It allows strategy to open both long and short positions. Mirrors `strategy.direction.all`.
export const string direction_all   = "all"
//@description A named constant for use with the oca_type parameter of the `strategy.entry`() and `strategy.order`() commands. It specifies that the order executes independently of all other orders, including those with the same oca_name. Mirrors `strategy.oca.none`.
export const int oca_none   = 0
//@description A named constant for use with the oca_type parameter of the `strategy.entry`() and `strategy.order`() commands. It specifies that the strategy cancels the unfilled order when another order with the same oca_name and oca_type executes. Mirrors `strategy.oca.cancel`.
export const int oca_cancel = 1
//@description A named constant for use with the oca_type parameter of the `strategy.entry`() and `strategy.order`() commands. It specifies that when another order with the same oca_name and oca_type executes, the strategy reduces the unfilled order by that order's size. If the unfilled order's size reaches 0 after reduction, it is the same as canceling the order entirely. Mirrors `strategy.oca.reduce`.
export const int oca_reduce = 2
//@description Commission type for an order. A percentage of the cash volume of order. Mirrors `strategy.commission.percent`.
export const string commission_percent             = "percent"
//@description Commission type for an order. Money displayed in the account currency per order. Mirrors `strategy.commission.cash_per_order`.
export const string commission_cash_per_order      = "cash_per_order"
//@description Commission type for an order. Money displayed in the account currency per contract. Mirrors `strategy.commission.cash_per_contract`.
export const string commission_cash_per_contract   = "cash_per_contract"
//@description Commission type for an order. Money displayed in the account currency per contract. Mirrors `strategy.commission.cash_per_contract`.
export const string commission_per_contract        = "per_contract"
//@description Commission type: cash_per_trade.
export const string commission_cash_per_trade      = "cash_per_trade"
//@description Risk rule type: max_drawdown.
export const string risk_max_drawdown_type         = "max_drawdown"
//@description Risk rule type: max_intraday_loss.
export const string risk_max_intraday_loss_type    = "max_intraday_loss"
// ── §8 · Namespace accessors — the strategy.* read surface ───────────────────
//@function equity
//@description Current equity (`strategy.initial_capital` + `strategy.netprofit` + `strategy.openprofit`). Mirrors `strategy.equity`.
//@param e Engine instance.
//@returns Equity in account currency.
export equity(PTEngine e) => e.equity + e.open_profit
//@function openprofit
//@description Current unrealized profit or loss for all open positions. Mirrors `strategy.openprofit`.
//@param e Engine instance.
//@returns Open profit in account currency.
export openprofit(PTEngine e) => e.open_profit
//@function closedtrades
//@description Number of trades, which were closed for the whole trading range. Mirrors `strategy.closedtrades`.
//@param e Engine instance.
//@returns Count.
export closedtrades(PTEngine e) => array.size(e.closed)
//@function closedtrades_first_index
//@description The index, or trade number, of the first (oldest) trade listed in the List of Trades. This number is usually zero. If more trades than the allowed limit have been closed, the oldest trades are removed, and this number is the index of the oldest remaining trade. PineTunnel never trims closed trades, so this value is always 0. Mirrors `strategy.closedtrades.first_index`.
//@param e Engine instance.
//@returns 0-based index (0 while history_cap trimming is inactive).
export closedtrades_first_index(PTEngine e) =>
    array.size(e.closed) >= 0 ? 0 : 0
//@function opentrades
//@description Number of market position entries, which were not closed and remain opened. If there is no open market position, 0 is returned. Mirrors `strategy.opentrades`.
//@param e Engine instance.
//@returns Count.
export opentrades(PTEngine e) => array.size(e.legs)
//@function position_size
//@description Direction and size of the current market position. If the value is > 0, the market position is long. If the value is < 0, the market position is short. The absolute value is the number of contracts/shares/lots/units in trade (position size). Mirrors `strategy.position_size`.
//@param e Engine instance.
//@returns Positive for long, negative for short, 0 for flat.
export position_size(PTEngine e) => e.position_size
//@function position_avg_price
//@description Average entry price of current market position. If the market position is flat, 'NaN' is returned. Mirrors `strategy.position_avg_price`.
//@param e Engine instance.
//@returns Price in symbol currency.
export position_avg_price(PTEngine e) => e.position_avg_price
//@function initial_capital
//@description The amount of initial capital set in the strategy properties. Mirrors `strategy.initial_capital`.
//@param e Engine instance.
//@returns Capital in account currency.
export initial_capital(PTEngine e) => e.cfg.initial_capital
//@function account_currency
//@description Returns the currency used to calculate results, which can be set in the strategy's properties. Mirrors `strategy.account_currency`.
//@param e Engine instance.
//@returns Currency code (e.g. "USDT").
export account_currency(PTEngine e) => e.cfg.currency == "" or na(e.cfg.currency) ? syminfo.currency : e.cfg.currency
//@function grossprofit
//@description Total currency value of all completed winning trades. Mirrors `strategy.grossprofit`.
//@param e Engine instance.
//@returns Gross profit in account currency.
export grossprofit(PTEngine e) => e.grossprofit
//@function grossloss
//@description Total currency value of all completed losing trades. Mirrors `strategy.grossloss`.
//@param e Engine instance.
//@returns Gross loss in account currency.
export grossloss(PTEngine e) => e.grossloss
//@function wintrades
//@description Number of profitable trades for the whole trading range. Mirrors `strategy.wintrades`.
//@param e Engine instance.
//@returns Count.
export wintrades(PTEngine e) => e.wintrades
//@function losstrades
//@description Number of unprofitable trades for the whole trading range. Mirrors `strategy.losstrades`.
//@param e Engine instance.
//@returns Count.
export losstrades(PTEngine e) => e.losstrades
//@function eventrades
//@description Number of breakeven trades for the whole trading range. Mirrors `strategy.eventrades`.
//@param e Engine instance.
//@returns Count.
export eventrades(PTEngine e) => e.eventrades
//@function position_entry_name
//@description Name of the order that initially opened current market position. Mirrors `strategy.position_entry_name`.
//@param e Engine instance.
//@returns Entry id, `""` when flat.
export position_entry_name(PTEngine e) => e.position_entry_name
//@function max_drawdown
//@description Maximum equity drawdown value for the whole trading range. Mirrors `strategy.max_drawdown`.
//@param e Engine instance.
//@returns Positive drawdown value.
export max_drawdown(PTEngine e) => e.max_dd_value
//@function max_drawdown_percent
//@description The maximum equity drawdown value for the whole trading range, expressed as a percentage and calculated by formula: Lowest Value During Trade / (Entry Price x Quantity) * 100. Mirrors `strategy.max_drawdown_percent`.
//@param e Engine instance.
//@returns Percent value.
export max_drawdown_percent(PTEngine e) => not na(e.max_dd_peak) and e.max_dd_peak > 0 ? e.max_dd_value / e.max_dd_peak * 100.0 : 0.0
//@function max_runup
//@description Maximum equity run-up value for the whole trading range. Mirrors `strategy.max_runup`.
//@param e Engine instance.
//@returns Positive runup value.
export max_runup(PTEngine e) => e.max_runup_value
//@function max_runup_percent
//@description The maximum equity run-up value for the whole trading range, expressed as a percentage and calculated by formula: Highest Value During Trade / (Entry Price x Quantity) * 100. Mirrors `strategy.max_runup_percent`.
//@param e Engine instance.
//@returns Percent value.
export max_runup_percent(PTEngine e) => not na(e.equity_trough) and e.equity_trough > 0 ? e.max_runup_value / e.equity_trough * 100.0 : 0.0
//@function netprofit_percent
//@description The total value of all completed trades, expressed as a percentage of the initial capital. Mirrors `strategy.netprofit_percent`.
//@param e Engine instance.
//@returns Percent value.
export netprofit_percent(PTEngine e) => netprofit(e) / e.cfg.initial_capital * 100.0
//@function openprofit_percent
//@description The current unrealized profit or loss for all open positions, expressed as a percentage and calculated by formula: openPL / realizedEquity * 100. Mirrors `strategy.openprofit_percent`.
//@param e Engine instance.
//@returns Percent value.
export openprofit_percent(PTEngine e) => e.open_profit / e.cfg.initial_capital * 100.0
//@function grossprofit_percent
//@description The total currency value of all completed winning trades, expressed as a percentage of the initial capital. Mirrors `strategy.grossprofit_percent`.
//@param e Engine instance.
//@returns Percent value.
export grossprofit_percent(PTEngine e) => e.grossprofit / e.cfg.initial_capital * 100.0
//@function grossloss_percent
//@description The total value of all completed losing trades, expressed as a percentage of the initial capital. Mirrors `strategy.grossloss_percent`.
//@param e Engine instance.
//@returns Percent value.
export grossloss_percent(PTEngine e) => e.grossloss / e.cfg.initial_capital * 100.0
//@function avg_trade
//@description Returns the average amount of money gained or lost per trade. Calculated as the sum of all profits and losses divided by the number of closed trades. Mirrors `strategy.avg_trade`.
//@param e Engine instance.
//@returns Average trade P&L, `na` when no closed trades.
export avg_trade(PTEngine e) =>
    int _n = array.size(e.closed)
    _n > 0 ? _closedNet(e) / _n : na
//@function avg_trade_percent
//@description Returns the average percentage gain or loss per trade. Calculated as the sum of all profit and loss percentages divided by the number of closed trades. Mirrors `strategy.avg_trade_percent`.
//@param e Engine instance.
//@returns Percent value, `na` when no closed trades.
export avg_trade_percent(PTEngine e) =>
    int _n = array.size(e.closed)
    _n > 0 ? _closedNet(e) / e.cfg.initial_capital * 100.0 : na
//@function avg_winning_trade
//@description Returns the average amount of money gained per winning trade. Calculated as the sum of profits divided by the number of winning trades. Mirrors `strategy.avg_winning_trade`.
//@param e Engine instance.
//@returns Average win in account currency.
export avg_winning_trade(PTEngine e) => e.wintrades > 0 ? e.grossprofit / e.wintrades : na
//@function avg_winning_trade_percent
//@description Returns the average percentage gain per winning trade. Calculated as the sum of profit percentages divided by the number of winning trades. Mirrors `strategy.avg_winning_trade_percent`.
//@param e Engine instance.
//@returns Percent value.
export avg_winning_trade_percent(PTEngine e) => e.wintrades > 0 ? e.grossprofit / e.wintrades / e.cfg.initial_capital * 100.0 : na
//@function avg_losing_trade
//@description Returns the average amount of money lost per losing trade. Calculated as the sum of losses divided by the number of losing trades. Mirrors `strategy.avg_losing_trade`.
//@param e Engine instance.
//@returns Average loss in account currency.
export avg_losing_trade(PTEngine e) => e.losstrades > 0 ? e.grossloss / e.losstrades : na
//@function avg_losing_trade_percent
//@description Returns the average percentage loss per losing trade. Calculated as the sum of loss percentages divided by the number of losing trades. Mirrors `strategy.avg_losing_trade_percent`.
//@param e Engine instance.
//@returns Percent value.
export avg_losing_trade_percent(PTEngine e) => e.losstrades > 0 ? e.grossloss / e.losstrades / e.cfg.initial_capital * 100.0 : na
//@function max_contracts_held_all
//@description Maximum number of contracts/shares/lots/units in one trade for the whole trading range. Mirrors `strategy.max_contracts_held_all`.
//@param e Engine instance.
//@returns Count.
export max_contracts_held_all(PTEngine e) => e.max_contracts_held_all
//@function max_contracts_held_long
//@description Maximum number of contracts/shares/lots/units in one long trade for the whole trading range. Mirrors `strategy.max_contracts_held_long`.
//@param e Engine instance.
//@returns Count.
export max_contracts_held_long(PTEngine e) => e.max_contracts_held_long
//@function max_contracts_held_short
//@description Maximum number of contracts/shares/lots/units in one short trade for the whole trading range. Mirrors `strategy.max_contracts_held_short`.
//@param e Engine instance.
//@returns Count.
export max_contracts_held_short(PTEngine e) => e.max_contracts_held_short
//@function margin_liquidation_price
//@description When margin is used in a strategy, returns the price point where a simulated margin call will occur and liquidate enough of the position to meet the margin requirements. Mirrors `strategy.margin_liquidation_price`.
//@param e Engine instance.
//@returns Price value, `na` when flat or margin disabled.
export margin_liquidation_price(PTEngine e) =>
    float _net = _liveNet(e)
    float _result = na
    if _net != 0
        bool _isLong = _net > 0
        float _mPct = _isLong ? e.cfg.margin_long : e.cfg.margin_short
        bool _checkable = _isLong ? _mPct < 100.0 : _mPct > 0.0
        if _checkable
            float _ratio = _mPct / 100.0
            float _n = math.abs(_net)
            float _s = 0.0
            for _lg in e.legs
                _s += _lg.qty * _lg.avg_price
            float _avg = _s / _n
            float _p = _isLong ? (_s - e.equity) / (_n * (1.0 - _ratio)) : (e.equity + _s) / (_n * (1.0 + _ratio))
            // longs call on a decline (P < avg), shorts on a rise (P > avg);
            // avg derived from the live legs — e.position_avg_price may be
            // stale if a margin call shrank the book earlier this bar.
            bool _reachable = _isLong ? _p < _avg : _p > _avg
            if _reachable and _p > 0.0
                _result := _p
    _result
//@function runDeeptest
//@description One-call analytics endpoint: on the last confirmed history bar, computes engine statistics and renders the on-chart performance table.
//@param e Engine instance.
//@returns None.
export runDeeptest(PTEngine e) =>
    if barstate.islastconfirmedhistory
        ptStats(e, makeStatsConfig())
_closed(PTEngine e, int i) => i >= 0 and i < array.size(e.closed) ? array.get(e.closed, i) : na
_open(PTEngine e, int i)   => i >= 0 and i < array.size(e.legs)   ? array.get(e.legs, i)   : na
//@function closedtrades_entry_id
//@description Returns the id of the closed trade's entry. Mirrors `strategy.closedtrades.entry_id()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series string value.
export closedtrades_entry_id(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.entry_id
//@function closedtrades_entry_price
//@description Returns the price of the closed trade's entry. Mirrors `strategy.closedtrades.entry_price()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_entry_price(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.entry_price
//@function closedtrades_entry_time
//@description Returns the UNIX time of the closed trade's entry, expressed in milliseconds.. Mirrors `strategy.closedtrades.entry_time()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series int value.
export closedtrades_entry_time(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.entry_time
//@function closedtrades_entry_bar_index
//@description Returns the bar_index of the closed trade's entry. Mirrors `strategy.closedtrades.entry_bar_index()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Bar index.
export closedtrades_entry_bar_index(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.entry_bar_index
//@function closedtrades_entry_comment
//@description Returns the comment message of the closed trade's entry, or na if there is no entry with this trade_num. Mirrors `strategy.closedtrades.entry_comment()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Comment string.
export closedtrades_entry_comment(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.entry_comment
//@function closedtrades_exit_bar_index
//@description Returns the bar_index of the closed trade's exit. Mirrors `strategy.closedtrades.exit_bar_index()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series int value.
export closedtrades_exit_bar_index(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.exit_bar_index
//@function closedtrades_exit_id
//@description Returns the id of the closed trade's exit. Mirrors `strategy.closedtrades.exit_id()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series string value.
export closedtrades_exit_id(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.exit_id
//@function closedtrades_exit_price
//@description Returns the price of the closed trade's exit. Mirrors `strategy.closedtrades.exit_price()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_exit_price(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.exit_price
//@function closedtrades_exit_time
//@description Returns the UNIX time of the closed trade's exit, expressed in milliseconds. Mirrors `strategy.closedtrades.exit_time()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series int value.
export closedtrades_exit_time(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.exit_time
//@function closedtrades_exit_comment
//@description Returns the comment message of the closed trade's exit, or na if there is no entry with this trade_num. Mirrors `strategy.closedtrades.exit_comment()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Comment string.
export closedtrades_exit_comment(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.exit_comment
//@function closedtrades_max_drawdown
//@description Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed in `strategy.account_currency.` Mirrors `strategy.closedtrades.max_drawdown()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_max_drawdown(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.max_drawdown
//@function closedtrades_max_runup
//@description Returns the maximum run up of the closed trade, i.e., the maximum possible profit during the trade, expressed in `strategy.account_currency.` Mirrors `strategy.closedtrades.max_runup()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_max_runup(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.max_runup
//@function closedtrades_profit
//@description Returns the profit/loss of the closed trade in the strategy's account currency, reduced by the trade's commissions. A positive returned value represents a profit, and a negative value represents a loss. Mirrors `strategy.closedtrades.profit()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_profit(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.profit
//@function closedtrades_profit_percent
//@description Returns the profit/loss value of the closed trade, expressed as a percentage. Losses are expressed as negative values. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.closedtrades.profit_percent()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_profit_percent(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.profit_percent
//@function closedtrades_size
//@description Returns the direction and the number of contracts traded in the closed trade. If the value is > 0, the market position was long. If the value is < 0, the market position was short. Mirrors `strategy.closedtrades.size()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_size(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.dir * ct.qty
//@function closedtrades_commission
//@description Returns the sum of entry and exit fees paid in the closed trade, expressed in `strategy.account_currency.` Mirrors `strategy.closedtrades.commission()`.
//@param e Engine instance.
//@param i The trade number of the closed trade. The number of the first trade is zero.
//@returns Series float value.
export closedtrades_commission(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) ? na : ct.commission
//@function closedtrades_max_drawdown_percent
//@description Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed as a percentage and calculated by formula: Lowest Value During Trade / (Entry Price x Quantity) * 100. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.closedtrades.max_drawdown_percent()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Percent value (positive magnitude), `na` when the trade or denominator is unavailable.
export closedtrades_max_drawdown_percent(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) or ct.denom_at_close <= 0 ? na : ct.max_drawdown / ct.denom_at_close * 100.0
//@function closedtrades_max_runup_percent
//@description Returns the maximum run-up of the closed trade, i.e., the maximum possible profit during the trade, expressed as a percentage and calculated by formula: Highest Value During Trade / (Entry Price x Quantity) * 100. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.closedtrades.max_runup_percent()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Percent value, `na` when the trade or denominator is unavailable.
export closedtrades_max_runup_percent(PTEngine e, int i) =>
    ClosedTrade ct = _closed(e, i)
    na(ct) or ct.denom_at_close <= 0 ? na : ct.max_runup / ct.denom_at_close * 100.0
//@function opentrades_entry_id
//@description Returns the id of the open trade's entry. Mirrors `strategy.opentrades.entry_id()`.
//@param e Engine instance.
//@param i The trade number of the open trade. The number of the first trade is zero.
//@returns Series string value.
export opentrades_entry_id(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.entry_id
//@function opentrades_entry_price
//@description Returns the price of the open trade's entry. Mirrors `strategy.opentrades.entry_price()`.
//@param e Engine instance.
//@param i The trade number of the open trade. The number of the first trade is zero.
//@returns Series float value.
export opentrades_entry_price(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.avg_price
//@function opentrades_entry_time
//@description Returns the UNIX time of the open trade's entry, expressed in milliseconds. Mirrors `strategy.opentrades.entry_time()`.
//@param e Engine instance.
//@param i The trade number of the open trade. The number of the first trade is zero.
//@returns Series int value.
export opentrades_entry_time(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.entry_time
//@function opentrades_size
//@description Returns the direction and the number of contracts traded in the open trade. If the value is > 0, the market position was long. If the value is < 0, the market position was short. Mirrors `strategy.opentrades.size()`.
//@param e Engine instance.
//@param i The trade number of the open trade. The number of the first trade is zero.
//@returns Series float value.
export opentrades_size(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.dir * lg.qty
//@function opentrades_commission
//@description Returns the sum of entry and exit fees paid in the open trade, expressed in `strategy.account_currency.` Mirrors `strategy.opentrades.commission()`.
//@param e Engine instance.
//@param i The trade number of the open trade. The number of the first trade is zero.
//@returns Series float value.
export opentrades_commission(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.entry_commission
//@function opentrades_entry_bar_index
//@description Returns the bar_index of the open trade's entry. Mirrors `strategy.opentrades.entry_bar_index()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Bar index.
export opentrades_entry_bar_index(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.entry_bar_index
//@function opentrades_entry_comment
//@description Returns the comment message of the open trade's entry, or na if there is no entry with this trade_num. Mirrors `strategy.opentrades.entry_comment()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Comment string.
export opentrades_entry_comment(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.entry_comment
//@function opentrades_max_drawdown
//@description Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed in `strategy.account_currency.` Mirrors `strategy.opentrades.max_drawdown()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Positive drawdown value.
export opentrades_max_drawdown(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.max_drawdown
//@function opentrades_max_runup
//@description Returns the maximum run up of the open trade, i.e., the maximum possible profit during the trade, expressed in `strategy.account_currency.` Mirrors `strategy.opentrades.max_runup()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Positive runup value.
export opentrades_max_runup(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.max_runup
//@function opentrades_profit
//@description Returns the profit/loss of the open trade, expressed in `strategy.account_currency.` Losses are expressed as negative values. Mirrors `strategy.opentrades.profit()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns P&L in account currency. Multiplication order matches _closeLeg so open and closed P&L agree to the last float bit.
export opentrades_profit(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    // TV marks open trades at the current bar (e._bar_c cached in onBar —
    // built-in `close` is wrong when callers feed synthetic OHLC).
    na(lg) ? na : (e._bar_c - lg.avg_price) * lg.qty * lg.dir * syminfo.pointvalue * e._last_rate
//@function opentrades_profit_percent
//@description Returns the profit/loss of the open trade, expressed as a percentage. Losses are expressed as negative values. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.opentrades.profit_percent()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Percent value.
export opentrades_profit_percent(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : opentrades_profit(e, i) / _opOpenDenom(e, lg) * 100.0
//@function opentrades_max_drawdown_percent
//@description Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed as a percentage and calculated by formula: Lowest Value During Trade / (Entry Price x Quantity) * 100. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.opentrades.max_drawdown_percent()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Percent value.
export opentrades_max_drawdown_percent(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.max_drawdown / _opOpenDenom(e, lg) * 100.0
//@function opentrades_max_runup_percent
//@description Returns the maximum run-up of the open trade, i.e., the maximum possible profit during the trade, expressed as a percentage and calculated by formula: Highest Value During Trade / (Entry Price x Quantity) * 100. PineTunnel freezes the percent denominator at the trade's fill-time FX rate. Mirrors `strategy.opentrades.max_runup_percent()`.
//@param e Engine instance.
//@param i Trade index (0-based).
//@returns Percent value.
export opentrades_max_runup_percent(PTEngine e, int i) =>
    OpenTrade lg = _open(e, i)
    na(lg) ? na : lg.max_runup / _opOpenDenom(e, lg) * 100.0
//@function opentrades_capital_held
//@description Returns the capital amount currently held by open trades. Mirrors `strategy.opentrades.capital_held`.
//@param e Engine instance.
//@returns Capital in account currency.
export opentrades_capital_held(PTEngine e) =>
    capital_held(e, e._bar_c)

← 返回列表