{"record":{"id":"c73efba9e8b1d058","repo":"nautechsystems/nautilus_trader","slug":"failed-to-repay-spot-borrow-with-conversion-for","errorCode":null,"errorMessage":"Failed to repay spot borrow (with conversion) for {coin}: {e}","messagePattern":"Failed to repay spot borrow \\(with conversion\\) for (.+?): (.+?)","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/adapters/bybit/src/http/client.rs","lineNumber":2399,"sourceCode":"    /// # Errors\n    ///\n    /// Returns an error if:\n    /// - Credentials are missing.\n    /// - The request fails.\n    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).\n    /// - Insufficient balance for repayment.\n    pub async fn repay_spot_borrow_with_conversion(\n        &self,\n        coin: &str,\n        amount: Option<Quantity>,\n    ) -> anyhow::Result<BybitRepayResponse> {\n        let amount_str = amount.as_ref().map(|q| q.to_string());\n        let response = self\n            .inner\n            .repay(Some(coin), amount_str.as_deref())\n            .await\n            .map_err(|e| {\n                anyhow::anyhow!(\"Failed to repay spot borrow (with conversion) for {coin}: {e}\")\n            })?;\n        Self::ensure_repay_accepted(coin, response.result.result_status)?;\n        Ok(response)\n    }\n\n    fn ensure_repay_accepted(coin: &str, status: BybitRepayStatus) -> anyhow::Result<()> {\n        anyhow::ensure!(\n            status != BybitRepayStatus::Failed,\n            \"Bybit repay for {coin} returned result status {status}\"\n        );\n        Ok(())\n    }\n\n    /// Generate SPOT position reports from wallet balances.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if:","sourceCodeStart":2381,"sourceCodeEnd":2417,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/bybit/src/http/client.rs#L2381-L2417","documentation":"The repay-with-conversion wrapper calls the inner repay endpoint (which may convert other assets to cover the borrow) and wraps request failures with a coin-labeled anyhow error. The {e} inside carries the true cause: network failure, Bybit error code (insufficient balance, invalid coin, permissions), or rate limiting. On success, ensure_repay_accepted still validates the result status.","triggerScenarios":"Calling the conversion repay when the account has no convertible assets, the coin has no outstanding borrow, the request times out, or Bybit rejects due to permissions or risk state.","commonSituations":"Closing short spot positions and cleaning up borrows across multiple coins; margin liquidations leaving unexpected borrow states; automated repay loops hitting rate limits.","solutions":["Read the inner {e} to identify the actual failure code","Confirm the coin has an outstanding borrow and sufficient assets (or convertible balance) exist","Ensure API credentials include repay/margin trading permissions","Back off and retry on transient errors; respect Bybit rate limits"],"exampleFix":"// before\nclient.repay(Some(\"USDT\"), Some(\"50\".into())).await?;\n// after\nmatch client.repay(Some(\"USDT\"), Some(\"50\".into())).await {\n    Ok(resp) => log::info!(\"repay accepted\"),\n    Err(e) => log::error!(\"repay with conversion failed: {e}\"),\n}","handlingStrategy":"try-catch","validationCode":"let convertible = client.get_convertible_balance(coin).await?;\nif convertible < amount { return Err(\"insufficient assets for convert-repay\".into()); }","typeGuard":null,"tryCatchPattern":"match client.repay(Some(coin), amount).await {\n    Ok(_) => info!(\"convert-repay {coin} accepted\"),\n    Err(e) => {\n        warn!(\"convert-repay {coin} failed: {e}\");\n        sleep_backoff().await;\n    }\n}","preventionTips":["Verify assets exist to convert before repay-with-conversion","Rate-limit repay loops to avoid 429s","Check borrow state before looping repay across coins"],"tags":["rust","bybit","http","margin"],"backgroundTag":"api-request-failed","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"}