Skip to content

fix(virtual): keep signal accounts marked, funded and liquidated - #441

Closed
mabaojinbj wants to merge 3 commits into
OpenByteInc:mainfrom
mabaojinbj:fix/virtual-account-maintenance
Closed

mabaojinbj wants to merge 3 commits into
OpenByteInc:mainfrom
mabaojinbj:fix/virtual-account-maintenance

Conversation

@mabaojinbj

Copy link
Copy Markdown

Fixes #440.

What changed

Mark-to-market stopped after every runtime restart. mark_virtual_positions() selected positions with (strategy_run_id = 0 OR strategy_run_id = current_run). Positions are only re-stamped with a run id by a new fill, so positions opened by an earlier run became invisible to marking once the runtime restarted. mark_virtual_positions now marks every open position of the strategy; the run id stays on the row for audit but no longer gates marking.

No liquidation. Virtual perpetual accounts had no maintenance-margin check, so paper equity could go arbitrarily negative. liquidate_virtual_positions() now:

  • reads leverage and maintenance_margin_rate / liquidation_margin_rate from trading_config (default 0.5%, capped at half the initial margin),
  • closes every position at the current mark once equity <= maintenance margin,
  • writes qd_strategy_virtual_orders / qd_strategy_virtual_trades rows with close_reason='liquidation' and fill_source='virtual_liquidation',
  • floors the resulting account equity at zero, so a forced close can never lose more than the account had.

No funding. accrue_virtual_funding() pulls settled funding rates from public Binance futures history, falling back to Gate.io. It writes one qd_strategy_funding_fees row per settlement (external_id = virtual:<venue>:<symbol>:<funding_ms>:<side>, so retries are idempotent) and deducts the amount from the virtual account's realized_pnl, which is what every signal-mode equity view reads.

Sweep independent of the strategy runtime. sync_virtual_accounts() marks, funds and liquidates every signal strategy with open virtual positions. PendingOrderWorker._maybe_sync_positions() calls it next to the existing live funding sync, so a stopped/restarting strategy runtime no longer leaves a virtual account frozen.

The live execution path is untouched: the sweep only reads qd_strategy_virtual_positions and writes qd_strategy_virtual_* / qd_strategy_funding_fees.

Tests

backend_api_python/tests/test_virtual_account_maintenance.py:

  • regression: the mark query must not contain strategy_run_id;
  • maintenance-margin defaults, overrides and the cap below initial margin;
  • settlement-price selection from hourly closes;
  • Binance → Gate.io funding fallback.

Shadow replay of the production ledger (hourly Gate.io BTC_USDT marks) is documented in #440: strategy 71 liquidated at 75,741 with 21,633.60 remaining and zero negative observations; a direct mark to the current 52,404 crash price floors equity at 0.0; strategy 72 accrued 4 funding settlements (-6,950.43) before liquidating at 59,131.4.

@mabaojinbj
mabaojinbj force-pushed the fix/virtual-account-maintenance branch 4 times, most recently from fbaf053 to 5f4a9e2 Compare December 4, 2026 07:22
Virtual (signal-mode) positions were marked only when their stored
strategy_run_id matched the current runtime run. Every strategy restart
(the trading worker restores runtimes on boot) orphaned the still-open
positions: mark price, unrealized PnL and equity snapshots froze until a
new fill overwrote the row. On the Raspberry Pi deployment strategies 71
and 72 stayed frozen for 28 and 3 days while BTC fell from ~76k/59.6k to
~52k, so the virtual account showed +34k/+569k equity instead of being
liquidated.

- mark every open virtual position for the strategy, regardless of which
  run opened it.
- add maintenance-margin liquidation for virtual perpetual accounts
  (configurable via maintenance_margin_rate, default 0.5%), force close at
  the current mark, and floor the account equity at zero so paper losses
  can never exceed the initial capital.
- accrue settled funding into qd_strategy_funding_fees using public
  Binance/Gate.io funding history and deduct it from the virtual account's
  realised PnL; runs from the strategy loop and from a worker sweep so a
  stopped runtime cannot leave a position unmarked.
- wire the sweep into the pending-order worker (virtual ledgers only; the
  live execution path is untouched).

Tests cover the run-scope regression, maintenance-margin bounds,
settlement-price selection and the Binance->Gate funding fallback.

Co-authored-by: multica-agent <[email protected]>
@mabaojinbj
mabaojinbj force-pushed the fix/virtual-account-maintenance branch from 5f4a9e2 to ced7a24 Compare December 4, 2026 07:23
- Derive the funding start from the current position cycle by replaying the
  trade ledger, so a partial reduction no longer resets it and the accrual
  never falls back to the strategy creation time.
- Cap every funding backfill window (default 7 days) so a first sweep or a
  long gap cannot back-charge months of settlements at today's size.
- Gate settlements on 8h clock boundaries instead of holding duration.
- Dedupe funding rows per (symbol, minute, side) and only among virtual
  rows so hedged long/short positions both accrue.
- Cancel pending_orders and strategy_order_intents when liquidation cancels
  virtual orders, matching the normal cancellation path.
- Book forgiven loss beyond initial capital as an explicit bad_debt
  adjustment so trade PnL keeps summing to the account's realized PnL.
- Add regression tests for cycle replay, boundary gating, side split,
  three-table liquidation cancel and bad-debt reconciliation.
@sonarqubecloud

sonarqubecloud Bot commented Dec 4, 2026

Copy link
Copy Markdown

❌ The last analysis has failed.

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Virtual (signal) accounts stop marking to market after runtime restart; no liquidation, no funding

3 participants