feat: добавить общий виртуальный счёт, справку и восстановление позиций
This commit is contained in:
1 parent
6aa76064dc
commit
c5aed5b970
29 files changed
+3600
-224
No files matched your search
+117
-6
@@ -1,5 +1,84 @@
|
||||
# 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
|
||||
@@ -21,6 +100,13 @@ spot-to-spot entries require manual reconciliation on the exchanges. The applica
|
||||
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,
|
||||
@@ -28,16 +114,35 @@ must match that authority; POST also requires `X-Sim: 1`. The proxy preserves th
|
||||
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.
|
||||
|
||||
Responses for an earlier venue/coin selection cannot replace the current screen. Commands are disabled until
|
||||
the selected context has loaded, and row close actions carry their original venue or coin. Poll responses also
|
||||
have sequence numbers so a slower old response cannot overwrite a newer completed response.
|
||||
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` |
|
||||
@@ -57,9 +162,15 @@ 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. CI runs these suites on Windows with Python 3.11, 3.12 and 3.13; configuring the
|
||||
workflow does not imply that a remote CI run or a real exchange integration has been performed.
|
||||
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.
|
||||
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.
|
||||
Reference in new issue
Block a user