Fase 3 — Conti, ordini, contabilità #89

Merged
Alby96 merged 7 commits from fase-3 into main 2026-11-10 22:32:05 +01:00
Owner

Conti, ordini e contabilità: interfaccia comune dei broker, simulatore interno, gestore degli ordini con gli stop sul broker, contabilità per strategia in sola aggiunta, riconciliazione con modalità prudente, adapter Alpaca (paper) e OKX (demo), schermata Conti e posizioni, chiavi e capitale in Impostazioni.

  • Scelte nell'ADR 0009; fatti delle API verificati in docs/API-NOTES.md ("Verifiche della Fase 3").
  • tasks check verde; stessi test verdi su SQLite e PostgreSQL (216 superati).
  • Revisione indipendente fatta; i difetti trovati sono corretti in 1a0912e (frazionamenti vecchi, prezzi delle posizioni, stop prima di una vendita, vendite rifiutate, token antifalsificazione, riconciliazione, capitale in dollari, codici OKX).
  • In attesa dell'utente: la batteria di conformità sui veri conti di prova (servono le chiavi demo di OKX e Alpaca).

Closes #26
Closes #27
Closes #28
Closes #29
Closes #30
Closes #31
Closes #32
Closes #33

🤖 Generated with Claude Code

Conti, ordini e contabilità: interfaccia comune dei broker, simulatore interno, gestore degli ordini con gli stop sul broker, contabilità per strategia in sola aggiunta, riconciliazione con modalità prudente, adapter Alpaca (paper) e OKX (demo), schermata Conti e posizioni, chiavi e capitale in Impostazioni. - Scelte nell'ADR 0009; fatti delle API verificati in `docs/API-NOTES.md` ("Verifiche della Fase 3"). - `tasks check` verde; stessi test verdi su SQLite e PostgreSQL (216 superati). - Revisione indipendente fatta; i difetti trovati sono corretti in 1a0912e (frazionamenti vecchi, prezzi delle posizioni, stop prima di una vendita, vendite rifiutate, token antifalsificazione, riconciliazione, capitale in dollari, codici OKX). - In attesa dell'utente: la batteria di conformità sui veri conti di prova (servono le chiavi demo di OKX e Alpaca). Closes #26 Closes #27 Closes #28 Closes #29 Closes #30 Closes #31 Closes #32 Closes #33 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Alby96 added this to the Fase 3 — Conti, ordini, contabilità milestone 2026-11-10 21:51:22 +01:00
Alby96 added 6 commits 2026-11-10 21:51:23 +01:00
Phase 3 needs books the bot can trust before any strategy trades. This adds:
- schema 0003: executions, order events, trades, residues, account status,
  reconciliations, capital changes, applied corporate actions, simulator books;
- the broker interface with the internal simulator and the Alpaca paper and
  OKX demo adapters, all behind the live guard (SPEC 2.2);
- the append-only ledger with lots, trades from zero to zero, residues,
  dividends, splits and reversals; capital entrusted per broker and equity
  photographs with time-weighted return and FX effect;
- the order manager (chasing limit, pacing, sells never abandoned, server
  stops, breached-stop rule) and the reconciler with prudent mode;
- the trading service wired into the host, off in demo mode and in tests.

Ids made with one clock in the same millisecond now carry a counter (RFC 9562
method 1): two lots of one order kept a random order, which broke LIFO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Order manager tests drive the internal simulator turn by turn: the chasing
limit with its post-only steps and aggressive cross, a buy given up, a sale
never given up with its alert, the pace of six sends a minute, Alpaca's
GTC + day stops, the stop-already-passed rule and splits, lost answers,
duplicate fills, refusals and residues. Reconciliation tests cover clean,
healed, prudent mode and its return, align/exclude, unknown orders, stop
coverage, withdraw-capable keys and an unreachable broker.

Two defects found by the tests are fixed: stops were not cleared before an
execution that starts aggressive (Alpaca refuses a buy with a sell stop open,
and a sale must free the quantity), and an order's creation is now recorded
as its first event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One abstract battery states the adapter contract (time and cash, an order's
client id from send to cancel, well-formed orders, positions and fills with
fees as costs, key permissions) and runs it on the internal simulator, on
Alpaca's and OKX's documentation samples with stateful fakes, and on the demo
accounts when the user's keys are in the environment (LiveDemo, inconclusive
without them). The OKX sample key lists withdraw, and the adapter reports it.

Service tests cover the accounts created without keys (no request leaves),
stock strategies moving to the paper account only while their ledger is
empty, the simulator funded from the ledgers once, and dividends and splits
applied once each. The whole suite also passes on PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Conti e posizioni screen follows mockup 02: totals split by strategy,
one card per account with key permissions and the last reconciliation,
positions with a per-account filter and CSV export, pending stops (Alpaca
grouped into permanent and day stops), residues, and exposure by currency.
It shows one world only, real accounts when there are any, so simulated
and real money never add up. Position values are rounded to the cent per
row, as the table shows them, so the figures add up on screen.

Settings gain "Conti e chiavi": practice keys are asked to the broker
before they are saved and refused when they may withdraw or cannot trade;
they are never shown again and the engine restarts to use them. The
capital entrusted to each broker is set there in euro. Until any capital
is set, the overview points to that section as the first step.

The overview now reads one world, nets capital flows out of its results
and uses the time-weighted index; open orders exclude protective stops.

The demo seed gains cash rows, closed trades, stops, the ECB rate and the
reconciliation state, so the ledger itself computes the mockup's figures.
Screenshots now capture the whole page and include Conti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ADR 0009 records the Phase 3 choices; API-NOTES gains the verified trading
facts and what Anubis does with each; ROADMAP and STATE mark the phase done
with the live-demo conformance waiting for the user's keys.

Two defects found while writing the notes:
- The positions CSV used dot decimals; SPEC 13 asks for decimal commas.
  Trailing zeros are dropped so both engines give the same text.
- Alpaca's catalogue has no tick, so limit and stop prices were sent
  unrounded and would get 422 "sub-penny". OrderRules.TickOf applies
  Alpaca's rule (2 decimals from 1 $, 4 below) to orders, stops and the
  simulator's own check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fix the defects found by the Phase 3 review (refs #33 #26 #27 #28 #29 #30 #31 #32)
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
1a0912e436
- Splits multiply only the shares held before the ex-date. Old splits in
  the table no longer inflate positions bought later; the simulator's book
  follows the same split once, together with the ledger.
- Dividends pay the simulator once on the ex-date holdings, and each
  payment is marked in the same write, so a failure never pays twice.
- Positions are marked to market before every equity photograph; until
  now equity, drawdown and the Conti screen stayed at the last fill.
- A sale with no price keeps its broker stops until it can really leave;
  a purchase with no price is dropped.
- A refused sale is retried with pauses of 1, 2, 4, 8 and 15 minutes
  instead of every tick, and one failing execution no longer stops the
  stop alignment of the whole account.
- On Alpaca a purchase clears the sell stops of every strategy on the
  symbol and holds them until it ends.
- OKX order lookups treat only 51603 as unknown; any other failure is an
  error, so a lost order is never sent twice.
- The reconcile choice and key removal forms now require the antiforgery
  token; the choice re-runs the comparison and is only offered after the
  15 minutes; stale differences are dropped.
- A replaced key that cannot withdraw releases the prudent mode.
- Re-entering the same euro capital for Alpaca changes nothing; a new
  amount converts only the euro difference at today's rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Alby96 added 1 commit 2026-11-10 22:10:44 +01:00
Retry test database creation on any transient PostgreSQL error (refs #33)
ci / test (postgres) (push) Successful in 3m40s
ci / test (sqlite) (push) Successful in 2m53s
ci / test (postgres) (pull_request) Successful in 4m31s
ci / test (sqlite) (pull_request) Successful in 2m59s
ci / image (push) Successful in 13s
ci / image (pull_request) Successful in 15s
16be51e175
CI run 188 failed once on the SQLite job: a cross-engine test lost its
connection (EndOfStreamException) while creating its PostgreSQL database,
right after the service container started. The retry covered only
timeouts. It now covers every transient Npgsql error and picks a new
database name on each attempt, in case the lost answer had already
created the database. Test helper only; no product code changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Alby96 merged commit 6d3ef8e7b5 into main 2026-11-10 22:32:05 +01:00
Sign in to join this conversation.
No Reviewers
No labels
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: BalboSoft/Anubis#89