{"record":{"id":"d5e6a8b8343badb9","repo":"nautechsystems/nautilus_trader","slug":"failed-to-convert-balance-e","errorCode":null,"errorMessage":"Failed to convert balance: {e}","messagePattern":"Failed to convert balance: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/adapters/polymarket/src/execution/parse.rs","lineNumber":717,"sourceCode":"        filled_qty\n    }\n}\n\n/// pUSD scale factor: the Polymarket API returns balances in micro-pUSD (10^6 units).\nconst USDC_SCALE: Decimal = Decimal::from_parts(1_000_000, 0, 0, false, 0);\n\n/// Converts a raw micro-pUSD balance from the Polymarket API into an [`AccountBalance`].\n///\n/// The API returns balances as integer micro-pUSD (e.g. `20000000` = 20 pUSD).\n/// This divides by 10^6 and constructs Money via `Money::from_decimal`, matching\n/// the pattern used by dYdX, Deribit, OKX, and other adapters.\npub fn parse_balance_allowance(\n    balance_raw: Decimal,\n    currency: Currency,\n) -> anyhow::Result<AccountBalance> {\n    let balance_pusd = balance_raw / USDC_SCALE;\n    AccountBalance::from_total_and_locked(balance_pusd, Decimal::ZERO, currency)\n        .map_err(|e| anyhow::anyhow!(\"Failed to convert balance: {e}\"))\n}\n\n/// Result of walking the order book to compute market order parameters.\n#[derive(Debug)]\npub struct MarketPriceResult {\n    /// The crossing price (worst level reached) for the signed CLOB order.\n    pub crossing_price: Decimal,\n    /// Expected base quantity (shares) computed by walking levels at actual prices.\n    pub expected_base_qty: Decimal,\n}\n\n/// Calculates the market-crossing price and expected base quantity by walking the order book.\n///\n/// Sorts levels deterministically before walking:\n/// - BUY (asks): ascending by price, best (lowest) ask first\n/// - SELL (bids): descending by price, best (highest) bid first\n///\n/// This ensures correct results regardless of the CLOB API's response ordering.","sourceCodeStart":699,"sourceCodeEnd":735,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/polymarket/src/execution/parse.rs#L699-L735","documentation":"parse_balance_allowance divides the raw USDC balance by USDC_SCALE and calls AccountBalance::from_total_and_locked; if the domain layer rejects the conversion (e.g. invalid money value for the currency), the error is wrapped as 'Failed to convert balance: {e}'. This surfaces a domain-constraint violation while turning a venue balance into a Nautilus AccountBalance.","triggerScenarios":"fetch_and_emit_account_state receives a balance_raw from the Polymarket API that, after division by USDC_SCALE, cannot form a valid AccountBalance — e.g. a negative balance or a value exceeding currency precision/limits.","commonSituations":"Venue returning an anomalous (negative or huge) balance during API incidents; a USDC_SCALE mismatch making values overflow the expected precision; a changed API response unit.","solutions":["Log and inspect the inner error and the raw balance value to see which domain constraint failed.","Sanity-check balance_raw (reject negatives / implausible magnitudes) before calling parse_balance_allowance.","Verify USDC_SCALE matches the API's current balance units (micro/macro USDC)."],"exampleFix":"// before\nlet balance = parse_balance_allowance(balance_raw, currency)?;\n// after\nanyhow::ensure!(balance_raw >= Decimal::ZERO, \"negative balance_raw: {balance_raw}\");\nlet balance = parse_balance_allowance(balance_raw, currency)?;","handlingStrategy":"try-catch","validationCode":"if balance_raw < Decimal::ZERO { return Err(anyhow!(\"negative balance_raw: {balance_raw}\")); }","typeGuard":null,"tryCatchPattern":"match parse_balance_allowance(balance_raw, currency) {\n    Ok(bal) => emit(bal),\n    Err(e) => { log::error!(\"balance conversion failed: {e:#}; raw={balance_raw}\"); /* skip this update, keep last good state */ }\n}","preventionTips":["Log the raw value and inner error on failure","Sanity-check venue balances against plausible bounds","Pin USDC_SCALE to the documented API units"],"tags":["rust","balance","conversion","polymarket"],"backgroundTag":"type-mismatch","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}