Skip to content

fix(virtual): restore signal account maintenance and reconcile historical funding - #442

Merged
brokermr810 merged 167 commits into
mainfrom
test
Dec 4, 2026
Merged

brokermr810 merged 167 commits into
mainfrom
test

Conversation

@brokermr810

@brokermr810 brokermr810 commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Signal accounts can retain open exposure across runtime restarts while their marks, funding and liquidation stop updating. This continues #441 by @mabaojinbj, preserving all three original authored commits and the original co-author trailer, then adds fixes for issues found during review. References #440.

Behavior and fixes

  • Mark positions across runtime runs and sweep open/recently closed signal accounts from the trading worker, independently of live-position synchronization. Rotate batches so accounts beyond the first 50 are not starved.

  • Reconstruct quantity at each historical funding settlement, including additions, reductions, hedge sides and closed legs. Serialize ledger updates and deduplicate settlements; do not silently erase funding losses while exposure remains.

  • Use historical fill product/venue for funding, including carry-in quantities. Exclude spot fills and skip unknown/mixed historical venues instead of inferring today's configuration. Prefer settlement marks; record previous-hour close estimates explicitly and avoid future-candle prices.

  • Require complete valid prices for simulated liquidation; reject stale background crypto quotes. Fix multi-instrument canonical symbols, cancellation of resting-order chains, final account equity, and explicit bad-debt adjustments.

  • Preserve instrument market/venue when fetching marks, show zero/current equity correctly, and route public REST requests through existing request budgets.

  • Check margin before matching resting virtual orders and after fills. Fetch background marks after funding I/O; funding failures must not suppress liquidation checks.

  • Include only virtual funding and explicit debt adjustments in virtual trade summaries; exclude adjustments from completed/winning trade counts and include historical virtual funding when reconstructing daily opening equity.

  • Treat the first monotonic-clock maintenance call as due, including during the first five minutes after host startup.

Validation

  • 118 focused cases verified locally, including 13 isolated PostgreSQL transaction cases covering concurrent/idempotent funding, historical products/venues and sizes, closed positions, liquidation, ledger reconciliation and real/virtual funding separation.
  • Current revision fd607d8 passed both Linux backend CI shards: 7,584 tests, plus 158 transactional accounting checks and the independent release gate. This includes the sandbox/runtime coverage that requires Linux.
  • Full Ruff critical lint, backend structure guardrail, documentation checks and diff whitespace checks passed.
  • No real orders or production databases were used.

Scope and deployment

Signal-mode simulated ledgers only; no real broker orders. Funding currently covers Binance/Gate USDT perpetuals; unsupported venues/products are skipped. Liquidation is a simplified account-wide model for linear USDT/USDC swaps, not an exact exchange margin engine.

Deploy API and trading/evaluator workers together. No new schema migration. First deployment may append missing funding within the default seven-day window and trigger simulated liquidation; existing fills are not rewritten. English/Chinese safety guides document bounds and configuration.

Attribution

Original commits from @mabaojinbj: ced7a24, 9ebeb24, c50bb51 (retained authors through signed-off cherry-picks). Please preserve the original author commits when merging; if squashing, retain Co-authored-by: mabaojinbj <[email protected]> and the existing co-author attribution in the squash message.

tianhe added 30 commits November 1, 2026 17:17
Signed-off-by: TIANHE <[email protected]>

# Conflicts:
#	backend_api_python/app/routes/community.py
tianhe and others added 26 commits November 30, 2026 13:37
Signed-off-by: TIANHE <[email protected]>

# Conflicts:
#	docs/trading/LIVE_TRADING_SAFETY.md
#	docs/trading/LIVE_TRADING_SAFETY_CN.md
Signed-off-by: TIANHE <[email protected]>

# Conflicts:
#	docs/trading/LIVE_TRADING_SAFETY.md
#	docs/trading/LIVE_TRADING_SAFETY_CN.md
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]>
Signed-off-by: TIANHE <[email protected]>
- 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.

Signed-off-by: TIANHE <[email protected]>
@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Dec 4, 2026

Copy link
Copy Markdown

@brokermr810
brokermr810 merged commit 08da2f4 into main Dec 4, 2026
15 checks passed
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.

7 participants