linux
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s

This commit is contained in:
listik committed 2026-10-23 21:36:08 +03:00
1 parent f6f1ae20c2
commit efd4e1dcf4
43 files changed
+25641

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
# Recovery and development
## Shared virtual capital and paper recovery
`virtual_account.py` owns the web application's paper capital in
`web_sim_data/virtual_account.json`. All simulated coin engines use owners named `coin:<key>`;
the paper arbitrage engine uses `cross`. Real arbitrage, real-signal ledgers, the Tk leader window
and the main desktop account do not draw on this wallet.
An owner commit stores its complete recovery snapshot, cumulative cash movement and reserved capital
in the same account document. Only the difference from its previous cash total changes the balance.
This keeps a close, fee or funding payment from being credited again after restart. The account's owner
snapshot takes precedence over legacy per-engine files. Coin snapshots include open positions, IDs,
trade history and policy state needed to resume exits; paper arbitrage snapshots include both legs
and their fixed entry reserves. Restoring these positions does not emit a new entry.
The initial balance is taken once from the old common budget, with a 300 $ default. Migration preserves
existing positions and their reserve even when that reserve exceeds the chosen initial deposit; free
capital then remains zero until the deficit is resolved. Individual legacy starting balances and old
closed profits are not summed into a new deposit. Open-position entry costs are brought into account
cash; the old closed trades remain statistical history. Reopening the same owner does not import it twice.
| Account figure | Meaning |
| --- | --- |
| `balance` | Initial deposit + subsequent adjustments + settled trading cash movements |
| `equity` | Balance + current unrealized result |
| `reserved` | Total capital reserved by all paper owners |
| `free` | `max(0, min(balance, equity) - reserved)` |
| `realized` | Balance minus net deposits; deposits and withdrawals do not change this result |
| `stale` | Array of owners whose open-position marks are missing or older than 30 seconds |
Coin reserve is the margin fixed at entry. Spot/futures arbitrage reserves the spot cost plus the greater
of 103% of futures notional and the capital required by the configured liquidation buffer. Spot/spot
arbitrage reserves the capital of both legs. Changing the settings does not release an existing position's
entry reserve. A new or increased reservation must fit the shared capital after fees. Unrealized losses
reduce free capital; unrealized profits do not fund new entries.
Marks are refreshed only by market data. Saving settings or restoring a checkpoint does not make an old
quote fresh, and one current arbitrage link cannot refresh unrelated positions. If any open owner's mark
is stale, new reservations and withdrawals are refused. Deposits and reductions/settlement remain permitted
by the account, while the trading engine separately checks that it has a usable quote for a paper close.
A restart retains the last known unrealized result but treats its mark as stale until fresh data arrives.
`GET /api/account`, `state.account` and the paper basis response's `paper_account` expose the same account.
`POST /api/account/adjust` accepts a signed `amount` and a `request_id`; the same ID and amount is idempotent,
including after server restart, while reuse for a different amount is refused. Numeric inputs must be finite;
zero adjustments, booleans and out-of-range amounts are rejected. The API journal returns the newest 100
entries first. `version` orders persisted changes; `updated_at` also reflects newer in-memory market marks.
The browser uses both to reject older account snapshots arriving through different endpoints. Its pending
adjustment ID is retained in the currently open page for an explicit retry; after reloading the page, inspect
the journal before starting another adjustment.
Statistics reset cannot erase open shared positions or replenish the account. A coin's web reset is also
refused while real execution is unfinished. Paper and real modes of a coin use separate ledgers:
`signal_<coin>.json/.csv` is the private real-signal state, with no shared-account funding gate or paper
entry hooks. Switching modes requires the current exposure, the destination ledger's saved positions and
real pending/recovery work to be clear. The saved mode and active trader are changed only after the new
ledger and mode settings have been saved successfully.
## Persistence and concurrency
`persistence.atomic_write_json` writes a unique temporary file in the destination directory, flushes and
fsyncs it, then replaces the old JSON file. Account operations prepare a new document and publish it only
after this write succeeds. Failed account writes leave both account cash and the authoritative owner
snapshot unchanged; the engine restores its previous position/history state instead of reporting a fill.
Unreadable or malformed recovery data is surfaced as an error and blocks entries, rather than silently
starting an independent empty paper account. CSV histories are exports, not the recovery authority for
an owner attached to the shared account.
`runtime_lock.py` holds an OS file lock on `web_sim_data/engine.lock` for the entire engine lifetime.
It prevents a second engine using the same data directory even if a different HTTP port is requested.
The OS releases the lock when the process exits; the existence of the lock file alone does not mean a
process still owns it. The HTTP port is bound before recovery workers or exchange connections start.
Within one process, account instances resolving to the same path share an `RLock`; a commit or adjustment
refreshes the latest persisted version while holding that lock before applying its change. Per-engine locks
protect their position/state transitions, and a separate registry lock protects engine lookup and removal.
The account stores snapshots and performs no exchange calls or callbacks into engines while its lock is held.
Atomic replacement does not substitute for these locks: it protects a single file replacement, not two
independent read/modify/write operations.
## Real orders
`cross.py` records an entry intent before sending its first order. A working limit order stays pending until
the exchange reports a terminal status; a cancel acknowledgement alone is insufficient. If the spot hedge is
rejected, the remaining short is closed with reduce-only orders and the actual position is checked again.
Failed and partial rollbacks survive restart and block further real entries while recovery is in progress.
The saved instrument snapshot allows cancellation/rollback even before the market scanner rediscovers the pair.
`real_mirror.py` records prepared, submitted and filled stages. A prepared entry is never replayed on restart.
A confirmed fill is saved before requesting a take-profit. Saved positions are closed after restart, consistent
with the previous simulator behaviour. Atomic JSON writes are shared through `persistence.py`; persistence
failures block new entries and appear in the UI.
An accepted submission whose response was lost may have no exchange order ID. A flat position snapshot does
not prove that such an order cannot fill later. These intents remain blocked; the futures recovery path checks
and reduces any remaining position without submitting another entry. Unknown spot submissions and interrupted
spot-to-spot entries require manual reconciliation on the exchanges. The application does not provide a blind
“forget pending order” button. The `/api/basis?ex=cross_real` response includes `recovery` details; the UI displays
the reason for pausing. A supervised resolution must verify the exchange's open orders and fills, not just its
current position. Automatic resolution by client order ID across every exchange is not implemented.
Coin removal is a durable workflow in `pending_removals.py`, not an immediate deletion of the connection.
The intent and connection are saved first, new entries stop, and paper/real closes are requested. The engine
and its feeds remain available until paper positions are gone and the real mirror reports no position,
pending state, queued job or storage error. Only then are the connection and removal intent removed and
the engine stopped. Restart merges pending-removal connections back into the managed list, so a crash
between deleting the normal connection and completing the intent does not forget unfinished exposure.
## Browser boundary
Both the proxy and the engine validate the original loopback Host on GET and POST. A browser Origin, if present,
must match that authority; POST also requires `X-Sim: 1`. The proxy preserves the validated Host when forwarding.
Both listeners remain bound to loopback. This is local-app isolation, not user authentication for internet hosting.
Static assets are served from an explicit allowlist.
Read timers are registered before the initial request, so a failed first fetch cannot permanently prevent
startup. GET requests have bounded timeouts and share one in-flight request per endpoint within the same
context; slow periodic tasks do not queue duplicate rendering work. Switching a coin or venue invalidates
the old read generation and starts a fresh request. Old responses, including old connection failures, cannot
replace the new context. Row close actions carry their original venue or coin. Sequence numbers also reject
older completed poll responses. The scanner checks the selected context before changing the DOM and again
after awaiting its response.
An error or more than 10 seconds without a successful relevant read disables browser commands and displays
the last-data age. This is distinct from the account's 30-second market-mark rule. GET polling reconnects
automatically; POST commands are never automatically replayed. A lost command response is shown as an
unconfirmed result, requiring inspection of positions/state before an explicit repeat. Business refusals,
including statistics-reset refusals, are displayed instead of discarded. The selected mode and account
scope remain visible. Main arbitrage settings and fee/limit edits have separate Save buttons; switching
between paper and real views keeps their unsaved drafts separate in the current browser page.
`web/help-data.js` contains the local reference descriptions; `web/help.js` builds a searchable native dialog
from them and the actual settings/modes used by the page. It supports keyboard focus, Escape and returning
focus to the opener. A regression test checks that all declared settings and static controls have help text.
## Code boundaries
| Responsibility | Files |
| --- | --- |
| Web layout, styles, behaviour | `web_sim.html`, `web/app.css`, `web/app.js` |
| Searchable help and field descriptions | `web/help.js`, `web/help-data.js` |
| HTTP routing and local browser policy | `web_sim.py`, `web_proxy.py`, `request_security.py` |
| Shared paper cash, owner snapshots and reservations | `virtual_account.py`, `scalp_paper.py`, `cross.py` |
| Single-engine ownership and deferred removal | `runtime_lock.py`, `pending_removals.py` |
| Desktop account models and chart | `desktop_models.py`, `desktop_chart.py` |
| Desktop coordination | `main.py` |
| Order execution and recovery | `cross.py`, `real_mirror.py` |
| Exchange adapters | `live.py`, `bybit_live.py` |
| Atomic snapshots | `persistence.py` |
| Historical execution and risk metrics | `historical_backtest.py`, `strategy.py` |
## Verification
Python 3.11+ is supported by the pinned dependencies in `requirements.txt`; the primary local validation uses
Python 3.12. JavaScript regression tests use Node.js 22+ and its built-in test runner, with no npm dependencies.
```powershell
python -m pip install -r requirements.txt
python -B scripts/run_tests.py
node --test tests/web_context.test.cjs
```
The Python runner blocks external connections and DNS while permitting loopback HTTP fixtures. Exchange orders
are tested using fake clients. The CI workflow is configured for Windows with Python 3.11, 3.12 and 3.13;
configuration does not imply that a remote CI run or a real exchange integration has been performed. Browser
preview checks use a separate mocked local API, not a running trading backend.
Regression cases cover refused/partial rollback, uncertain cancellation and submission, restart before and
after order acceptance, failed disk writes, hostile Host/Origin, response ordering, percentage drawdown and
capital-floor ordering for long/short backtests including fees. Shared-account cases additionally cover
competing coins/arbitrage for one reserve limit, idempotent adjustments and settlement, migration/restart,
stale marks and retained unrealized losses, entry/close rollback on write failure, fixed collateral after
settings changes, reset without creating money, and separation of real signal execution from virtual funding.
Browser tests cover first-fetch recovery, single-flight reads, context invalidation, stale controls, scanner
navigation, refused reset, account snapshot ordering, signed adjustments, retry IDs and help coverage.