Tide Trader-Ledger (Trade Journal & Performance Engine)

Coastal_Capital · study · 1750 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// © Coastal Capital | Tide Trader Series
indicator("Tide Trader: Trade Ledger & Performance Engine", shorttitle="🌊Tide Trader-Ledger (Journaling Framework)", overlay=true, max_lines_count=500, max_boxes_count=500, max_labels_count=500)
 
// ===========================================================================================================
// SECTION 01: MASTER VISUAL PALETTE & DESIGN SYSTEM TOKENS (INHERITED STRICTLY FROM SCRIPT 1)
// ===========================================================================================================
// --- Master Color Token Block (Tidal / Ocean Theme) ---
color c_bull_base    = #00FFA3 // Primary positive / win / long (Seafoam Neon)
color c_bull_sec     = #00F2FE // Secondary bullish / take-profit (Electric Cyan)
color c_seafoam      = #4EEDA6 // Subtle inflow tint / confirmation
color c_bear_base    = #FF6B6B // Primary negative / loss / risk / short (Coral Red)
color c_bear_sec     = #FF5A5F // Secondary bearish / displacement / underwater (Abyssal Red)
color c_bear_dark    = #B30000 // Deep crimson for dense stop-loss risk
color c_neutral      = #C8D1D9 // Breakeven / Cost Basis / Equilibrium (Coastal Fog Platinum)
color c_text_pri     = #E2EDF8 // High-contrast primary reading typography (Sea Salt White)
color c_text_mut     = #7E92A8 // Muted diagnostic / metadata slate
color c_dune         = #E2C9A5 // Coastal sand neutral
color c_amber        = #FFB703 // High visibility amber/gold for accents and ratios
color c_marine       = #177E89 // Vibrant marine blue for targets and secondary markers
color c_storm_teal   = #62686B // Structural reference / secondary boundary
color c_azure        = #005C99 // Azure blue for cost-basis reference
 
// HUD Matrix Tokens (Identical to Script 1)
color c_hud_bg       = #061325 // Ocean abyss HUD table cell background
color c_hud_hdr      = #162A45 // Navy HUD header background
color c_hud_border   = #2A4365 // Slate-blue table framing grid
color c_hud_txt      = #E2EDF8 // HUD primary typography
 
// ===========================================================================================================
// SECTION 02: NATIVE V6 ENUMS & OBJECT-ORIENTED STRUCTURES (UDTs)
// ===========================================================================================================
enum Direction
    LONG  = "LONG"
    SHORT = "SHORT"
 
enum TradeStatus
    OPEN   = "OPEN"
    CLOSED = "CLOSED"
    FLAT   = "FLAT"
 
enum HudPos
    top_right     = "Top Right"
    top_center    = "Top Center"
    top_left      = "Top Left"
    middle_right  = "Middle Right"
    middle_center = "Middle Center"
    middle_left   = "Middle Left"
    bottom_right  = "Bottom Right"
    bottom_center = "Bottom Center"
    bottom_left   = "Bottom Left"
 
enum HudSize
    auto_sz = "Auto"
    tiny    = "Tiny"
    small   = "Small"
    normal  = "Normal"
    large   = "Large"
 
type DCAEntry
    int    time_in
    float  price
    float  size
    int    ticket_id       = 0
    string symbol          = ""
    string direction       = "LONG"
    float  live_price      = na
    bool   has_live_feed   = true
    string currency        = "USD"
    float  sl_price        = 0.0
    bool   has_explicit_id = false
 
type Trade
    int             id
    string          symbol
    string          direction
    string          status
    array<DCAEntry> entries
    float           sl_price
    float           tp_price
    int             time_exit
    float           exit_price
    float           realized_pnl_pct
    float           realized_r_multiple
    float           cached_vwap       = na
    float           cached_size       = 0.0
    int             cached_first_time = na
    bool            has_explicit_id   = false
 
type AccountMetrics
    int   total_trades        = 0
    int   win_count           = 0
    int   loss_count          = 0
    int   breakeven_count     = 0
    float win_rate            = 0.0
    float profit_factor       = 0.0
    float expectancy          = 0.0
    float dollar_expectancy   = 0.0
    float gross_profit_pct    = 0.0
    float gross_loss_pct      = 0.0
    float avg_win_pct         = 0.0
    float avg_loss_pct        = 0.0
    float gross_profit_val    = 0.0
    float gross_loss_val      = 0.0
    float total_basis_val     = 0.0
    float avg_r_multiple      = 0.0
    int   r_trades_count      = 0
    float portfolio_open_risk = 0.0
    int   risk_open_count     = 0
 
// ===========================================================================================================
// SECTION 03: SETTINGS MODAL (STANDARDIZED 4-TIER ARCHITECTURE)
// ===========================================================================================================
string GRP_CORE   = "═════ 01. CORE ENGINE ═════"
string GRP_FILTER = "═════ 02. FILTERS & DIAGNOSTICS ═════"
string GRP_THEME  = "═════ 03. VISUAL THEME & PALETTE ═════"
string GRP_HUD    = "═════ 04. HUD DASHBOARD ═════"
 
// --- 01. CORE ENGINE ---
bool   i_show_trade_markers= input.bool(true,  "Individual DCA Entry Pins",   inline="core_vis", group=GRP_CORE, tooltip="Definition: Places a marker on the chart at the exact date, time, and price of every buy/sell entry in your ledger—both active DCA fills and completed historical trades.\n\nPro Tip: Recommended ON. If you place many scale-in orders close together and text badges overlap your candles, keep this ON and change 'DCA Marker Style' to 'Compact Pin' so you still see exact fill points without chart clutter.")
bool   i_show_closed_boxes = input.bool(true,  "Historical Trade Boxes",      inline="core_vis", group=GRP_CORE, tooltip="Definition: Draws a shaded rectangle for each closed trade spanning from your entry time and average entry price to your exit time and exit price—green for wins, red for losses.\n\nPro Tip: Recommended ON for post-trade review so you can immediately see holding duration and price capture. Quick same-bar scalps automatically expand to 1 bar wide so they never disappear on higher timeframes.")
bool   i_show_closed_labels= input.bool(true,  "Historical Exit Badges",      inline="core_vis2", group=GRP_CORE, tooltip="Definition: Displays a summary badge at the exit price of each completed trade showing Ticket ID, Symbol, and Realized Return % (with full size, VWAP, exit price, and R-multiple shown on hover).\n\nPro Tip: Recommended ON. On crowded charts with dozens of closed trades, pair this with 'Compact Pin' mode to shrink exit badges into clean dots while keeping all trade metrics one mouse-hover away.")
bool   i_show_box_connector= input.bool(true,  "Box Entry→Exit Connector",    inline="core_vis2", group=GRP_CORE, tooltip="Definition: Draws a thin dashed diagonal line inside each Historical Trade Box connecting your entry coordinate directly to your exit coordinate.\n\nPro Tip: Recommended ON. Especially helpful when multiple overlapping trades occur in the same price range, making it effortless to see whether each trade climbed from bottom-left to top-right (win) or dropped against you.")
string i_account_currency  = input.string(
     defval  = "Native (1:1 Unconverted)",
     title   = "Portfolio Base Reporting Currency",
     options = [
         "Native (1:1 Unconverted)",
         "USD",
         "AUD",
         "EUR",
         "GBP",
         "AED",
         "SGD",
         "INR",
         "JPY"
     ],
     group   = GRP_CORE,
     tooltip = "Definition: Chooses the currency used to convert and combine cash profits, losses, and deployed capital across all symbols in your ledger using live daily FX rates.\n\nPro Tip: Recommended: Set this to your broker account's funding currency (for example AUD or USD) when holding international stocks/ETFs so your Global Portfolio PnL adds up accurately. Keep 'Native (1:1 Unconverted)' only if all your trades are in the same currency."
 )
 
string i_ledger_tz         = input.string(
     defval  = "UTC+4 (Dubai)",
     title   = "Ledger Entry/Exit Timezone",
     options = [
         "UTC+4 (Dubai)",
         "Exchange Time (Chart Symbol)",
         "UTC+0 (GMT / UTC)",
         "Sydney / Melbourne (Australia/Sydney)",
         "New York (America/New_York)",
         "London (Europe/London)",
         "Singapore / Perth (Asia/Singapore)",
         "India (Asia/Kolkata)",
         "Tokyo (Asia/Tokyo)",
         "Custom UTC Offset"
     ],
     group   = GRP_CORE,
     tooltip = "Definition: Sets the timezone in which your typed or pasted entry and exit timestamps are written so pins and trade boxes align with your TradingView chart.\n\nPro Tip: Recommended: Keep 'UTC+4 (Dubai)' if your ledger entries use Dubai local time (or match your TradingView bottom-right clock). Choose 'Exchange Time (Chart Symbol)' only if each ticker's timestamps come directly from its native exchange clock."
 )
float  i_custom_tz_offset  = input.float(4.0, "Custom UTC Offset (Hours)", minval=-12.0, maxval=14.0, step=0.5, group=GRP_CORE, tooltip="Definition: Manual UTC hour offset (e.g., +4.0 for UTC+4, -5.0 for EST, +5.5 for IST) applied only when 'Ledger Entry/Exit Timezone' is set to 'Custom UTC Offset'.\n\nPro Tip: Leave at 4.0 unless you choose 'Custom UTC Offset' above for a region not listed in the presets.")
 
string i_trade_ledger      = input.text_area(
     defval  = "# MULTI-ASSET TRADE LEDGER (Single Trades, DCA Scale-Ins & Excel/Google Sheets Batch Pastes)\n# Open Trade:        BUY 68.20 09:30 qty=10 sl=65.00 tp=75.00\n# Close Same Line:   BUY 68.20 09:30 qty=10 sl=65.00 EXIT 69.50 10:15\n# Multi-Asset Open:  BGBL BUY 2026-10-02 10:00 81.50 qty=12 sl=78.00\n# Multi-Asset Close: 101 WULX BUY 2026-10-01 09:30 12.40 qty=50 sl=11.50 EXIT 2026-10-05 14:00 14.10\n# Direct Excel / Google Sheets (Tab-separated) & Semicolon/CSV formats are 100% supported!",
     title   = "Multi-Asset Trade Ledger",
     group   = GRP_CORE,
     tooltip = "Definition: Your single master trade log supporting open positions, DCA scale-ins, short trades, closed trades, and pasted Excel / Google Sheets Companion rows.\n\nExamples (one trade per line):\n• Intraday Open (Chart Symbol): BUY 81.50 10:00 qty=12 sl=78.00 tp=90.00\n• Open Short (Dated): SELL 2026-10-02 10:00 155.00 qty=5 sl=160.00\n• Multi-Asset / DCA Scale-In: BGBL BUY 2026-10-02 10:00 81.50 qty=12 (add another BGBL BUY line to blend VWAP)\n• Closed Trade: 101 WULX BUY 2026-10-01 09:30 12.40 qty=50 sl=11.50 EXIT 2026-10-05 14:00 14.10\n• Multi-Leg Closed Campaign: Reuse the same Ticket ID (e.g., 101) across multiple closed rows for the same symbol & direction.\n• Spreadsheet Batch: Copy-paste tab-separated Excel/Sheets or CSV/semicolon rows directly.\n\nPro Tip: Recommended workflow—maintain your log in the Companion spreadsheet, paste the formatted rows here, and click 'Defaults -> Save as default' at the bottom of Settings so your ledger stays saved across sessions and symbols."
 )
 
// --- 02. FILTERS & DIAGNOSTICS ---
int    i_max_trades_visualized = input.int(100, "Max Visualized Closed Trades", minval=1, maxval=150, inline="flt_tr", group=GRP_FILTER, tooltip="Definition: Limits how many of your most recent closed trades draw boxes, connectors, and badges on the chart at one time (up to 150).\n\nPro Tip: Recommended: 50 to 100. Your HUD performance statistics still calculate across your entire ledger history, while capping on-chart drawings keeps lower-timeframe charts fast and well under TradingView's 500-object limit.")
string i_dca_marker_style      = input.string("Full Badge", "DCA Marker Style", options=["Full Badge", "Compact Pin"], inline="flt_tr", group=GRP_FILTER, tooltip="Definition: Switches chart entry and exit markers between 'Full Badge' (text labels showing ID, quantity, price, or return %) and 'Compact Pin' (clean triangles/dots with full details shown when you hover).\n\nPro Tip: Recommended: Use 'Full Badge' for clean swing charts with 1–5 fills; switch to 'Compact Pin' when managing dense multi-entry DCA campaigns so price candles stay completely clear.")
string i_recent_return_format  = input.string("Auto (Show R Only If SL Set)", "Recent Activity Metric Format", options=["Auto (Show R Only If SL Set)", "Clean Percentage Only (%)", "Percentage + Dollar PnL ($%)"], group=GRP_FILTER, tooltip="Definition: Controls the extra detail shown beside the percentage return in the HUD's bottom activity rows (Rows 5–7).\n\nPro Tip: Recommended: 'Percentage + Dollar PnL ($%)' to see exact cash impact alongside % return on every position, or 'Auto (Show R Only If SL Set)' if you manage risk primarily by stop-loss R-multiples.")
bool   i_save_reminder         = input.bool(true, "Display Template Persistence Reminder", group=GRP_FILTER, tooltip="Definition: Enables built-in reminders about saving your TradingView indicator settings as a default template.\n\nPro Tip: Recommended ON. TradingView resets unsaved text-area edits if you remove and re-add an indicator—always use 'Defaults -> Save as default' after editing your ledger.")
 
// --- 03. VISUAL THEME & PALETTE ---
color  i_c_win           = input.color(color.new(c_bull_base, 50), "Win / Profit / Long", inline="thm_pnl", group=GRP_THEME, tooltip="Definition: Color used for winning closed trade boxes, profitable live VWAP lines, entry/exit badges in profit, and positive HUD numbers.\n\nPro Tip: Recommended: Seafoam Neon (#00FFA3) at 50% opacity for crisp readability on dark charts. Increase brightness or switch to a deeper emerald if using a bright white chart theme.")
color  i_c_loss          = input.color(color.new(c_bear_base, 50), "Loss / Risk / Short",  inline="thm_pnl", group=GRP_THEME, tooltip="Definition: Color used for losing closed trade boxes, underwater VWAP lines, Stop-Loss projection lines, and negative HUD returns.\n\nPro Tip: Recommended: Coral Red (#FF6B6B) for unmistakable contrast against winning zones and immediate visual warning when price approaches your stop loss.")
color  i_c_vwap          = input.color(color.new(c_neutral, 50),   "Cost Basis / Breakeven", inline="thm_ref", group=GRP_THEME, tooltip="Definition: Neutral reference color reserved for breakeven / cost-basis markers.\n\nPro Tip: Recommended: Keep at Coastal Fog Platinum (#C8D1D9) so neutral reference levels stay visually distinct from green profit and red risk zones.")
color  i_c_tp            = input.color(color.new(c_bull_sec, 50),  "Take-Profit Target",     inline="thm_ref", group=GRP_THEME, tooltip="Definition: Color of the horizontal dashed Take-Profit (TP) target line projected from your open position when a 'tp=' level is set.\n\nPro Tip: Recommended: Electric Cyan (#00F2FE) so your profit target stands out clearly from both your candles and your live VWAP line.")
int    i_box_fill_transp = input.int(80, "Trade Box Fill Transp (%)",   minval=40, maxval=98, step=5, inline="thm_box", group=GRP_THEME, tooltip="Definition: Sets how see-through the shaded interior of Historical Trade Boxes appears (higher % = lighter/more transparent).\n\nPro Tip: Recommended: 75% to 85%. This keeps trade zones clearly tinted for fast review while letting candlestick wicks and price action shine through cleanly.")
int    i_box_bdr_transp  = input.int(25, "Trade Box Border Transp (%)", minval=0,  maxval=80, step=5, inline="thm_box", group=GRP_THEME, tooltip="Definition: Sets the transparency of the outer border around Historical Trade Boxes and the diagonal Entry→Exit connector line.\n\nPro Tip: Recommended: 20% to 35% so box edges stay sharp and readable even when boxes overlap or when fill transparency is high.")
 
// --- 04. HUD DASHBOARD ---
bool    i_show_hud          = input.bool(true, "Display Institutional HUD", inline="hud_main", group=GRP_HUD, tooltip="Definition: Master toggle to show or hide the on-chart Coastal Capital Performance HUD table.\n\nPro Tip: Recommended ON during active trading and portfolio review. Toggle OFF temporarily if you want an unobstructed full-screen chart for pure technical markup.")
string  i_hud_scope         = input.string("Global Portfolio (All Symbols)", "Metrics Scope", options=["Global Portfolio (All Symbols)", "Current Chart Symbol Only"], inline="hud_main", group=GRP_HUD, tooltip="Definition: Chooses whether the HUD calculates totals across every ticker in your ledger ('Global Portfolio') or filters metrics strictly to the chart symbol currently open ('Current Chart Symbol Only').\n\nPro Tip: Recommended: 'Global Portfolio (All Symbols)' for whole-account monitoring, and switch to 'Current Chart Symbol Only' when auditing win rate, deployed capital, and fills for one specific stock or ETF.")
string  i_hud_activity_mode = input.string("Auto (Open on Active Chart, Else Closed)", "HUD Activity Feed", options=["Auto (Open on Active Chart, Else Closed)", "Open Positions Only", "Closed Trades Only"], group=GRP_HUD, tooltip="Definition: Selects whether the bottom 3 rows of the HUD list active Open DCA Positions or completed Closed Trades.\n\nPro Tip: Recommended: 'Auto (Open on Active Chart, Else Closed)' so open positions stay visible whenever you hold active trades, automatically switching to recent closed trades once you are flat. Use 'Closed Trades Only' during weekend post-trade journaling.")
HudPos  i_hud_pos           = input.enum(HudPos.top_right,   "HUD Anchor Corner", inline="hud_cfg", group=GRP_HUD, tooltip="Definition: Pins the HUD dashboard to any corner or edge of your chart pane.\n\nPro Tip: Recommended: 'Top Right' (default) or 'Bottom Left' depending on where your chart candles normally sit—placing it opposite recent price action prevents it from covering live bars or your VWAP badge.")
HudSize i_hud_size          = input.enum(HudSize.small,      "Typography Scale",  inline="hud_cfg", group=GRP_HUD, tooltip="Definition: Controls the font size and overall footprint of the HUD table ('Tiny', 'Small', 'Normal', 'Large', or 'Auto').\n\nPro Tip: Recommended: 'Small' for laptops and standard monitors (best balance of crisp monospace alignment and compact footprint), or 'Normal' on 4K ultrawide screens.")
color   i_c_hud_bg          = input.color(color.new(c_hud_bg, 0),     "HUD Cell Surface", inline="hud_c1", group=GRP_HUD, tooltip="Definition: Background fill color for the HUD's main data cells.\n\nPro Tip: Recommended: Deep Ocean Abyss (#061325) at 0% transparency so numbers stay sharp and readable even when candlesticks pass behind the table.")
color   i_c_hud_hdr         = input.color(color.new(c_hud_hdr, 0),    "HUD Header BG",    inline="hud_c1", group=GRP_HUD, tooltip="Definition: Background color for the HUD's top title bar and the Recent Activity section divider row.\n\nPro Tip: Recommended: Deep Navy (#162A45) to visually separate header bars from live data rows.")
color   i_c_hud_border      = input.color(color.new(c_hud_border, 0), "HUD Framing Grid", inline="hud_c2", group=GRP_HUD, tooltip="Definition: Color for the HUD's outer frame and interior cell gridlines.\n\nPro Tip: Recommended: Slate Blue (#2A4365) for subtle structure that organizes rows and columns without looking heavy.")
color   i_c_hud_txt         = input.color(c_hud_txt,                  "Primary Text",     inline="hud_c2", group=GRP_HUD, tooltip="Definition: Main text color for HUD metric values, column headers, and price transitions.\n\nPro Tip: Recommended: Sea Salt White (#E2EDF8) for clean high-contrast legibility against the dark Ocean Abyss background.")
color   i_c_hud_accent      = input.color(c_amber,                    "Accent / Gold",    inline="hud_c3", group=GRP_HUD, tooltip="Definition: Highlight text color used for key summary outputs like Gross Gain / Loss, Open Positions, Avg Win / Loss, and section banners.\n\nPro Tip: Recommended: Amber Gold (#FFB703) so portfolio totals and activity headers stand out immediately at a glance.")
color   i_c_hud_muted       = input.color(c_text_mut,                 "Muted Slate",      inline="hud_c3", group=GRP_HUD, tooltip="Definition: Subtle text color used for empty placeholder rows ('—' or 'No Open Portfolio Trades') in the HUD.\n\nPro Tip: Recommended: Muted Slate (#7E92A8) so empty slots fade cleanly into the background and never distract from active numbers.")
 
// ===========================================================================================================
// SECTION 04: HELPER FUNCTIONS & FORMATTING METHODS
// ===========================================================================================================
method to_pos(HudPos this) =>
    switch this
        HudPos.top_right     => position.top_right
        HudPos.top_center    => position.top_center
        HudPos.top_left      => position.top_left
        HudPos.middle_right  => position.middle_right
        HudPos.middle_center => position.middle_center
        HudPos.middle_left   => position.middle_left
        HudPos.bottom_right  => position.bottom_right
        HudPos.bottom_center => position.bottom_center
        HudPos.bottom_left   => position.bottom_left
        => position.top_right
 
method to_size(HudSize this) =>
    switch this
        HudSize.small   => size.small
        HudSize.tiny    => size.tiny
        HudSize.normal  => size.normal
        HudSize.large   => size.large
        HudSize.auto_sz => size.auto
        => size.small
 
// Single-pass UDT finalizer: computes and caches total_size, vwap, earliest fill time, realized PnL %, and R-multiple in O(N)
method finalize(Trade this) =>
    float sum_pq   = 0.0
    float sum_q    = 0.0
    int   earliest = na
    if not na(this.entries)
        for entry in this.entries
            if not na(entry.price) and entry.price > 0.0 and not na(entry.size) and entry.size > 0.0
                sum_pq += entry.price * entry.size
                sum_q  += entry.size
                if not na(entry.time_in)
                    earliest := na(earliest) ? entry.time_in : math.min(earliest, entry.time_in)
    this.cached_size       := sum_q
    this.cached_vwap       := sum_q > 0.0 ? (sum_pq / sum_q) : na
    this.cached_first_time := earliest
    if this.status == "CLOSED" and not na(this.cached_vwap) and this.cached_vwap > 0.0 and not na(this.exit_price) and this.exit_price > 0.0
        this.realized_pnl_pct := this.direction == "LONG" ? ((this.exit_price - this.cached_vwap) / this.cached_vwap) * 100.0 : ((this.cached_vwap - this.exit_price) / this.cached_vwap) * 100.0
        if not na(this.sl_price) and this.sl_price > 0.0
            float risk = math.abs(this.cached_vwap - this.sl_price)
            if risk > 0.0
                float reward = this.direction == "LONG" ? (this.exit_price - this.cached_vwap) : (this.cached_vwap - this.exit_price)
                this.realized_r_multiple := reward / risk
    this
 
method get_total_size(Trade this) =>
    if this.cached_size > 0.0
        this.cached_size
    else
        float total_qty = 0.0
        if not na(this.entries)
            for entry in this.entries
                if not na(entry.size) and entry.size > 0.0 and not na(entry.price) and entry.price > 0.0
                    total_qty += entry.size
        this.cached_size := total_qty
        total_qty
 
method get_vwap(Trade this) =>
    if not na(this.cached_vwap)
        this.cached_vwap
    else
        float sum_pq = 0.0
        float sum_q  = 0.0
        if not na(this.entries)
            for entry in this.entries
                if not na(entry.price) and entry.price > 0.0 and not na(entry.size) and entry.size > 0.0
                    sum_pq += entry.price * entry.size
                    sum_q  += entry.size
        this.cached_vwap := sum_q > 0.0 ? (sum_pq / sum_q) : na
        this.cached_vwap
 
method calculate_unrealized_pnl(Trade this, float current_close) =>
    float vwap = this.get_vwap()
    float unrealized_pct = 0.0
    if not na(vwap) and vwap > 0.0 and not na(current_close)
        unrealized_pct := this.direction == "LONG" ? ((current_close - vwap) / vwap) * 100.0 : ((vwap - current_close) / vwap) * 100.0
    unrealized_pct
 
method calculate_r_multiple(Trade this) =>
    if not na(this.realized_r_multiple)
        this.realized_r_multiple
    else
        float vwap = this.get_vwap()
        float r_mult = na
        if not na(vwap) and vwap > 0.0 and not na(this.sl_price) and this.sl_price > 0.0 and not na(this.exit_price) and this.exit_price > 0.0
            float risk = math.abs(vwap - this.sl_price)
            if risk > 0.0
                float reward = this.direction == "LONG" ? (this.exit_price - vwap) : (vwap - this.exit_price)
                r_mult := reward / risk
        this.realized_r_multiple := r_mult
        r_mult
 
method get_first_entry_time(Trade this) =>
    if not na(this.cached_first_time)
        this.cached_first_time
    else
        int earliest = na
        if not na(this.entries)
            for entry in this.entries
                if not na(entry.time_in) and entry.price > 0.0 and entry.size > 0.0
                    earliest := na(earliest) ? entry.time_in : math.min(earliest, entry.time_in)
        this.cached_first_time := earliest
        earliest
 
// FIFO Eviction & Drawing Queues
var array<box>   closed_boxes      = array.new<box>()
var array<line>  closed_lines      = array.new<line>()
var array<label> closed_labels     = array.new<label>()
var array<label> closed_entry_pins = array.new<label>()
var table        t_hud             = na
var string       last_tbl_pos      = ""
var string       last_tbl_sz       = ""
var color        last_hud_bg       = na
var color        last_hud_bdr      = na
 
// Persistent Object Pool for Live On-Chart Projections (Zero GC Churn / Zero Micro-Flicker)
var line         vwap_ray      = line.new(na, na, na, na, xloc=xloc.bar_time, style=line.style_solid,  width=1)
var line         sl_ray        = line.new(na, na, na, na, xloc=xloc.bar_time, style=line.style_dashed, width=1)
var line         tp_ray        = line.new(na, na, na, na, xloc=xloc.bar_time, style=line.style_dashed, width=1)
var label        live_lbl      = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_label_left, size=size.small)
var array<label> dca_pins_pool = array.new<label>()
 
f_enqueue_box(array<box> queue, box b, int max_limit) =>
    queue.push(b)
    while queue.size() > math.max(1, max_limit)
        box evicted = queue.shift()
        if not na(evicted)
            box.delete(evicted)
 
f_enqueue_line(array<line> queue, line ln, int max_limit) =>
    queue.push(ln)
    while queue.size() > math.max(1, max_limit)
        line evicted = queue.shift()
        if not na(evicted)
            line.delete(evicted)
 
f_enqueue_label(array<label> queue, label lb, int max_limit) =>
    queue.push(lb)
    while queue.size() > math.max(1, max_limit)
        label evicted = queue.shift()
        if not na(evicted)
            label.delete(evicted)
 
f_clear_boxes(array<box> b_q) =>
    while b_q.size() > 0
        box b = b_q.shift()
        if not na(b)
            box.delete(b)
 
f_clear_lines(array<line> l_q) =>
    while l_q.size() > 0
        line l = l_q.shift()
        if not na(l)
            line.delete(l)
 
f_clear_labels(array<label> lb_q) =>
    while lb_q.size() > 0
        label lb = lb_q.shift()
        if not na(lb)
            label.delete(lb)
 
f_solid(color c) =>
    color.rgb(color.r(c), color.g(c), color.b(c), 0)
 
f_with_transp(color c, int transp_val) =>
    color.rgb(color.r(c), color.g(c), color.b(c), transp_val)
 
f_badge_text_color(color badge_bg, color pref_text) =>
    float alpha = (100.0 - float(color.t(badge_bg))) / 100.0
    float eff_r = alpha * color.r(badge_bg) + (1.0 - alpha) * color.r(chart.bg_color)
    float eff_g = alpha * color.g(badge_bg) + (1.0 - alpha) * color.g(chart.bg_color)
    float eff_b = alpha * color.b(badge_bg) + (1.0 - alpha) * color.b(chart.bg_color)
    float lum   = 0.299 * eff_r + 0.587 * eff_g + 0.114 * eff_b
    lum > 145.0 ? color.rgb(6, 19, 37, 0) : f_solid(pref_text)
 
f_strip_exchange(string raw_sym) =>
    string s = str.upper(str.trim(raw_sym))
    if str.contains(s, ":")
        array<string> parts = str.split(s, ":")
        s := parts.size() >= 2 ? str.trim(parts.get(1)) : s
    if str.endswith(s, ".AX")
        s := str.substring(s, 0, str.length(s) - 3)
    else if str.endswith(s, ".US")
        s := str.substring(s, 0, str.length(s) - 3)
    else if str.endswith(s, ".L")
        s := str.substring(s, 0, str.length(s) - 2)
    else if str.endswith(s, ".DE")
        s := str.substring(s, 0, str.length(s) - 3)
    s
 
f_get_exchange(string raw_sym) =>
    string s = str.upper(str.trim(raw_sym))
    if str.contains(s, ":")
        array<string> parts = str.split(s, ":")
        parts.size() >= 2 ? str.trim(parts.get(0)) : ""
    else
        ""
 
f_clean_num(string raw) =>
    string clean = str.replace_all(str.replace_all(str.replace_all(str.trim(raw), "$", ""), ",", ""), "%", "")
    str.length(clean) > 0 ? str.tonumber(clean) : na
 
f_split_row(string row_str) =>
    string delim = str.contains(row_str, "\t") ? "\t" : (str.contains(row_str, ";") ? ";" : (str.contains(row_str, "|") ? "|" : (str.contains(row_str, ",") ? "," : "")))
    array<string> res = array.new<string>()
    if delim != ""
        string padded = str.replace_all(row_str, delim + delim, delim + " " + delim)
        padded := str.replace_all(padded, delim + delim, delim + " " + delim)
        if str.endswith(padded, delim)
            padded := padded + " "
        res := str.split(padded, delim)
    else
        array<string> raw_tokens = str.split(row_str, " ")
        for t in raw_tokens
            string cl = str.trim(t)
            if str.length(cl) > 0 and cl != "@"
                res.push(cl)
    res
 
f_symbol_matches_chart(string raw_sym) =>
    string s       = f_strip_exchange(raw_sym)
    string exch    = f_get_exchange(raw_sym)
    string chart_t = str.upper(syminfo.ticker)
    string chart_r = str.upper(syminfo.root)
    string chart_x = str.upper(syminfo.prefix)
    bool exch_ok   = exch == "" or exch == chart_x or (exch == "CBOE" and chart_x == "ASX") or (exch == "ASX" and chart_x == "CBOE")
    bool is_match  = false
    if s == "" or s == "CURRENT" or s == "ALL" or s == "*"
        is_match := true
    else if (chart_t == s or chart_r == s) and exch_ok
        is_match := true
    else if (s == "GOLD" or s == "XAU" or s == "XAUUSD") and (chart_t == "GOLD" or chart_t == "XAUUSD" or chart_r == "GC" or chart_r == "XAU")
        is_match := true
    else if (s == "SILVER" or s == "XAG" or s == "XAGUSD") and (chart_t == "SILVER" or chart_t == "XAGUSD" or chart_r == "SI" or chart_r == "XAG")
        is_match := true
    else if (s == "BTC" or s == "BTCUSD" or s == "BTCUSDT") and (chart_t == "BTCUSD" or chart_t == "BTCUSDT" or chart_t == "XBTUSD" or chart_r == "BTC")
        is_match := true
    is_match
 
// ===========================================================================================================
// SECTION 05: INTERMARKET DATA FEEDS & TRIANGULATED FX ENGINE (30 / 40 QUOTA CALLS)
// ===========================================================================================================
// Essential FX Conversion Feeds (7 Calls)
float feed_audusd = request.security("FX_IDC:AUDUSD", "D", close, ignore_invalid_symbol=true)
float feed_eurusd = request.security("FX_IDC:EURUSD", "D", close, ignore_invalid_symbol=true)
float feed_gbpusd = request.security("FX_IDC:GBPUSD", "D", close, ignore_invalid_symbol=true)
float feed_usdaed = request.security("FX_IDC:USDAED", "D", close, ignore_invalid_symbol=true)
float feed_usdsgd = request.security("FX_IDC:USDSGD", "D", close, ignore_invalid_symbol=true)
float feed_usdinr = request.security("FX_IDC:USDINR", "D", close, ignore_invalid_symbol=true)
float feed_usdjpy = request.security("FX_IDC:USDJPY", "D", close, ignore_invalid_symbol=true)
 
// High-Liquidity Benchmark & Intermarket Equity Feeds (23 Calls)
float feed_btcusd = request.security("BTCUSD",        "D", close, ignore_invalid_symbol=true)
float feed_ethusd = request.security("ETHUSD",        "D", close, ignore_invalid_symbol=true)
float feed_solusd = request.security("SOLUSD",        "D", close, ignore_invalid_symbol=true)
float feed_gold   = request.security("GOLD",          "D", close, ignore_invalid_symbol=true)
float feed_silver = request.security("SILVER",        "D", close, ignore_invalid_symbol=true)
float feed_usoil  = request.security("USOIL",         "D", close, ignore_invalid_symbol=true)
float feed_spy    = request.security("SPY",           "D", close, ignore_invalid_symbol=true)
float feed_qqq    = request.security("QQQ",           "D", close, ignore_invalid_symbol=true)
float feed_tqqq   = request.security("TQQQ",          "D", close, ignore_invalid_symbol=true)
float feed_sqqq   = request.security("SQQQ",          "D", close, ignore_invalid_symbol=true)
float feed_soxl   = request.security("SOXL",          "D", close, ignore_invalid_symbol=true)
float feed_soxs   = request.security("SOXS",          "D", close, ignore_invalid_symbol=true)
float feed_iwm    = request.security("IWM",           "D", close, ignore_invalid_symbol=true)
float feed_nvda   = request.security("NVDA",          "D", close, ignore_invalid_symbol=true)
float feed_tsla   = request.security("TSLA",          "D", close, ignore_invalid_symbol=true)
float feed_aapl   = request.security("AAPL",          "D", close, ignore_invalid_symbol=true)
float feed_a200   = request.security("ASX:A200",      "D", close, ignore_invalid_symbol=true)
float feed_bgbl   = request.security("ASX:BGBL",      "D", close, ignore_invalid_symbol=true)
float feed_ebtc_c = request.security("CBOE:EBTC",     "D", close, ignore_invalid_symbol=true)
float feed_pmgold = request.security("ASX:PMGOLD",    "D", close, ignore_invalid_symbol=true)
float feed_gdx_au = request.security("ASX:GDX",       "D", close, ignore_invalid_symbol=true)
float feed_ggov   = request.security("ASX:GGOV",      "D", close, ignore_invalid_symbol=true)
float feed_etpmag = request.security("ASX:ETPMAG",    "D", close, ignore_invalid_symbol=true)
 
f_normalize_base_currency(string raw) =>
    if str.contains(raw, "AUD")
        "AUD"
    else if str.contains(raw, "EUR")
        "EUR"
    else if str.contains(raw, "GBP")
        "GBP"
    else if str.contains(raw, "AED")
        "AED"
    else if str.contains(raw, "SGD")
        "SGD"
    else if str.contains(raw, "INR")
        "INR"
    else if str.contains(raw, "JPY")
        "JPY"
    else if str.contains(raw, "USD")
        "USD"
    else
        "Native"
 
f_detect_symbol_currency(string raw_sym, float ref_price) =>
    string exch = f_get_exchange(raw_sym)
    string s    = f_strip_exchange(raw_sym)
    if f_symbol_matches_chart(raw_sym) and syminfo.currency != ""
        syminfo.currency
    else if exch == "ASX" or exch == "CBOE" or exch == "CHIXAU" or exch == "AUD" or str.endswith(s, ".AX")
        "AUD"
    else if exch == "XETR" or exch == "FWB" or exch == "EURONEXT" or exch == "EPA" or exch == "EBR" or exch == "BIT" or exch == "BME" or exch == "EUR" or str.endswith(s, ".DE")
        "EUR"
    else if exch == "LSE" or exch == "LON" or exch == "LSIN" or exch == "GBP" or str.endswith(s, ".L")
        "GBP"
    else if exch == "DFM" or exch == "ADX" or exch == "AED"
        "AED"
    else if exch == "SGX" or exch == "SGD" or str.endswith(s, ".SI")
        "SGD"
    else if exch == "NSE" or exch == "BSE" or exch == "INR" or str.endswith(s, ".NS") or str.endswith(s, ".BO")
        "INR"
    else if exch == "TSE" or exch == "TYO" or exch == "JPY" or str.endswith(s, ".T")
        "JPY"
    else if exch == "AMEX" or exch == "NYSE" or exch == "NASDAQ" or exch == "ARCA" or exch == "USD"
        "USD"
    else if s == "A200" or s == "BGBL" or s == "EBTC" or s == "PMGOLD" or s == "GGOV" or s == "ETPMAG" or s == "NDQ"
        "AUD"
    else if s == "GDX"
        ref_price > 75.0 ? "AUD" : "USD"
    else
        "USD"
 
f_currency_symbol(string base_mode) =>
    string norm = f_normalize_base_currency(base_mode)
    switch norm
        "AUD" => "A$"
        "EUR" => "€"
        "GBP" => "£"
        "AED" => "AED "
        "SGD" => "S$"
        "INR" => "₹"
        "JPY" => "¥"
        => "$"
 
f_get_rate_to_usd(string curr) =>
    float r_aud = nz(feed_audusd, 0.67)   > 0.0 ? nz(feed_audusd, 0.67)   : 0.67
    float r_eur = nz(feed_eurusd, 1.09)   > 0.0 ? nz(feed_eurusd, 1.09)   : 1.09
    float r_gbp = nz(feed_gbpusd, 1.30)   > 0.0 ? nz(feed_gbpusd, 1.30)   : 1.30
    float r_aed = nz(feed_usdaed, 3.6725) > 0.0 ? nz(feed_usdaed, 3.6725) : 3.6725
    float r_sgd = nz(feed_usdsgd, 1.32)   > 0.0 ? nz(feed_usdsgd, 1.32)   : 1.32
    float r_inr = nz(feed_usdinr, 84.0)   > 0.0 ? nz(feed_usdinr, 84.0)   : 84.0
    float r_jpy = nz(feed_usdjpy, 150.0)  > 0.0 ? nz(feed_usdjpy, 150.0)  : 150.0
    switch curr
        "USD" => 1.0
        "AUD" => r_aud
        "EUR" => r_eur
        "GBP" => r_gbp
        "AED" => 1.0 / r_aed
        "SGD" => 1.0 / r_sgd
        "INR" => 1.0 / r_inr
        "JPY" => 1.0 / r_jpy
        => 1.0
 
f_fx_multiplier(string asset_curr, string base_mode) =>
    string norm_base = f_normalize_base_currency(base_mode)
    if norm_base == "Native" or asset_curr == norm_base
        1.0
    else
        float asset_to_usd = f_get_rate_to_usd(asset_curr)
        float base_to_usd  = f_get_rate_to_usd(norm_base)
        base_to_usd > 0.0 ? (asset_to_usd / base_to_usd) : 1.0
 
f_resolve_live_price_with_status(string raw_sym, float fallback_entry) =>
    float px = na
    if f_symbol_matches_chart(raw_sym)
        px := close
    else
        string s = f_strip_exchange(raw_sym)
        px := switch s
            "A200"    => feed_a200
            "BGBL"    => feed_bgbl
            "EBTC"    => feed_ebtc_c
            "PMGOLD"  => feed_pmgold
            "GDX"     => feed_gdx_au
            "GGOV"    => feed_ggov
            "ETPMAG"  => feed_etpmag
            "BTC"     => feed_btcusd
            "BTCUSD"  => feed_btcusd
            "BTCUSDT" => feed_btcusd
            "ETH"     => feed_ethusd
            "ETHUSD"  => feed_ethusd
            "ETHUSDT" => feed_ethusd
            "SOL"     => feed_solusd
            "SOLUSD"  => feed_solusd
            "SOLUSDT" => feed_solusd
            "GOLD"    => feed_gold
            "XAUUSD"  => feed_gold
            "SILVER"  => feed_silver
            "XAGUSD"  => feed_silver
            "USOIL"   => feed_usoil
            "SPY"     => feed_spy
            "QQQ"     => feed_qqq
            "TQQQ"    => feed_tqqq
            "SQQQ"    => feed_sqqq
            "SOXL"    => feed_soxl
            "SOXS"    => feed_soxs
            "IWM"     => feed_iwm
            "NVDA"    => feed_nvda
            "TSLA"    => feed_tsla
            "AAPL"    => feed_aapl
            => na
    bool has_feed = not na(px) and px > 0.0
    [has_feed ? px : fallback_entry, has_feed]
 
f_resolve_live_price(string raw_sym, float fallback_entry) =>
    [px, _] = f_resolve_live_price_with_status(raw_sym, fallback_entry)
    px
 
f_is_dir_token(string tok) =>
    string u = str.upper(str.trim(tok))
    u == "L" or u == "LONG" or u == "BUY" or u == "S" or u == "SHORT" or u == "SELL"
 
f_is_currency_token(string tok) =>
    string tu = str.upper(str.trim(tok))
    tu == "AUD" or tu == "USD" or tu == "EUR" or tu == "GBP" or tu == "CAD" or tu == "CHF" or tu == "NZD" or tu == "JPY" or tu == "SGD" or tu == "HKD" or tu == "AED" or tu == "INR" or tu == "CNY" or tu == "USDT" or tu == "USDC" or tu == "BUSD" or tu == "DAI"
 
f_is_date_only(string s) =>
    string cl = str.trim(s)
    (str.contains(cl, "-") or str.contains(cl, "/")) and not str.contains(cl, ":")
 
f_is_time_only(string s) =>
    string cl = str.trim(s)
    str.contains(cl, ":") and not str.contains(cl, "-") and not str.contains(cl, "/")
 
f_merge_delim_datetime(array<string> raw_cols) =>
    array<string> merged = array.new<string>()
    int idx = 0
    while idx < raw_cols.size()
        string cur = str.trim(raw_cols.get(idx))
        if idx + 1 < raw_cols.size() and f_is_date_only(cur) and f_is_time_only(raw_cols.get(idx + 1))
            merged.push(cur + " " + str.trim(raw_cols.get(idx + 1)))
            idx += 2
        else
            merged.push(cur)
            idx += 1
    merged
 
// Timezone Resolution & Formatting Helpers
f_tz_id() =>
    switch i_ledger_tz
        "UTC+4 (Dubai)"                         => "Asia/Dubai"
        "Exchange Time (Chart Symbol)"          => syminfo.timezone
        "UTC+0 (GMT / UTC)"                     => "Etc/UTC"
        "Sydney / Melbourne (Australia/Sydney)" => "Australia/Sydney"
        "New York (America/New_York)"           => "America/New_York"
        "London (Europe/London)"                => "Europe/London"
        "Singapore / Perth (Asia/Singapore)"    => "Asia/Singapore"
        "India (Asia/Kolkata)"                  => "Asia/Kolkata"
        "Tokyo (Asia/Tokyo)"                    => "Asia/Tokyo"
        => "Etc/UTC"
 
f_tz_label() =>
    if i_ledger_tz == "Custom UTC Offset"
        string sgn = i_custom_tz_offset >= 0.0 ? "+" : ""
        "UTC" + sgn + str.tostring(i_custom_tz_offset, "#.#")
    else if i_ledger_tz == "Exchange Time (Chart Symbol)"
        syminfo.timezone
    else
        i_ledger_tz
 
f_tz_shift_ms() =>
    i_ledger_tz == "Custom UTC Offset" ? int(math.round(i_custom_tz_offset * 3600000.0)) : 0
 
f_extract_ymd(int ts_ms) =>
    int shift = f_tz_shift_ms()
    string tz = f_tz_id()
    int t_eff = ts_ms + shift
    [year(t_eff, tz), month(t_eff, tz), dayofmonth(t_eff, tz)]
 
f_build_ts(int yr, int mo, int dy, int hr, int mn, int sc, bool force_utc = false) =>
    if force_utc
        timestamp("Etc/UTC", yr, mo, dy, hr, mn, sc)
    else
        int raw_ts = timestamp(f_tz_id(), yr, mo, dy, hr, mn, sc)
        raw_ts - f_tz_shift_ms()
 
f_format_ts(int ts_ms) =>
    if na(ts_ms)
        "—"
    else
        int shift = f_tz_shift_ms()
        string tz = f_tz_id()
        int t_eff = ts_ms + shift
        str.tostring(year(t_eff, tz)) + "-" + str.tostring(month(t_eff, tz), "00") + "-" + str.tostring(dayofmonth(t_eff, tz), "00") + " " + str.tostring(hour(t_eff, tz), "00") + ":" + str.tostring(minute(t_eff, tz), "00")
 
// Robust Timezone-Aware Timestamp Parser with Last-Bar Ceiling & Session Rollback
f_parse_timestamp(string raw_dt) =>
    string clean = str.trim(raw_dt)
    int result_ts = na
    if str.length(clean) > 0
        string u_clean = str.upper(clean)
        bool force_utc = str.endswith(u_clean, "Z")
        if force_utc
            clean   := str.trim(str.substring(clean, 0, str.length(clean) - 1))
            u_clean := str.upper(clean)
        bool is_pm = str.contains(u_clean, "PM")
        bool is_am = str.contains(u_clean, "AM")
        if is_pm or is_am
            clean := str.trim(str.replace_all(str.replace_all(str.replace_all(str.replace_all(clean, "PM", ""), "pm", ""), "AM", ""), "am", ""))
        clean := str.trim(str.replace_all(str.replace_all(clean, "T", " "), "t", " "))
 
        int bar_ceil  = math.max(last_bar_time, math.max(time, nz(time_close, last_bar_time)))
        int ref_clock = math.max(bar_ceil, timenow)
        [cur_yr, cur_mo, cur_dy] = f_extract_ymd(ref_clock)
 
        if str.contains(clean, ":") and not str.contains(clean, "-") and not str.contains(clean, "/")
            array<string> t_parts = str.split(clean, ":")
            int hr = int(nz(str.tonumber(t_parts.get(0)), 0))
            int mn = t_parts.size() >= 2 ? int(nz(str.tonumber(t_parts.get(1)), 0)) : 0
            int sc = t_parts.size() >= 3 ? int(nz(str.tonumber(t_parts.get(2)), 0)) : 0
            if is_pm and hr < 12
                hr += 12
            else if is_am and hr == 12
                hr := 0
            int parsed_time = f_build_ts(cur_yr, cur_mo, cur_dy, hr, mn, sc, force_utc)
            if parsed_time > timenow
                parsed_time -= 86400000
            if parsed_time > bar_ceil
                parsed_time := bar_ceil
            result_ts := parsed_time
        else
            array<string> raw_dt_parts = str.split(clean, " ")
            array<string> dt_parts     = array.new<string>()
            for dtp in raw_dt_parts
                string dt_s = str.trim(dtp)
                if str.length(dt_s) > 0
                    dt_parts.push(dt_s)
            string date_norm       = str.replace_all(dt_parts.get(0), "/", "-")
            array<string> d_parts  = str.split(date_norm, "-")
            int yr = cur_yr
            int mo = 1
            int dy = 1
            if d_parts.size() == 2
                mo := int(nz(str.tonumber(d_parts.get(0)), 1))
                dy := int(nz(str.tonumber(d_parts.get(1)), 1))
            else if d_parts.size() >= 3
                string p0 = str.trim(d_parts.get(0))
                string p1 = str.trim(d_parts.get(1))
                string p2 = str.trim(d_parts.get(2))
                bool is_dmy = str.length(p0) <= 2 and str.length(p2) == 4
                yr := int(nz(str.tonumber(is_dmy ? p2 : p0), cur_yr))
                mo := int(nz(str.tonumber(p1), 1))
                dy := int(nz(str.tonumber(is_dmy ? p0 : p2), 1))
 
            int hr = 0
            int mn = 0
            int sc = 0
            if dt_parts.size() >= 2
                array<string> t_parts = str.split(dt_parts.get(1), ":")
                if t_parts.size() >= 1
                    hr := int(nz(str.tonumber(t_parts.get(0)), 0))
                if t_parts.size() >= 2
                    mn := int(nz(str.tonumber(t_parts.get(1)), 0))
                if t_parts.size() >= 3
                    sc := int(nz(str.tonumber(t_parts.get(2)), 0))
            if is_pm and hr < 12
                hr += 12
            else if is_am and hr == 12
                hr := 0
            result_ts := f_build_ts(yr, mo, dy, hr, mn, sc, force_utc)
            if result_ts > ref_clock and yr > cur_yr
                result_ts := f_build_ts(cur_yr, mo, dy, hr, mn, sc, force_utc)
            if result_ts > bar_ceil
                result_ts := bar_ceil
    result_ts
 
f_build_closed_trade(int id_val, string sym_val, string dir_raw, int t_in, float avg_in, int t_out, float avg_out, float sl_val, float size_val = 1.0, string curr_override = "", bool explicit_id = false) =>
    string clean_sym = str.length(str.trim(sym_val)) > 0 ? f_strip_exchange(sym_val) : syminfo.ticker
    string norm_dir  = (dir_raw == "S" or dir_raw == "SHORT" or dir_raw == "SELL") ? "SHORT" : "LONG"
    float  safe_qty  = math.max(nz(size_val, 1.0), 0.0001)
    string curr      = curr_override != "" ? curr_override : f_detect_symbol_currency(sym_val, avg_in)
    array<DCAEntry> tr_list = array.new<DCAEntry>()
    tr_list.push(DCAEntry.new(t_in, avg_in, safe_qty, id_val, clean_sym, norm_dir, avg_out, true, curr, sl_val, explicit_id))
    Trade tr = Trade.new(
         id                  = id_val,
         symbol              = clean_sym,
         direction           = norm_dir,
         status              = "CLOSED",
         entries             = tr_list,
         sl_price            = sl_val,
         tp_price            = 0.0,
         time_exit           = t_out,
         exit_price          = avg_out,
         realized_pnl_pct    = 0.0,
         realized_r_multiple = na,
         has_explicit_id     = explicit_id
     )
    tr.finalize()
 
f_parse_universal_row(string raw_line, int default_id) =>
    string line = str.trim(raw_line)
    int    max_bar_t = math.max(last_bar_time, math.max(time, nz(time_close, last_bar_time)))
    int    t_id = default_id
    bool   has_explicit_id = false
    string t_sym = syminfo.ticker
    string t_dir = "LONG"
    int    t_in  = max_bar_t
    float  p_in  = 0.0
    float  t_size = 1.0
    float  p_sl  = 0.0
    float  p_tp  = 0.0
    int    t_out = na
    float  p_out = 0.0
    string t_curr = ""
 
    string u_line    = str.replace_all(str.upper(line), "\t", " ")
    int    exit_pos  = str.pos(u_line, " EXIT ")
    int    exit_len  = 6
    if na(exit_pos)
        exit_pos := str.pos(u_line, " CLOSED ")
        exit_len := 8
    if na(exit_pos)
        exit_pos := str.pos(u_line, " OUT ")
        exit_len := 5
    if na(exit_pos)
        exit_pos := str.pos(u_line, " -> ")
        exit_len := 4
 
    string entry_seg = not na(exit_pos) ? str.trim(str.substring(line, 0, exit_pos)) : line
    string exit_seg  = not na(exit_pos) ? str.trim(str.substring(line, exit_pos + exit_len)) : ""
 
    bool has_delim = str.contains(entry_seg, "\t") or str.contains(entry_seg, ";") or str.contains(entry_seg, "|") or str.contains(entry_seg, ",")
 
    if has_delim
        array<string> raw_cols = f_split_row(entry_seg)
        array<string> cols     = f_merge_delim_datetime(raw_cols)
        if cols.size() >= 2
            string c0 = str.trim(cols.get(0))
            string c1 = str.trim(cols.get(1))
            string c2 = cols.size() >= 3 ? str.trim(cols.get(2)) : ""
 
            for c_i = 0 to cols.size() - 1
                string c_val = str.upper(str.trim(cols.get(c_i)))
                if f_is_currency_token(c_val)
                    t_curr := c_val
 
            bool is_ticket_first = not na(f_clean_num(c0)) and f_is_dir_token(c2)
            if is_ticket_first
                t_id            := int(nz(f_clean_num(c0), default_id))
                has_explicit_id := true
                t_sym           := not f_is_currency_token(c1) ? str.upper(c1) : t_sym
                t_dir           := (str.upper(c2) == "S" or str.upper(c2) == "SHORT" or str.upper(c2) == "SELL") ? "SHORT" : "LONG"
                t_in            := cols.size() >= 4 and str.length(str.trim(cols.get(3))) > 0 ? nz(f_parse_timestamp(cols.get(3)), max_bar_t) : max_bar_t
                p_in            := cols.size() >= 5 ? nz(f_clean_num(cols.get(4)), 0.0) : 0.0
                bool is_batch_style = cols.size() >= 7 and (str.length(str.trim(cols.get(5))) == 0 or str.contains(cols.get(5), "-") or str.contains(cols.get(5), ":") or str.contains(cols.get(5), "/"))
                if is_batch_style
                    t_out  := str.length(str.trim(cols.get(5))) > 0 ? f_parse_timestamp(cols.get(5)) : na
                    p_out  := cols.size() >= 7 and str.length(str.trim(cols.get(6))) > 0 ? nz(f_clean_num(cols.get(6)), 0.0) : 0.0
                    p_sl   := cols.size() >= 8 and str.length(str.trim(cols.get(7))) > 0 ? nz(f_clean_num(cols.get(7)), 0.0) : 0.0
                    t_size := cols.size() >= 9 and str.length(str.trim(cols.get(8))) > 0 ? math.max(nz(f_clean_num(cols.get(8)), 1.0), 0.0001) : 1.0
                else
                    // Companion Spreadsheet Columns A-L layout: Ticket | Sym | Side | EntryDT | Price | Qty | SL | TP | ExitDT | [EmptyTime] | ExitPx
                    t_size := cols.size() >= 6 and str.length(str.trim(cols.get(5))) > 0 ? math.max(nz(f_clean_num(cols.get(5)), 1.0), 0.0001) : 1.0
                    p_sl   := cols.size() >= 7 and str.length(str.trim(cols.get(6))) > 0 ? nz(f_clean_num(cols.get(6)), 0.0) : 0.0
                    p_tp   := cols.size() >= 8 and str.length(str.trim(cols.get(7))) > 0 ? nz(f_clean_num(cols.get(7)), 0.0) : 0.0
                    if cols.size() >= 9
                        for ex_i = 8 to math.min(cols.size() - 1, 11)
                            string ex_v = str.trim(cols.get(ex_i))
                            if str.length(ex_v) > 0
                                if str.contains(ex_v, "-") or str.contains(ex_v, "/") or str.contains(ex_v, ":")
                                    if na(t_out)
                                        t_out := f_parse_timestamp(ex_v)
                                else
                                    float ep = f_clean_num(ex_v)
                                    if not na(ep) and ep > 0.0 and p_out == 0.0
                                        p_out := ep
            else
                if f_is_dir_token(c0)
                    t_dir  := (str.upper(c0) == "S" or str.upper(c0) == "SHORT" or str.upper(c0) == "SELL") ? "SHORT" : "LONG"
                    t_in   := cols.size() >= 2 and (str.contains(c1, ":") or str.contains(c1, "-") or str.contains(c1, "/")) ? nz(f_parse_timestamp(c1), max_bar_t) : max_bar_t
                    p_in   := cols.size() >= 3 ? nz(f_clean_num(cols.get(2)), 0.0) : (cols.size() >= 2 and na(f_parse_timestamp(c1)) ? nz(f_clean_num(c1), 0.0) : 0.0)
                    t_size := cols.size() >= 4 and str.length(str.trim(cols.get(3))) > 0 ? math.max(nz(f_clean_num(cols.get(3)), 1.0), 0.0001) : 1.0
                    p_sl   := cols.size() >= 5 and str.length(str.trim(cols.get(4))) > 0 ? nz(f_clean_num(cols.get(4)), 0.0) : 0.0
                    p_tp   := cols.size() >= 6 and str.length(str.trim(cols.get(5))) > 0 ? nz(f_clean_num(cols.get(5)), 0.0) : 0.0
                    t_out  := cols.size() >= 7 and str.length(str.trim(cols.get(6))) > 0 ? f_parse_timestamp(cols.get(6)) : na
                    p_out  := cols.size() >= 8 and str.length(str.trim(cols.get(7))) > 0 ? nz(f_clean_num(cols.get(7)), 0.0) : 0.0
                else
                    if not f_is_currency_token(c0)
                        t_sym := str.upper(c0)
                    t_dir  := (str.upper(c1) == "S" or str.upper(c1) == "SHORT" or str.upper(c1) == "SELL") ? "SHORT" : "LONG"
                    t_in   := cols.size() >= 3 and (str.contains(c2, ":") or str.contains(c2, "-") or str.contains(c2, "/")) ? nz(f_parse_timestamp(c2), max_bar_t) : max_bar_t
                    p_in   := cols.size() >= 4 ? nz(f_clean_num(cols.get(3)), 0.0) : (cols.size() >= 3 and na(f_parse_timestamp(c2)) ? nz(f_clean_num(c2), 0.0) : 0.0)
                    t_size := cols.size() >= 5 and str.length(str.trim(cols.get(4))) > 0 ? math.max(nz(f_clean_num(cols.get(4)), 1.0), 0.0001) : 1.0
                    p_sl   := cols.size() >= 6 and str.length(str.trim(cols.get(5))) > 0 ? nz(f_clean_num(cols.get(5)), 0.0) : 0.0
                    p_tp   := cols.size() >= 7 and str.length(str.trim(cols.get(6))) > 0 ? nz(f_clean_num(cols.get(6)), 0.0) : 0.0
                    t_out  := cols.size() >= 8 and str.length(str.trim(cols.get(7))) > 0 ? f_parse_timestamp(cols.get(7)) : na
                    p_out  := cols.size() >= 9 and str.length(str.trim(cols.get(8))) > 0 ? nz(f_clean_num(cols.get(8)), 0.0) : 0.0
    else
        array<string> raw_tokens = str.split(entry_seg, " ")
        array<string> tokens = array.new<string>()
        for r_tok in raw_tokens
            string r_tk = str.trim(r_tok)
            if str.length(r_tk) > 0 and r_tk != "@"
                tokens.push(r_tk)
 
        int start_idx = 0
        int t_in_date = na
        bool sym_assigned = false
 
        if tokens.size() >= 3 and not na(f_clean_num(tokens.get(0))) and f_is_dir_token(tokens.get(2))
            t_id            := int(nz(f_clean_num(tokens.get(0)), default_id))
            has_explicit_id := true
            t_sym           := str.upper(tokens.get(1))
            string d_tok    = str.upper(tokens.get(2))
            t_dir           := (d_tok == "S" or d_tok == "SHORT" or d_tok == "SELL") ? "SHORT" : "LONG"
            start_idx       := 3
            sym_assigned    := true
        else if tokens.size() >= 2 and f_is_dir_token(tokens.get(1)) and not f_is_dir_token(tokens.get(0)) and na(f_clean_num(tokens.get(0)))
            t_sym        := str.upper(tokens.get(0))
            string d_tok = str.upper(tokens.get(1))
            t_dir        := (d_tok == "S" or d_tok == "SHORT" or d_tok == "SELL") ? "SHORT" : "LONG"
            start_idx    := 2
            sym_assigned := true
        else if tokens.size() >= 1 and f_is_dir_token(tokens.get(0))
            string d_tok = str.upper(tokens.get(0))
            t_dir        := (d_tok == "S" or d_tok == "SHORT" or d_tok == "SELL") ? "SHORT" : "LONG"
            start_idx    := 1
            if tokens.size() >= 2
                string tok1 = tokens.get(1)
                string u1   = str.upper(tok1)
                bool is_dt  = str.contains(tok1, ":") or str.contains(tok1, "-") or str.contains(tok1, "/")
                bool is_num = not na(f_clean_num(tok1))
                bool is_kv  = str.contains(tok1, "=") or str.contains(tok1, ":")
                if not is_num and not is_dt and not is_kv and not f_is_currency_token(u1) and not f_is_dir_token(u1)
                    t_sym        := u1
                    start_idx    := 2
                    sym_assigned := true
 
        int tok_i = start_idx
        while tok_i < tokens.size()
            string tk = tokens.get(tok_i)
            string tu = str.upper(tk)
            if f_is_dir_token(tu)
                t_dir := (tu == "S" or tu == "SHORT" or tu == "SELL") ? "SHORT" : "LONG"
            else if str.startswith(tu, "ID=") or str.startswith(tu, "TICKET=") or str.startswith(tu, "ID:") or str.startswith(tu, "TICKET:")
                string clean_val = str.replace_all(str.replace_all(tu, "ID=", ""), "TICKET=", "")
                clean_val := str.replace_all(str.replace_all(clean_val, "ID:", ""), "TICKET:", "")
                t_id := int(nz(f_clean_num(clean_val), default_id))
                has_explicit_id := true
            else if str.startswith(tu, "QTY=") or str.startswith(tu, "SIZE=") or str.startswith(tu, "QTY:") or str.startswith(tu, "SIZE:")
                string clean_val = str.replace_all(str.replace_all(tu, "QTY=", ""), "SIZE=", "")
                clean_val := str.replace_all(str.replace_all(clean_val, "QTY:", ""), "SIZE:", "")
                t_size := math.max(nz(f_clean_num(clean_val), 1.0), 0.0001)
            else if str.startswith(tu, "SL=") or str.startswith(tu, "SL:")
                string clean_val = str.replace_all(str.replace_all(tu, "SL=", ""), "SL:", "")
                p_sl := nz(f_clean_num(clean_val), 0.0)
            else if str.startswith(tu, "TP=") or str.startswith(tu, "TP:")
                string clean_val = str.replace_all(str.replace_all(tu, "TP=", ""), "TP:", "")
                p_tp := nz(f_clean_num(clean_val), 0.0)
            else if str.startswith(tu, "CURR=") or str.startswith(tu, "CCY=") or str.startswith(tu, "CURRENCY=") or str.startswith(tu, "CURR:") or str.startswith(tu, "CCY:") or str.startswith(tu, "CURRENCY:")
                string clean_val = str.replace_all(str.replace_all(str.replace_all(tu, "CURRENCY=", ""), "CURR=", ""), "CCY=", "")
                clean_val := str.replace_all(str.replace_all(str.replace_all(clean_val, "CURRENCY:", ""), "CURR:", ""), "CCY:", "")
                t_curr := clean_val
            else if str.startswith(tu, "SYM=") or str.startswith(tu, "SYMBOL=") or str.startswith(tu, "TICKER=") or str.startswith(tu, "SYM:") or str.startswith(tu, "SYMBOL:") or str.startswith(tu, "TICKER:")
                string clean_val = str.replace_all(str.replace_all(str.replace_all(tu, "SYMBOL=", ""), "SYM=", ""), "TICKER=", "")
                clean_val := str.replace_all(str.replace_all(str.replace_all(clean_val, "SYMBOL:", ""), "SYM:", ""), "TICKER:", "")
                t_sym := clean_val
                sym_assigned := true
            else if f_is_currency_token(tu)
                t_curr := tu
            else if str.contains(tk, ":") or str.contains(tk, "-") or str.contains(tk, "/")
                string dt_tk = tk
                if tok_i + 1 < tokens.size()
                    string nxt_u = str.upper(tokens.get(tok_i + 1))
                    if nxt_u == "AM" or nxt_u == "PM"
                        dt_tk  += " " + nxt_u
                        tok_i  += 1
                int parsed_t = f_parse_timestamp(dt_tk)
                if not na(parsed_t)
                    string u_dt_tk = str.upper(dt_tk)
                    bool is_time_tok = str.contains(dt_tk, ":") and not str.contains(dt_tk, "-") and not str.contains(dt_tk, "/")
                    if is_time_tok and not na(t_in_date)
                        bool tk_pm = str.contains(u_dt_tk, "PM")
                        bool tk_am = str.contains(u_dt_tk, "AM")
                        string clean_tm = str.trim(str.replace_all(str.replace_all(u_dt_tk, "PM", ""), "AM", ""))
                        array<string> tp = str.split(clean_tm, ":")
                        int hr = int(nz(str.tonumber(tp.get(0)), 0))
                        int mn = tp.size() >= 2 ? int(nz(str.tonumber(tp.get(1)), 0)) : 0
                        int sc = tp.size() >= 3 ? int(nz(str.tonumber(tp.get(2)), 0)) : 0
                        if tk_pm and hr < 12
                            hr += 12
                        else if tk_am and hr == 12
                            hr := 0
                        [d_yr, d_mo, d_dy] = f_extract_ymd(t_in_date)
                        int combined_in = f_build_ts(d_yr, d_mo, d_dy, hr, mn, sc)
                        t_in := combined_in > max_bar_t ? max_bar_t : combined_in
                    else
                        t_in := parsed_t
                        if str.contains(dt_tk, "-") or str.contains(dt_tk, "/")
                            t_in_date := parsed_t
            else
                float n = f_clean_num(tk)
                if not na(n) and n > 0.0 and p_in == 0.0
                    p_in := n
                else if na(n) and not sym_assigned and str.length(tk) >= 2 and not f_is_currency_token(tu)
                    t_sym := tu
                    sym_assigned := true
            tok_i += 1
 
    int t_out_date = na
    if str.length(exit_seg) > 0
        string norm_exit_seg = str.replace_all(exit_seg, "\t", " ")
        array<string> raw_ex_toks = str.split(norm_exit_seg, " ")
        array<string> ex_toks = array.new<string>()
        for r_et in raw_ex_toks
            string cet = str.trim(r_et)
            if str.length(cet) > 0 and cet != "@"
                ex_toks.push(cet)
        int ex_i = 0
        while ex_i < ex_toks.size()
            string et = ex_toks.get(ex_i)
            if str.contains(et, ":") or str.contains(et, "-") or str.contains(et, "/")
                string dt_et = et
                if ex_i + 1 < ex_toks.size()
                    string nxt_eu = str.upper(ex_toks.get(ex_i + 1))
                    if nxt_eu == "AM" or nxt_eu == "PM"
                        dt_et += " " + nxt_eu
                        ex_i  += 1
                int parsed_e = f_parse_timestamp(dt_et)
                if not na(parsed_e)
                    string u_dt_et = str.upper(dt_et)
                    bool is_et_time = str.contains(dt_et, ":") and not str.contains(dt_et, "-") and not str.contains(dt_et, "/")
                    if is_et_time and not na(t_out_date)
                        bool et_pm = str.contains(u_dt_et, "PM")
                        bool et_am = str.contains(u_dt_et, "AM")
                        string clean_etm = str.trim(str.replace_all(str.replace_all(u_dt_et, "PM", ""), "AM", ""))
                        array<string> tp = str.split(clean_etm, ":")
                        int hr = int(nz(str.tonumber(tp.get(0)), 0))
                        int mn = tp.size() >= 2 ? int(nz(str.tonumber(tp.get(1)), 0)) : 0
                        int sc = tp.size() >= 3 ? int(nz(str.tonumber(tp.get(2)), 0)) : 0
                        if et_pm and hr < 12
                            hr += 12
                        else if et_am and hr == 12
                            hr := 0
                        [o_yr, o_mo, o_dy] = f_extract_ymd(t_out_date)
                        int combined_out = f_build_ts(o_yr, o_mo, o_dy, hr, mn, sc)
                        t_out := combined_out > max_bar_t ? max_bar_t : combined_out
                    else
                        t_out := parsed_e
                        if str.contains(dt_et, "-") or str.contains(dt_et, "/")
                            t_out_date := parsed_e
            else
                float ep = f_clean_num(et)
                if not na(ep) and ep > 0.0 and p_out == 0.0
                    p_out := ep
            ex_i += 1
 
    if p_out > 0.0 and na(t_out)
        t_out := max_bar_t
 
    bool is_valid  = p_in > 0.0
    bool is_closed = is_valid and p_out > 0.0 and not na(t_out)
    [is_valid, is_closed, t_id, t_sym, t_dir, t_in, p_in, t_size, p_sl, p_tp, t_out, p_out, t_curr, has_explicit_id]
 
// ===========================================================================================================
// SECTION 06: CORE MATHEMATICAL ENGINE & UNIFIED LEDGER PARSER
// ===========================================================================================================
var bool            is_ledger_ingested     = false
var bool            is_closed_boxes_drawn  = false
var bool            is_closed_labels_drawn = false
var bool            is_closed_pins_drawn   = false
var array<DCAEntry> cached_open_entries    = array.new<DCAEntry>()
var array<DCAEntry> cached_live_entries    = array.new<DCAEntry>()
var array<Trade>    cached_all_closed      = array.new<Trade>()
var array<Trade>    cached_chart_closed    = array.new<Trade>()
var array<string>   parse_error_log        = array.new<string>()
var string          cached_live_sym        = syminfo.ticker
var string          cached_live_dir        = "LONG"
var float           cached_live_sl         = 0.0
var float           cached_live_tp         = 0.0
var int             skipped_rows_count     = 0
 
if barstate.islastconfirmedhistory or barstate.islast
    if not is_ledger_ingested
        cached_open_entries.clear()
        cached_live_entries.clear()
        cached_all_closed.clear()
        cached_chart_closed.clear()
        parse_error_log.clear()
        skipped_rows_count := 0
        cached_live_sym    := syminfo.ticker
        cached_live_dir    := "LONG"
        cached_live_sl     := 0.0
        cached_live_tp     := 0.0
 
        // Unified Single-Pass Ingestion Pass
        string merged_ledger = i_trade_ledger
 
        if str.length(str.trim(merged_ledger)) > 0
            array<string> rows = str.split(merged_ledger, "\n")
            int line_idx = 0
            while line_idx < rows.size()
                string row_str = str.trim(rows.get(line_idx))
                if str.length(row_str) > 0 and not str.startswith(row_str, "#") and not str.startswith(row_str, "//")
                    [is_v, is_c, t_id, t_sym, t_dir, t_in, p_in, t_size, p_sl, p_tp, t_out, p_out, t_curr, has_exp_id] = f_parse_universal_row(row_str, cached_open_entries.size() + cached_all_closed.size() + 1)
                    if is_v
                        string norm_dir = (t_dir == "S" or t_dir == "SHORT" or t_dir == "SELL") ? "SHORT" : "LONG"
                        string clean_s  = str.length(str.trim(t_sym)) > 0 ? f_strip_exchange(t_sym) : syminfo.ticker
                        string curr_s   = t_curr != "" ? t_curr : f_detect_symbol_currency(t_sym, p_in)
                        if is_c
                            Trade matched_tr = na
                            if has_exp_id and cached_all_closed.size() > 0
                                for c_tr in cached_all_closed
                                    if c_tr.has_explicit_id and c_tr.id == t_id and c_tr.symbol == clean_s and c_tr.direction == norm_dir
                                        matched_tr := c_tr
                                        break
                            if not na(matched_tr)
                                float safe_qty = math.max(nz(t_size, 1.0), 0.0001)
                                matched_tr.entries.push(DCAEntry.new(t_in, p_in, safe_qty, t_id, clean_s, norm_dir, p_out, true, curr_s, p_sl, true))
                                if na(matched_tr.time_exit) or t_out >= matched_tr.time_exit
                                    matched_tr.time_exit  := t_out
                                    matched_tr.exit_price := p_out
                                if p_sl > 0.0
                                    matched_tr.sl_price := p_sl
                                matched_tr.finalize()
                            else
                                Trade built = f_build_closed_trade(t_id, t_sym, t_dir, t_in, p_in, t_out, p_out, p_sl, t_size, t_curr, has_exp_id)
                                cached_all_closed.push(built)
                                if f_symbol_matches_chart(t_sym)
                                    cached_chart_closed.push(built)
                        else
                            [init_px, has_fd] = f_resolve_live_price_with_status(t_sym, p_in)
                            DCAEntry ent      = DCAEntry.new(t_in, p_in, t_size, t_id, clean_s, norm_dir, init_px, has_fd, curr_s, p_sl, has_exp_id)
                            cached_open_entries.push(ent)
                            if f_symbol_matches_chart(t_sym)
                                cached_live_entries.push(ent)
                                cached_live_sym := clean_s
                                cached_live_dir := norm_dir
                                if p_sl > 0.0
                                    cached_live_sl := p_sl
                                if p_tp > 0.0
                                    cached_live_tp := p_tp
                    else
                        skipped_rows_count += 1
                        string err_snip = str.length(row_str) > 28 ? str.substring(row_str, 0, 25) + "…" : row_str
                        parse_error_log.push("L" + str.tostring(line_idx + 1) + ": " + err_snip)
                line_idx += 1
 
        is_ledger_ingested := true
 
    if not i_show_closed_boxes
        if closed_boxes.size() > 0
            f_clear_boxes(closed_boxes)
        if closed_lines.size() > 0
            f_clear_lines(closed_lines)
        is_closed_boxes_drawn := false
    if not i_show_closed_labels
        if closed_labels.size() > 0
            f_clear_labels(closed_labels)
        is_closed_labels_drawn := false
    if not i_show_trade_markers
        if closed_entry_pins.size() > 0
            f_clear_labels(closed_entry_pins)
        is_closed_pins_drawn := false
 
    bool need_boxes  = i_show_closed_boxes  and not is_closed_boxes_drawn
    bool need_labels = i_show_closed_labels and not is_closed_labels_drawn
    bool need_c_pins = i_show_trade_markers and not is_closed_pins_drawn
    if need_boxes or need_labels or need_c_pins
        if need_boxes
            f_clear_boxes(closed_boxes)
            f_clear_lines(closed_lines)
        if need_labels
            f_clear_labels(closed_labels)
        if need_c_pins
            f_clear_labels(closed_entry_pins)
        int total_c      = cached_chart_closed.size()
        int start_idx    = math.max(0, total_c - i_max_trades_visualized)
        int min_bar_span = math.max(nz(timeframe.in_seconds(timeframe.period), 60) * 1000, 1000)
        bool is_compact  = i_dca_marker_style == "Compact Pin"
        if total_c > 0 and start_idx < total_c
            for i = start_idx to total_c - 1
                Trade tr        = cached_chart_closed.get(i)
                float avg_entry = tr.get_vwap()
                int   time_in   = tr.get_first_entry_time()
                int   time_out  = tr.time_exit
                if not na(avg_entry) and not na(time_in) and not na(time_out)
                    bool  is_win     = tr.realized_pnl_pct >= 0.0
                    color base_col   = is_win ? i_c_win : i_c_loss
                    color fill_col   = color.new(base_col, i_box_fill_transp)
                    color border_col = color.new(base_col, i_box_bdr_transp)
                    float raw_top    = math.max(avg_entry, tr.exit_price)
                    float raw_bot    = math.min(avg_entry, tr.exit_price)
                    float min_h      = syminfo.mintick * 4.0
                    float mid_p      = (raw_top + raw_bot) * 0.5
                    float box_top    = (raw_top - raw_bot) < min_h ? (mid_p + min_h * 0.5) : raw_top
                    float box_bot    = (raw_top - raw_bot) < min_h ? (mid_p - min_h * 0.5) : raw_bot
                    int   plot_in    = math.min(time_in, time)
                    int   plot_out   = math.min(time_out, time)
                    int   raw_left   = math.min(plot_in, plot_out)
                    int   raw_right  = math.max(plot_in, plot_out)
                    int   box_right  = (raw_right - raw_left) < min_bar_span ? (raw_left + min_bar_span) : raw_right
 
                    string r_txt   = not na(tr.realized_r_multiple) ? " (" + str.tostring(tr.realized_r_multiple, "#.##") + "R)" : ""
                    string sign    = tr.realized_pnl_pct >= 0.0 ? "+" : ""
                    string b_txt   = "#" + str.tostring(tr.id, "00") + " " + tr.symbol + " " + sign + str.tostring(tr.realized_pnl_pct, "#.##") + "%"
                    string box_tip = "CLOSED TRADE #" + str.tostring(tr.id, "00") + " (" + tr.symbol + " " + tr.direction + ")\n• Entry Time: " + f_format_ts(time_in) + "\n• Exit Time: " + f_format_ts(time_out) + "\n• Size: " + str.tostring(tr.get_total_size(), "#.##") + "\n• Entry VWAP: " + str.tostring(avg_entry, format.mintick) + "\n• Exit Price: " + str.tostring(tr.exit_price, format.mintick) + "\n• Realized Return: " + sign + str.tostring(tr.realized_pnl_pct, "#.##") + "%" + r_txt
 
                    if need_boxes
                        box trade_box = box.new(
                             left         = raw_left,
                             top          = box_top,
                             right        = box_right,
                             bottom       = box_bot,
                             border_color = border_col,
                             border_width = 1,
                             border_style = line.style_solid,
                             bgcolor      = fill_col,
                             xloc         = xloc.bar_time
                         )
                        f_enqueue_box(closed_boxes, trade_box, i_max_trades_visualized)
                        if i_show_box_connector
                            int conn_x2 = plot_out <= plot_in ? box_right : plot_out
                            line conn_ln = line.new(
                                 x1    = plot_in,
                                 y1    = avg_entry,
                                 x2    = conn_x2,
                                 y2    = tr.exit_price,
                                 xloc  = xloc.bar_time,
                                 color = border_col,
                                 style = line.style_dashed,
                                 width = 1
                             )
                            f_enqueue_line(closed_lines, conn_ln, i_max_trades_visualized)
 
                    if need_labels
                        label exit_badge = label.new(
                             x         = raw_right,
                             y         = tr.exit_price,
                             text      = is_compact ? "" : b_txt,
                             tooltip   = box_tip,
                             xloc      = xloc.bar_time,
                             color     = base_col,
                             textcolor = f_badge_text_color(base_col, i_c_hud_txt),
                             style     = is_compact ? label.style_circle : (tr.exit_price >= avg_entry ? label.style_label_down : label.style_label_up),
                             size      = size.tiny
                         )
                        f_enqueue_label(closed_labels, exit_badge, i_max_trades_visualized)
 
                    if need_c_pins and tr.entries.size() > 0
                        for c_ent in tr.entries
                            int   c_t      = nz(c_ent.time_in, time_in)
                            int   c_plot_t = math.min(c_t, time)
                            float c_p      = c_ent.price
                            string c_q     = c_ent.size == math.floor(c_ent.size) ? str.tostring(c_ent.size, "#") : str.tostring(c_ent.size, "#.##")
                            string c_tid   = "#" + str.tostring(tr.id)
                            string c_full  = c_tid + " (" + c_q + ") @ " + str.tostring(c_p, format.mintick)
                            string c_tp    = "CLOSED FILL " + c_tid + " (" + tr.symbol + " " + tr.direction + ")\n• Fill Time: " + f_format_ts(c_t) + "\n• Entry Price: " + str.tostring(c_p, format.mintick) + "\n• Size / Qty: " + c_q + "\n• Trade Outcome: " + sign + str.tostring(tr.realized_pnl_pct, "#.##") + "%" + r_txt
                            label c_pin = label.new(
                                 x         = c_plot_t,
                                 y         = c_p,
                                 text      = is_compact ? "" : c_full,
                                 tooltip   = c_tp,
                                 xloc      = xloc.bar_time,
                                 color     = base_col,
                                 textcolor = f_badge_text_color(base_col, i_c_hud_txt),
                                 style     = is_compact ? (tr.direction == "LONG" ? label.style_triangleup : label.style_triangledown) : label.style_label_right,
                                 size      = size.tiny
                             )
                            f_enqueue_label(closed_entry_pins, c_pin, 200)
        if need_boxes
            is_closed_boxes_drawn := true
        if need_labels
            is_closed_labels_drawn := true
        if need_c_pins
            is_closed_pins_drawn := true
 
// ===========================================================================================================
// SECTION 07: REAL-TIME TICK VALUATION & PERSISTENT PROJECTION GRAPHICS
// ===========================================================================================================
AccountMetrics metrics = AccountMetrics.new()
float global_open_cost = 0.0
float global_open_diff = 0.0
float global_open_ret_pct = 0.0
float scoped_open_cost = 0.0
int   unmapped_feed_count = 0
bool  is_global_scope = i_hud_scope == "Global Portfolio (All Symbols)"
Trade active_trade = na
 
if barstate.islast
    for ent in cached_open_entries
        [cur_px, has_fd] = f_resolve_live_price_with_status(ent.symbol, ent.price)
        ent.live_price    := cur_px
        ent.has_live_feed := has_fd
        if not has_fd
            unmapped_feed_count += 1
 
    array<DCAEntry> live_entries        = cached_live_entries
    array<DCAEntry> all_open_entries    = cached_open_entries
    array<Trade>    all_closed_trades   = cached_all_closed
    array<Trade>    chart_closed_trades = cached_chart_closed
 
    active_trade := Trade.new(
         id                  = 101,
         symbol              = cached_live_sym,
         direction           = cached_live_dir,
         status              = live_entries.size() > 0 ? "OPEN" : "FLAT",
         entries             = live_entries,
         sl_price            = cached_live_sl,
         tp_price            = cached_live_tp,
         time_exit           = na,
         exit_price          = na,
         realized_pnl_pct    = 0.0,
         realized_r_multiple = na
     ).finalize()
 
    array<Trade>    scoped_trades = is_global_scope ? all_closed_trades : chart_closed_trades
    array<DCAEntry> scoped_open   = is_global_scope ? all_open_entries  : live_entries
    int   r_count = 0
    float r_sum   = 0.0
 
    for g_ent in all_open_entries
        float fx_m   = f_fx_multiplier(g_ent.currency, i_account_currency)
        float g_cur  = nz(g_ent.live_price, g_ent.price)
        float g_diff = g_ent.direction == "LONG" ? (g_cur - g_ent.price) : (g_ent.price - g_cur)
        global_open_cost += (g_ent.price * g_ent.size) * fx_m
        global_open_diff += (g_diff * g_ent.size) * fx_m
    global_open_ret_pct := global_open_cost > 0.0 ? (global_open_diff / global_open_cost) * 100.0 : 0.0
 
    for s_ent in scoped_open
        float s_fx   = f_fx_multiplier(s_ent.currency, i_account_currency)
        scoped_open_cost += (s_ent.price * s_ent.size) * s_fx
        float eff_sl = s_ent.sl_price > 0.0 ? s_ent.sl_price : (f_symbol_matches_chart(s_ent.symbol) ? cached_live_sl : 0.0)
        if eff_sl > 0.0
            float sl_dist = s_ent.direction == "LONG" ? math.max(s_ent.price - eff_sl, 0.0) : math.max(eff_sl - s_ent.price, 0.0)
            metrics.portfolio_open_risk += (sl_dist * s_ent.size) * s_fx
            metrics.risk_open_count     += 1
 
    float sum_win_pct  = 0.0
    float sum_loss_pct = 0.0
 
    if scoped_trades.size() > 0
        for tr in scoped_trades
            metrics.total_trades += 1
            float tr_vwap = nz(tr.get_vwap(), 0.0)
            float tr_qty  = tr.get_total_size()
            string tr_cur = tr.entries.size() > 0 ? tr.entries.get(0).currency : f_detect_symbol_currency(tr.symbol, tr_vwap)
            float fx_m    = f_fx_multiplier(tr_cur, i_account_currency)
            float tr_cost = (tr_vwap * tr_qty) * fx_m
            float tr_diff = (tr.direction == "LONG" ? (tr.exit_price - tr_vwap) : (tr_vwap - tr.exit_price)) * tr_qty * fx_m
            metrics.total_basis_val += tr_cost
 
            if tr.realized_pnl_pct > 1e-5
                metrics.win_count        += 1
                sum_win_pct              += tr.realized_pnl_pct
                metrics.gross_profit_val += math.max(tr_diff, 0.0)
            else if tr.realized_pnl_pct < -1e-5
                metrics.loss_count     += 1
                sum_loss_pct           += math.abs(tr.realized_pnl_pct)
                metrics.gross_loss_val += math.abs(math.min(tr_diff, 0.0))
            else
                metrics.breakeven_count += 1
 
            if not na(tr.realized_r_multiple)
                r_count += 1
                r_sum   += tr.realized_r_multiple
    else if scoped_open.size() > 0
        for ent in scoped_open
            metrics.total_trades += 1
            float cur_px  = nz(ent.live_price, ent.price)
            float t_pnl   = ent.direction == "LONG" ? ((cur_px - ent.price) / ent.price) * 100.0 : ((ent.price - cur_px) / ent.price) * 100.0
            float fx_m    = f_fx_multiplier(ent.currency, i_account_currency)
            float ent_cst = (ent.price * ent.size) * fx_m
            float ent_dif = (ent.direction == "LONG" ? (cur_px - ent.price) : (ent.price - cur_px)) * ent.size * fx_m
            metrics.total_basis_val += ent_cst
 
            if t_pnl > 1e-5
                metrics.win_count        += 1
                sum_win_pct              += t_pnl
                metrics.gross_profit_val += math.max(ent_dif, 0.0)
            else if t_pnl < -1e-5
                metrics.loss_count     += 1
                sum_loss_pct           += math.abs(t_pnl)
                metrics.gross_loss_val += math.abs(math.min(ent_dif, 0.0))
            else
                metrics.breakeven_count += 1
 
    if metrics.total_basis_val > 0.0
        metrics.gross_profit_pct := (metrics.gross_profit_val / metrics.total_basis_val) * 100.0
        metrics.gross_loss_pct   := (metrics.gross_loss_val   / metrics.total_basis_val) * 100.0
 
    if metrics.total_trades > 0
        metrics.win_rate     := (float(metrics.win_count) / float(metrics.total_trades)) * 100.0
        metrics.avg_win_pct  := metrics.win_count > 0 ? (sum_win_pct / float(metrics.win_count)) : 0.0
        metrics.avg_loss_pct := metrics.loss_count > 0 ? (sum_loss_pct / float(metrics.loss_count)) : 0.0
        float p_win          = float(metrics.win_count) / float(metrics.total_trades)
        float p_loss         = float(metrics.loss_count) / float(metrics.total_trades)
        metrics.expectancy   := (p_win * metrics.avg_win_pct) - (p_loss * metrics.avg_loss_pct)
 
    metrics.profit_factor := metrics.gross_loss_val > 0.0 ? (metrics.gross_profit_val / metrics.gross_loss_val) : (metrics.gross_profit_val > 0.0 ? 99.99 : 0.0)
    metrics.avg_r_multiple := r_count > 0 ? (r_sum / float(r_count)) : 0.0
    metrics.r_trades_count := r_count
 
    float net_realized_dlr = metrics.gross_profit_val - metrics.gross_loss_val
    metrics.dollar_expectancy := metrics.total_trades > 0 ? (net_realized_dlr / float(metrics.total_trades)) : 0.0
 
    bool  is_live_open = active_trade.status == "OPEN" and active_trade.get_total_size() > 0.0
    float live_vwap    = is_live_open ? active_trade.get_vwap() : na
    float live_pnl_pct = is_live_open ? active_trade.calculate_unrealized_pnl(close) : 0.0
    float live_qty     = is_live_open ? active_trade.get_total_size() : 0.0
 
    // Persistent In-Place Mutation of Graphics (Zero GC Churn)
    if is_live_open and not na(live_vwap)
        int fallback_t   = time[math.min(bar_index, 50)]
        int first_fill_t = active_trade.get_first_entry_time()
        int ray_start_t  = not na(first_fill_t) ? math.min(first_fill_t, time) : fallback_t
        color vwap_badge_col = live_pnl_pct >= 0.0 ? i_c_win : i_c_loss
 
        // 1. Mutate VWAP Master Ray (1pt thin, stops at the label)
        line.set_xy1(vwap_ray, ray_start_t, live_vwap)
        line.set_xy2(vwap_ray, time,        live_vwap)
        line.set_color(vwap_ray, vwap_badge_col)
        line.set_width(vwap_ray, 1)
        line.set_extend(vwap_ray, extend.none)
 
        // 2. Mutate SL Ray
        string stop_dist_str = " | SL: N/A"
        if active_trade.sl_price > 0.0
            float sl_dist_pct = ((close - active_trade.sl_price) / close) * 100.0
            stop_dist_str := " | Dist SL: " + str.tostring(math.abs(sl_dist_pct), "#.##") + "%"
            line.set_xy1(sl_ray, ray_start_t, active_trade.sl_price)
            line.set_xy2(sl_ray, time,        active_trade.sl_price)
            line.set_color(sl_ray, i_c_loss)
            line.set_extend(sl_ray, extend.right)
        else
            line.set_extend(sl_ray, extend.none)
            line.set_xy1(sl_ray, na, na)
            line.set_xy2(sl_ray, na, na)
 
        // 3. Mutate TP Ray
        if active_trade.tp_price > 0.0
            line.set_xy1(tp_ray, ray_start_t, active_trade.tp_price)
            line.set_xy2(tp_ray, time,        active_trade.tp_price)
            line.set_color(tp_ray, i_c_tp)
            line.set_extend(tp_ray, extend.right)
        else
            line.set_extend(tp_ray, extend.none)
            line.set_xy1(tp_ray, na, na)
            line.set_xy2(tp_ray, na, na)
 
        // 4. Mutate VWAP Master Badge (Clean - No SL data)
        string pnl_sign  = live_pnl_pct >= 0.0 ? "+" : ""
        string badge_str = "VWAP (" + str.tostring(live_entries.size()) + "x) " + str.tostring(live_vwap, format.mintick) + " | " + pnl_sign + str.tostring(live_pnl_pct, "#.##") + "%"
        string vwap_tip  = "MASTER VWAP COST BASIS (" + active_trade.symbol + ")\n• Active DCA Fills: " + str.tostring(live_entries.size()) + "\n• Total Position Size: " + str.tostring(live_qty, "#.##") + "\n• VWAP Price: " + str.tostring(live_vwap, format.mintick) + "\n• Floating Return: " + pnl_sign + str.tostring(live_pnl_pct, "#.##") + "%"
        label.set_point(live_lbl, chart.point.from_time(time, live_vwap))
        label.set_text(live_lbl, badge_str)
        label.set_tooltip(live_lbl, vwap_tip)
        label.set_color(live_lbl, vwap_badge_col)
        label.set_textcolor(live_lbl, f_badge_text_color(vwap_badge_col, i_c_hud_txt))
 
        // 5. Mutate DCA Individual Entry Pins via Persistent Label Pool
        if i_show_trade_markers
            bool is_compact_pin = i_dca_marker_style == "Compact Pin"
            if live_entries.size() > 0
                for idx = 0 to live_entries.size() - 1
                    DCAEntry ent = live_entries.get(idx)
                    int ent_t    = not na(ent.time_in) ? math.min(ent.time_in, time) : fallback_t
                    float tr_pnl = active_trade.direction == "LONG" ? ((close - ent.price) / ent.price) * 100.0 : ((ent.price - close) / ent.price) * 100.0
                    color tr_col = tr_pnl >= 0.0 ? i_c_win : i_c_loss
                    string t_sgn = tr_pnl >= 0.0 ? "+" : ""
 
                    string tid_s   = ent.ticket_id > 0 ? "#" + str.tostring(ent.ticket_id) : "T" + str.tostring(idx + 1)
                    string qty_s   = ent.size == math.floor(ent.size) ? str.tostring(ent.size, "#") : str.tostring(ent.size, "#.##")
                    string full_s  = tid_s + " (" + qty_s + ") @ " + str.tostring(ent.price, format.mintick)
                    string pin_txt = is_compact_pin ? "" : full_s
                    string pin_stl = is_compact_pin ? (ent.direction == "LONG" ? label.style_triangleup : label.style_triangledown) : label.style_label_right
                    string pin_tip = "OPEN DCA TRADE " + tid_s + " (" + ent.symbol + " " + ent.direction + ")\n• Fill Time: " + f_format_ts(ent.time_in) + "\n• Fill Price: " + str.tostring(ent.price, format.mintick) + "\n• Size / Qty: " + qty_s + "\n• Floating PnL: " + t_sgn + str.tostring(tr_pnl, "#.##") + "%"
 
                    label pool_pin = na
                    if idx < dca_pins_pool.size()
                        pool_pin := dca_pins_pool.get(idx)
                        label.set_point(pool_pin, chart.point.from_time(ent_t, ent.price))
                        label.set_text(pool_pin, pin_txt)
                        label.set_tooltip(pool_pin, pin_tip)
                        label.set_color(pool_pin, tr_col)
                        label.set_textcolor(pool_pin, f_badge_text_color(tr_col, i_c_hud_txt))
                        label.set_style(pool_pin, pin_stl)
                        label.set_size(pool_pin, size.tiny)
                    else
                        pool_pin := label.new(
                             x         = ent_t,
                             y         = ent.price,
                             text      = pin_txt,
                             tooltip   = pin_tip,
                             xloc      = xloc.bar_time,
                             color     = tr_col,
                             textcolor = f_badge_text_color(tr_col, i_c_hud_txt),
                             style     = pin_stl,
                             size      = size.tiny
                         )
                        dca_pins_pool.push(pool_pin)
 
            // Park excess pool pins off-screen
            if dca_pins_pool.size() > live_entries.size()
                for p_idx = live_entries.size() to dca_pins_pool.size() - 1
                    label.set_point(dca_pins_pool.get(p_idx), chart.point.from_time(na, na))
        else
            if dca_pins_pool.size() > 0
                for p_idx = 0 to dca_pins_pool.size() - 1
                    label.set_point(dca_pins_pool.get(p_idx), chart.point.from_time(na, na))
    else
        // Park all live projection graphics off-screen when flat
        line.set_extend(vwap_ray, extend.none)
        line.set_xy1(vwap_ray, na, na)
        line.set_xy2(vwap_ray, na, na)
        line.set_extend(sl_ray, extend.none)
        line.set_xy1(sl_ray, na, na)
        line.set_xy2(sl_ray, na, na)
        line.set_extend(tp_ray, extend.none)
        line.set_xy1(tp_ray, na, na)
        line.set_xy2(tp_ray, na, na)
        label.set_point(live_lbl, chart.point.from_time(na, na))
        if dca_pins_pool.size() > 0
            for p_idx = 0 to dca_pins_pool.size() - 1
                label.set_point(dca_pins_pool.get(p_idx), chart.point.from_time(na, na))
 
// ===========================================================================================================
// SECTION 08: PRODUCTION HUD MATRIX (MONOSPACE / FIXED COLUMN WIDTHS / ZERO JITTER)
// ===========================================================================================================
if barstate.islast
    if not i_show_hud
        if not na(t_hud)
            table.delete(t_hud)
            t_hud := na
    else
        string tbl_pos = i_hud_pos.to_pos()
        string tbl_sz  = i_hud_size.to_size()
 
        color hud_txt_col  = f_solid(i_c_hud_txt)
        color hud_acc_col  = f_solid(i_c_hud_accent)
        color hud_win_col  = f_solid(i_c_win)
        color hud_loss_col = f_solid(i_c_loss)
        color hud_bdr_col  = f_solid(i_c_hud_border)
        color hud_grid_col = f_with_transp(i_c_hud_border, 45)
 
        float bg_r         = color.r(i_c_hud_bg)
        float bg_g         = color.g(i_c_hud_bg)
        float bg_b         = color.b(i_c_hud_bg)
        color hud_hdr_bg   = f_solid(i_c_hud_hdr)
        color hud_row_odd  = color.rgb(math.max(bg_r, 0.0), math.max(bg_g, 0.0), math.max(bg_b, 0.0), 0)
        color hud_row_even = color.rgb(math.min(bg_r + 10.0, 255.0), math.min(bg_g + 16.0, 255.0), math.min(bg_b + 28.0, 255.0), 0)
 
        // Persistent Table Initialization with Static Merge and Locked Column Widths
        if na(t_hud) or tbl_pos != last_tbl_pos or tbl_sz != last_tbl_sz or i_c_hud_bg != last_hud_bg or i_c_hud_border != last_hud_bdr
            if not na(t_hud)
                table.delete(t_hud)
            t_hud := table.new(
                 position     = tbl_pos,
                 columns      = 3,
                 rows         = 8,
                 bgcolor      = hud_row_odd,
                 border_color = hud_grid_col,
                 border_width = 1,
                 frame_color  = hud_bdr_col,
                 frame_width  = 1
             )
            last_tbl_pos := tbl_pos
            last_tbl_sz  := tbl_sz
            last_hud_bg  := i_c_hud_bg
            last_hud_bdr := i_c_hud_border
 
        // Row 0: Master Header & Ingestion Diagnostics
        bool   is_live_open = not na(active_trade) and active_trade.status == "OPEN" and active_trade.get_total_size() > 0.0
        string err_flag     = skipped_rows_count > 0 ? " ⚠ " + str.tostring(skipped_rows_count) + " ERR" : ""
        string status_str   = "⚪ FLAT (" + syminfo.ticker + ")" + err_flag
        color  status_col   = skipped_rows_count > 0 ? hud_loss_col : hud_acc_col
 
        if is_global_scope and cached_open_entries.size() > 0
            status_str := "🟢 GLOBAL (" + str.tostring(cached_open_entries.size()) + " OPEN)" + err_flag
            status_col := global_open_ret_pct >= 0.0 ? hud_win_col : hud_loss_col
        else if is_live_open
            status_str := (active_trade.direction == "LONG" ? "🟢 LONG (" : "🔴 SHORT (") + active_trade.symbol + ")" + err_flag
            status_col := active_trade.direction == "LONG" ? hud_win_col : hud_loss_col
 
        // Granular Line-by-Line Syntax Error Telemetry in Tooltip
        string err_block = ""
        if parse_error_log.size() > 0
            err_block := "\n• SYNTAX ERRORS (" + str.tostring(parse_error_log.size()) + "):"
            int max_show = math.min(parse_error_log.size(), 6)
            for e = 0 to max_show - 1
                err_block += "\n  ↳ " + parse_error_log.get(e)
            if parse_error_log.size() > 6
                err_block += "\n  ↳ ...and " + str.tostring(parse_error_log.size() - 6) + " more"
 
        string curr_sym      = f_currency_symbol(i_account_currency)
        float  open_heat_pct = scoped_open_cost > 0.0 ? (metrics.portfolio_open_risk / scoped_open_cost) * 100.0 : 0.0
        string heat_line     = "\n• Open Risk at Stop: " + curr_sym + str.tostring(metrics.portfolio_open_risk, "#.##") + " (" + str.tostring(open_heat_pct, "#.##") + "% across " + str.tostring(metrics.risk_open_count) + " fills)"
 
        string hdr_tip = "TIDE TRADER | LEDGER DIAGNOSTICS" +
                         "\n• Ledger Timezone: "         + f_tz_label() +
                         "\n• Open DCA Trades Ingested: " + str.tostring(cached_open_entries.size()) +
                         "\n• Closed Trades Ingested: "   + str.tostring(cached_all_closed.size()) +
                         "\n• Malformed / Skipped Rows: " + str.tostring(skipped_rows_count) +
                         "\n• Unmapped Symbol Feeds: "   + str.tostring(unmapped_feed_count) +
                         "\n• Base Reporting Currency: "  + i_account_currency +
                         heat_line +
                         err_block
 
        table.cell(t_hud, 0, 0, "🌊 Tide Trader | Trade Ledger", text_color=c_bull_sec, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_hdr_bg, tooltip=hdr_tip)
        table.merge_cells(t_hud, 0, 0, 1, 0)
        table.cell(t_hud, 2, 0, status_str, text_color=status_col, text_size=tbl_sz, text_halign=text.align_right, bgcolor=hud_hdr_bg, tooltip=hdr_tip)
 
        // Row 1: Cost Basis | Floating Return | Dollar Delta
        string r1_c0_str = ""
        string r1_c1_str = ""
        string r1_c2_str = ""
        color  r1_col    = hud_txt_col
        float live_vwap  = is_live_open ? active_trade.get_vwap() : na
        float live_pnl_pct = is_live_open ? active_trade.calculate_unrealized_pnl(close) : 0.0
        float live_qty     = is_live_open ? active_trade.get_total_size() : 0.0
 
        if is_global_scope and cached_open_entries.size() > 0
            string g_vwap_s = is_live_open and not na(live_vwap) ? (syminfo.ticker + " VWAP: " + str.tostring(live_vwap, format.mintick)) : (curr_sym + str.tostring(global_open_cost, "#.##"))
            string g_f_sign = global_open_ret_pct > 0.0 ? "+" : ""
            string g_d_sign = global_open_diff > 0.0 ? "+" : ""
            r1_col    := global_open_ret_pct >= 0.0 ? hud_win_col : hud_loss_col
            r1_c0_str := "Portfolio Cost Basis\n" + g_vwap_s
            r1_c1_str := "Global Open Return\n" + g_f_sign + str.tostring(global_open_ret_pct, "#.##") + "%"
            r1_c2_str := "Global Portfolio Δ\n" + g_d_sign + curr_sym + str.tostring(global_open_diff, "#.##") + " (" + str.tostring(cached_open_entries.size()) + "x)"
        else
            string live_curr      = cached_live_entries.size() > 0 ? cached_live_entries.get(0).currency : f_detect_symbol_currency(syminfo.ticker, nz(live_vwap, close))
            float  live_fx_m      = f_fx_multiplier(live_curr, i_account_currency)
            string r1_curr_sym    = f_normalize_base_currency(i_account_currency) == "Native" ? f_currency_symbol(live_curr) : curr_sym
            string vwap_cell_str  = is_live_open and not na(live_vwap) ? str.tostring(live_vwap, format.mintick) : "—"
            string flt_sign       = live_pnl_pct > 0.0 ? "+" : ""
            string flt_cell_str   = is_live_open ? (flt_sign + str.tostring(live_pnl_pct, "#.##") + "%") : "0.00%"
            r1_col                := not is_live_open ? hud_txt_col : (live_pnl_pct >= 0.0 ? hud_win_col : hud_loss_col)
            float  raw_price_diff = is_live_open and not na(live_vwap) ? (active_trade.direction == "LONG" ? (close - live_vwap) : (live_vwap - close)) : 0.0
            float  dollar_delta   = raw_price_diff * live_qty * live_fx_m
            string d_sign         = dollar_delta > 0.0 ? "+" : ""
            string delta_cell_str = is_live_open ? (d_sign + r1_curr_sym + str.tostring(dollar_delta, "#.##")) : (r1_curr_sym + "0.00")
            r1_c0_str := "Cost Basis\n" + vwap_cell_str
            r1_c1_str := "Floating Return\n" + flt_cell_str
            r1_c2_str := "Dollar Δ\n" + delta_cell_str
 
        table.cell(t_hud, 0, 1, r1_c0_str, text_color=hud_txt_col, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_row_odd, text_font_family=font.family_monospace)
        table.cell(t_hud, 1, 1, r1_c1_str, text_color=r1_col,     text_size=tbl_sz, text_halign=text.align_center, bgcolor=hud_row_odd, text_font_family=font.family_monospace)
        table.cell(t_hud, 2, 1, r1_c2_str, text_color=r1_col,     text_size=tbl_sz, text_halign=text.align_right,  bgcolor=hud_row_odd, text_font_family=font.family_monospace)
 
        // Row 2: Win Rate % | Profit Factor | Gross Gain / Loss %
        string scope_lbl = is_global_scope ? " (Global)" : " (" + syminfo.ticker + ")"
        array<Trade> scoped_trades_chk = is_global_scope ? cached_all_closed : cached_chart_closed
        string wr_label  = scoped_trades_chk.size() > 0 ? "Closed Win Rate" : "Open In Profit"
        string be_sfx    = metrics.breakeven_count > 0 ? " [" + str.tostring(metrics.breakeven_count) + " BE]" : ""
        string wr_str    = str.tostring(metrics.win_rate, "#.#") + "% (" + str.tostring(metrics.win_count) + "/" + str.tostring(metrics.total_trades) + ")" + be_sfx
        color  wr_col    = metrics.win_rate >= 50.0 ? hud_win_col : (metrics.total_trades == 0 ? hud_txt_col : hud_loss_col)
        string pf_str    = (metrics.gross_loss_val == 0.0 and metrics.gross_profit_val > 0.0) ? "∞" : str.tostring(metrics.profit_factor, "#.##")
        color  pf_col    = metrics.profit_factor >= 1.5 ? hud_win_col : (metrics.profit_factor >= 1.0 ? hud_acc_col : (metrics.total_trades == 0 ? hud_txt_col : hud_loss_col))
        string gl_str    = "+" + str.tostring(metrics.gross_profit_pct, "#.#") + "% / -" + str.tostring(metrics.gross_loss_pct, "#.#") + "%"
        string basis_lbl = scoped_trades_chk.size() > 0 ? "• Closed Capital Basis: " : "• Open Capital Basis: "
        string gl_tip    = "CAPITAL-WEIGHTED GROSS GAIN / LOSS" + scope_lbl + "\n• Gross Gain (% of Capital): +" + str.tostring(metrics.gross_profit_pct, "#.##") + "% (+" + curr_sym + str.tostring(metrics.gross_profit_val, "#.##") + ")\n• Gross Loss (% of Capital): -" + str.tostring(metrics.gross_loss_pct, "#.##") + "% (-" + curr_sym + str.tostring(metrics.gross_loss_val, "#.##") + ")\n" + basis_lbl + curr_sym + str.tostring(metrics.total_basis_val, "#.##") + "\n• Avg Win / Avg Loss: +" + str.tostring(metrics.avg_win_pct, "#.##") + "% / -" + str.tostring(metrics.avg_loss_pct, "#.##") + "%"
 
        table.cell(t_hud, 0, 2, wr_label + "\n" + wr_str, text_color=wr_col, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_row_even, text_font_family=font.family_monospace)
        table.cell(t_hud, 1, 2, "Profit Factor\n" + pf_str, text_color=pf_col, text_size=tbl_sz, text_halign=text.align_center, bgcolor=hud_row_even, tooltip=gl_tip, text_font_family=font.family_monospace)
        table.cell(t_hud, 2, 2, "Gross Gain / Loss\n" + gl_str, text_color=hud_acc_col, text_size=tbl_sz, text_halign=text.align_right, bgcolor=hud_row_even, tooltip=gl_tip, text_font_family=font.family_monospace)
 
        // Row 3: Active Open Capital | Avg R-Multiple or Avg Win / Loss | Open Positions
        string cap_csym   = (not is_global_scope and f_normalize_base_currency(i_account_currency) == "Native") ? f_currency_symbol(cached_live_entries.size() > 0 ? cached_live_entries.get(0).currency : f_detect_symbol_currency(syminfo.ticker, close)) : curr_sym
        string cap_str    = cap_csym + str.tostring(scoped_open_cost, "#.##")
        string exp_sign   = metrics.expectancy > 0.0 ? "+" : ""
        string d_exp_sign = metrics.dollar_expectancy > 0.0 ? "+" : (metrics.dollar_expectancy < 0.0 ? "-" : "")
        string r_sign     = metrics.avg_r_multiple > 0.0 ? "+" : ""
        string r3_c1_lbl  = (metrics.avg_r_multiple != 0.0) ? ("Avg R (" + str.tostring(metrics.r_trades_count) + "/" + str.tostring(metrics.total_trades) + ")") : "Avg Win / Loss"
        string avg_r_s    = (metrics.avg_r_multiple != 0.0) ? (r_sign + str.tostring(metrics.avg_r_multiple, "#.##") + "R") : ("+" + str.tostring(metrics.avg_win_pct, "#.#") + "% / -" + str.tostring(metrics.avg_loss_pct, "#.#") + "%")
        color  avg_r_c    = (metrics.avg_r_multiple != 0.0) ? (metrics.avg_r_multiple > 0.0 ? hud_win_col : hud_loss_col) : hud_acc_col
        string tr_cnt_s   = is_global_scope ? (str.tostring(cached_open_entries.size()) + " Global | " + str.tostring(cached_live_entries.size()) + " Chart") : (str.tostring(cached_live_entries.size()) + " Chart | " + str.tostring(cached_open_entries.size()) + " Global")
 
        string exp_tip    = "CAPITAL & RISK TELEMETRY" + scope_lbl + "\n• Active Open Capital: " + cap_str + (scoped_trades_chk.size() > 0 ? ("\n• Closed Capital Turnover: " + curr_sym + str.tostring(metrics.total_basis_val, "#.##")) : "") + "\n• Math Expectancy: " + exp_sign + str.tostring(metrics.expectancy, "#.##") + "% (" + d_exp_sign + curr_sym + str.tostring(math.abs(metrics.dollar_expectancy), "#.##") + " per trade)" + "\n• Trades with Defined SL: " + str.tostring(metrics.r_trades_count) + " of " + str.tostring(metrics.total_trades) + " trades" + heat_line
 
        table.cell(t_hud, 0, 3, "Open Capital\n" + cap_str, text_color=hud_txt_col, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_row_odd, tooltip=exp_tip, text_font_family=font.family_monospace)
        table.cell(t_hud, 1, 3, r3_c1_lbl + "\n" + avg_r_s, text_color=avg_r_c, text_size=tbl_sz, text_halign=text.align_center, bgcolor=hud_row_odd, tooltip=exp_tip, text_font_family=font.family_monospace)
        table.cell(t_hud, 2, 3, "Open Positions\n" + tr_cnt_s, text_color=hud_acc_col, text_size=tbl_sz, text_halign=text.align_right, bgcolor=hud_row_odd, text_font_family=font.family_monospace)
 
        // Row 4-7: Mini-Ledger (Last 3 Open or Closed Records via HUD Activity Mode)
        array<DCAEntry> scoped_open_chk = is_global_scope ? cached_open_entries : cached_live_entries
        int  total_open_scoped = scoped_open_chk.size()
        int  total_closed      = scoped_trades_chk.size()
        string scope_tag       = is_global_scope ? " [GLOBAL PORTFOLIO]" : " [" + syminfo.ticker + "]"
        bool fmt_clean         = i_recent_return_format == "Clean Percentage Only (%)"
        bool fmt_dollars       = i_recent_return_format == "Percentage + Dollar PnL ($%)"
        bool show_open_feed    = i_hud_activity_mode == "Open Positions Only" ? true : (i_hud_activity_mode == "Closed Trades Only" ? false : (total_open_scoped > 0 or total_closed == 0))
 
        if not show_open_feed
            table.cell(t_hud, 0, 4, "RECENT ACTIVITY (LAST 3 CLOSED" + scope_tag + ")", text_color=hud_acc_col, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_hdr_bg)
            table.merge_cells(t_hud, 0, 4, 2, 4)
 
            for idx = 0 to 2
                int   row_num   = 5 + idx
                color row_bg    = row_num % 2 == 1 ? hud_row_odd : hud_row_even
                int   trade_idx = total_closed - 1 - idx
                if trade_idx >= 0
                    Trade rec       = scoped_trades_chk.get(trade_idx)
                    bool  rec_win   = rec.realized_pnl_pct >= 0.0
                    color rec_col   = rec_win ? hud_win_col : hud_loss_col
                    float rec_vwap  = nz(rec.get_vwap(), 0.0)
                    float rec_qty   = rec.get_total_size()
                    string rec_curr = rec.entries.size() > 0 ? rec.entries.get(0).currency : f_detect_symbol_currency(rec.symbol, rec_vwap)
                    float  rec_fx   = f_fx_multiplier(rec_curr, i_account_currency)
                    string rec_csym = f_normalize_base_currency(i_account_currency) == "Native" ? f_currency_symbol(rec_curr) : curr_sym
                    string p_sign   = rec.realized_pnl_pct >= 0.0 ? "+" : ""
                    string r_qty_s  = rec_qty == math.floor(rec_qty) ? str.tostring(rec_qty, "#") : str.tostring(rec_qty, "#.##")
                    float  rec_dlr  = (rec.direction == "LONG" ? (rec.exit_price - rec_vwap) : (rec_vwap - rec.exit_price)) * rec_qty * rec_fx
                    string d_sgn    = rec_dlr >= 0.0 ? "+" : "-"
                    string sfx_str  = fmt_clean ? "" : (fmt_dollars ? (" (" + d_sgn + rec_csym + str.tostring(math.abs(rec_dlr), "#.##") + ")") : (not na(rec.realized_r_multiple) ? (" (" + p_sign + str.tostring(rec.realized_r_multiple, "#.##") + "R)") : ""))
 
                    string col0_s   = "#" + str.tostring(rec.id, "00") + " " + rec.symbol + " (" + r_qty_s + ") | " + rec.direction
                    string col1_s   = str.tostring(rec_vwap, format.mintick) + " → " + str.tostring(rec.exit_price, format.mintick)
                    string col2_s   = p_sign + str.tostring(rec.realized_pnl_pct, "#.##") + "%" + sfx_str
 
                    table.cell(t_hud, 0, row_num, col0_s, text_color=rec_col,     text_size=tbl_sz, text_halign=text.align_left,   bgcolor=row_bg, text_font_family=font.family_monospace)
                    table.cell(t_hud, 1, row_num, col1_s, text_color=hud_txt_col, text_size=tbl_sz, text_halign=text.align_center, bgcolor=row_bg, text_font_family=font.family_monospace)
                    table.cell(t_hud, 2, row_num, col2_s, text_color=rec_col,     text_size=tbl_sz, text_halign=text.align_right,  bgcolor=row_bg, text_font_family=font.family_monospace)
                else
                    table.cell(t_hud, 0, row_num, "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_left, bgcolor=row_bg)
                    table.cell(t_hud, 1, row_num, idx == 0 ? "No Closed Records" : "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_center, bgcolor=row_bg)
                    table.cell(t_hud, 2, row_num, "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_right, bgcolor=row_bg)
        else
            table.cell(t_hud, 0, 4, "RECENT OPEN DCA TRADES" + scope_tag, text_color=hud_acc_col, text_size=tbl_sz, text_halign=text.align_left, bgcolor=hud_hdr_bg)
            table.merge_cells(t_hud, 0, 4, 2, 4)
 
            for idx = 0 to 2
                int   row_num = 5 + idx
                color row_bg  = row_num % 2 == 1 ? hud_row_odd : hud_row_even
                int   ent_idx = total_open_scoped - 1 - idx
                if ent_idx >= 0
                    DCAEntry ent     = scoped_open_chk.get(ent_idx)
                    float cur_px     = nz(ent.live_price, ent.price)
                    float ent_pnl    = ent.direction == "LONG" ? ((cur_px - ent.price) / ent.price) * 100.0 : ((ent.price - cur_px) / ent.price) * 100.0
                    color ent_col    = ent_pnl >= 0.0 ? hud_win_col : hud_loss_col
                    string p_sign    = ent_pnl >= 0.0 ? "+" : ""
                    string ent_qty_s = ent.size == math.floor(ent.size) ? str.tostring(ent.size, "#") : str.tostring(ent.size, "#.##")
                    string fd_flag   = ent.has_live_feed ? "" : "*"
                    float  ent_fx    = f_fx_multiplier(ent.currency, i_account_currency)
                    string ent_csym  = f_normalize_base_currency(i_account_currency) == "Native" ? f_currency_symbol(ent.currency) : curr_sym
                    float  ent_dlr   = (ent.direction == "LONG" ? (cur_px - ent.price) : (ent.price - cur_px)) * ent.size * ent_fx
                    string d_sgn     = ent_dlr >= 0.0 ? "+" : "-"
                    string open_sfx  = fmt_clean ? "" : (fmt_dollars ? (" (" + d_sgn + ent_csym + str.tostring(math.abs(ent_dlr), "#.##") + ")") : " (OPEN)")
                    string col0_s    = "#" + str.tostring(ent.ticket_id) + " " + ent.symbol + fd_flag + " (" + ent_qty_s + ") | " + ent.direction
                    string col1_s    = str.tostring(ent.price, "#.##") + " → " + str.tostring(cur_px, "#.##")
                    string col2_s    = p_sign + str.tostring(ent_pnl, "#.##") + "%" + open_sfx
 
                    table.cell(t_hud, 0, row_num, col0_s, text_color=ent_col,     text_size=tbl_sz, text_halign=text.align_left,   bgcolor=row_bg, text_font_family=font.family_monospace)
                    table.cell(t_hud, 1, row_num, col1_s, text_color=hud_txt_col, text_size=tbl_sz, text_halign=text.align_center, bgcolor=row_bg, text_font_family=font.family_monospace)
                    table.cell(t_hud, 2, row_num, col2_s, text_color=ent_col,     text_size=tbl_sz, text_halign=text.align_right,  bgcolor=row_bg, text_font_family=font.family_monospace)
                else
                    string empty_msg = is_global_scope ? "No Open Portfolio Trades" : ("No Trade on " + syminfo.ticker)
                    table.cell(t_hud, 0, row_num, "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_left, bgcolor=row_bg)
                    table.cell(t_hud, 1, row_num, idx == 0 ? empty_msg : "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_center, bgcolor=row_bg)
                    table.cell(t_hud, 2, row_num, "—", text_color=i_c_hud_muted, text_size=tbl_sz, text_halign=text.align_right, bgcolor=row_bg)

← 返回列表