diff --git a/CLAUDE.md b/CLAUDE.md index fad0d07..fa592cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,8 @@ Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR - `docs/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti - `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri - `docs/adr/0007-scelte-fase-1.md` — schema per i due motori, interfaccia statica, immagine Docker +- `docs/MANUALE.md`, `docs/RUNBOOK.md`, `docs/GO-LIVE.md` — manuali per l'utente: si aggiornano insieme al codice +- `docs/adr/0020-scelte-fase-9.md` — consegna, ripristino, dichiarazione, revisione trimestrale - `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo - `docs/ROADMAP.md` — fasi, issue, criteri di accettazione - `docs/STATE.md` — stato corrente diff --git a/README.md b/README.md index 12fbe5c..8ca6c53 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Bot di trading personale: azioni USA su **Alpaca** e crypto spot su **OKX Europe Si installa in due modi, dallo stesso codice: - **Docker**, un solo container pensato per un server Unraid sempre acceso. Immagine: `gitea.encke-hake.ts.net/balbosoft/anubis` (sezione Packages del repository). -- **Applicazione desktop** per Windows, con installatore (sezione Release). +- **Applicazione desktop** per Windows, con installatore (Fase 10, non ancora disponibile). Database a scelta: PostgreSQL oppure SQLite. Scritto in C# su .NET 10, con interfaccia Blazor: nessun runtime da installare, né su Windows né su Unraid (ADR 0003). @@ -23,6 +23,9 @@ Nell'antico Egitto Anubis, il dio con la testa di sciacallo, pesava il cuore dei | Documento | Contenuto | |---|---| +| [docs/MANUALE.md](docs/MANUALE.md) | Installare, usare, salvare, ripristinare | +| [docs/RUNBOOK.md](docs/RUNBOOK.md) | Cosa fare negli incidenti | +| [docs/GO-LIVE.md](docs/GO-LIVE.md) | Cosa deve essere vero prima dei soldi veri (questa versione non li usa) | | [docs/SPEC.md](docs/SPEC.md) | Specifica completa: architettura, strategie, rischio, interfaccia, piano a fasi | | [docs/ROADMAP.md](docs/ROADMAP.md) | Le fasi con i lavori su Gitea e i criteri di accettazione | | [docs/STATE.md](docs/STATE.md) | A che punto siamo e cosa serve dall'utente | diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index b71c508..f1a5cf8 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -163,6 +163,8 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio | V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 | | Storia dei flag ETF e frazionabile | Gli universi passati usano i flag di oggi; il limite è scritto nel rapporto della prova storica. | 4 | | Barre dei titoli tolti dalla borsa su Alpaca | Da controllare con le chiavi del conto di prova; fino ad allora gli universi passati vanno letti come ottimisti. | 2, 4 | +| Codici di una chiave rifiutata | Alpaca e OKX rispondono 401 o 403; su OKX i codici 50102 e 50112 parlano dell'orologio e non della chiave. Scritto dalla documentazione, non provato dal vivo: se un codice mancasse, l'avviso direbbe "non risponde" invece di "non accetta la chiave" (ADR 0020). | 9 | +| Archivi della SEC (settori) | `company_tickers.json` e `submissions` letti come da documentazione, non provati dal vivo perché serve un contatto dell'utente. Senza, nessuna richiesta parte; un settore sconosciuto non limita niente. | 9 | | Minuti senza scambi su OKX | Il buco si riscarica una volta, poi resta segnato come non recuperabile e non blocca nulla. | 2 | ## Verifiche della Fase 2 (dati di mercato) diff --git a/docs/MANUALE.md b/docs/MANUALE.md index b2fc0ab..fc4f56e 100644 --- a/docs/MANUALE.md +++ b/docs/MANUALE.md @@ -318,7 +318,9 @@ Si ripristina sempre in un database **vuoto**: quello che c'era non viene mai so 3. Avvia. L'interfaccia mostra "Il file del database non c'è…" (SQLite) oppure "Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già" (PostgreSQL). 4. Scegli il salvataggio, scrivi la **password iniziale** (quella della configurazione, `ANUBIS_ADMIN_PASSWORD`) e premi **Ripristina**. 5. Accedi con la password **che valeva il giorno del salvataggio** (anche il secondo fattore torna quello). -6. Il bot riparte **protetto**: è fermo. Dai conti di prova dei broker legge cosa è successo dopo il salvataggio, lo riscrive nel registro, annulla gli acquisti e le vendite rimasti in sospeso e riprende gli stop che trova sul conto. Il simulatore interno sta nel database: torna com'era al momento del salvataggio e quello che è successo dopo è perso. Quando ha finito la pagina **Rischio** elenca cosa ha ricostruito e cosa non è chiaro. Controlla, in particolare le posizioni segnalate senza stop, poi premi **Riparti**. +6. Il bot riparte **protetto**: è fermo. Dai conti di prova dei broker legge cosa è successo dopo il salvataggio, lo riscrive nel registro, annulla gli acquisti e le vendite rimasti in sospeso e riprende gli stop che trova sul conto. Il simulatore interno sta nel database: torna com'era al momento del salvataggio e quello che è successo dopo è perso. Quando ha finito la pagina **Rischio** elenca cosa ha ricostruito e cosa non è chiaro. Controlla, in particolare le posizioni segnalate senza stop, poi premi **Riparti**. Se nel salvataggio c'era una chiusura di tutte le posizioni ancora a metà, il bot non la continua e te lo scrive: se la vuoi ancora, chiedila di nuovo. + +Se il ripristino non riesce (archivio rovinato, disco pieno) la pagina lo dice e puoi riprovare o sceglierne un altro. Con SQLite un file cominciato e non finito resta in `db/` con `.incompleto-` nel nome: si può cancellare. Da quel momento il database di prima non viene più accettato: due registri sullo stesso conto farebbero ordini doppi. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6d5cd78..a6f6484 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -15,10 +15,10 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest | 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Completata (conti di prova in attesa delle chiavi) | | 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Completata | | 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Completata (`crypto_trend` non superato, azionarie in attesa delle chiavi Alpaca) | -| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Completata (prova di 48 ore in corso) | -| 7 | [Notizie](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/34) | Da fare | -| 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Da fare | -| 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Da fare | +| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Completata | +| 7 | [Notizie](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/34) | Completata (rapporto della prova di durata in attesa dell'utente) | +| 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Completata | +| 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Completata (pubblicazione e prova su Unraid in attesa dell'utente) | | 10 | [Applicazione desktop](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/37) | Da fare | Sezioni da leggere in ogni fase, oltre a 2, 16 e 19 e all'ADR 0003 (stack C#), che valgono sempre: indicate sotto il titolo. @@ -262,23 +262,23 @@ Un pacchetto Docker installabile da zero seguendo solo il manuale. **Lavori** -- [ ] [#68](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/68) Revisione della sicurezza -- [ ] [#69](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/69) Salvataggi, ripristino, impronta del database e ripartenza protetta -- [ ] [#70](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/70) CI completa e pubblicazione del pacchetto Docker nel registry di Gitea -- [ ] [#71](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/71) Template Unraid definitivo con icona e test -- [ ] [#72](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/72) Manuali: MANUALE.md, RUNBOOK.md, GO-LIVE.md -- [ ] [#73](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/73) Esportazione per la dichiarazione dei redditi -- [ ] [#74](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/74) Strategie candidate, migliorie in osservazione e revisione trimestrale -- [ ] [#75](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/75) Chiusura della fase, revisione indipendente e tag `fase-9` +- [x] [#68](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/68) Revisione della sicurezza +- [x] [#69](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/69) Salvataggi, ripristino, impronta del database e ripartenza protetta +- [x] [#70](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/70) CI completa e pubblicazione del pacchetto Docker nel registry di Gitea +- [x] [#71](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/71) Template Unraid definitivo con icona e test +- [x] [#72](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/72) Manuali: MANUALE.md, RUNBOOK.md, GO-LIVE.md +- [x] [#73](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/73) Esportazione per la dichiarazione dei redditi +- [x] [#74](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/74) Strategie candidate, migliorie in osservazione e revisione trimestrale +- [x] [#75](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/75) Chiusura della fase, revisione indipendente e tag `fase-9` **Criteri di accettazione** -- [ ] Installazione da zero con `docker run` seguendo solo il manuale, una volta con SQLite e una con PostgreSQL -- [ ] Il template Unraid supera il test di 15.3 (la prova su Unraid la fa l'utente) -- [ ] Ripristino da un salvataggio verificato, con la ripartenza protetta di 15.1 -- [ ] Un database vecchio, riavviato dopo un'importazione, porta alla pagina d'errore (test) -- [ ] `tasks check` e `tasks ci` passano, e la CI remota se esiste -- [ ] `STATE.md` elenca con franchezza ciò che resta debole +- [x] Installazione da zero con `docker run` seguendo solo il manuale, una volta con SQLite e una con PostgreSQL (prova del 01/12/2026 sull'immagine costruita, nella issue #72: accesso, capitale, tutte le pagine, salvataggio, ripristino, cambio di motore, importazione) +- [x] Il template Unraid supera il test di 15.3 (`DeliveryTests`). *In attesa dell'utente: la prova su Unraid* +- [x] Ripristino da un salvataggio verificato, con la ripartenza protetta di 15.1 (`RestoreServerTests`, `RestoreTests` e la prova nella issue #72, su entrambi i motori) +- [x] Un database vecchio, riavviato dopo un'importazione, porta alla pagina d'errore (`AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser`, e provato con i container) +- [x] `tasks check` e `tasks ci` passano, e la CI remota se esiste +- [x] `STATE.md` elenca con franchezza ciò che resta debole (sezione "Cosa resta debole") ## Fase 10 — Applicazione desktop diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index a323b4d..6119fb9 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -145,6 +145,7 @@ Quando il bot dice solo "il broker non risponde", non è la chiave: è la rete o 2. Quando ha finito, leggi cosa ha ricostruito e confrontalo con il sito del broker. 3. Se tra le cose ricostruite c'è un avviso, sistemalo prima di ripartire: - "non è nel catalogo, l'ordine … resta da controllare a mano": cerca quell'ordine sul sito del broker. Il bot non lo ha registrato: se ha comprato qualcosa, resta sul conto e il bot non lo gestisce; decidi tu se tenerlo o venderlo dal sito. + - "Nel salvataggio c'era una chiusura di tutte le posizioni non ancora finita": il bot non la continua. Se la vuoi ancora, chiedila dalla pagina Rischio. - "la posizione ricostruita non ha uno stop": guardala in Conti e posizioni e segui [5](#5-posizione-senza-stop). - "Il broker racconta solo gli ultimi … giorni": confronta a mano con il sito del broker le operazioni più vecchie. diff --git a/docs/STATE.md b/docs/STATE.md index 732ce0a..b88a293 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-12-01 ## Fase corrente -**Fase 8 — Apprendimento: completata.** La prossima è la Fase 9 — Rifinitura e consegna in Docker. Della Fase 7 resta un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. +**Fase 9 — Rifinitura e consegna in Docker: completata**, con tre cose in attesa dell'utente: il permesso di pubblicare l'immagine (segreto `REGISTRY_TOKEN` e primo tag `v*`), la prova del template su Unraid e, dalla Fase 7, il rapporto della prova di durata (#55). La prossima è la Fase 10 — Applicazione desktop. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. ## Fatto @@ -122,15 +122,41 @@ Aggiornato: 2026-12-01 - Schermata Apprendimento come il mockup 06 e sezione del modello in Impostazioni (#66). - Correzioni di due revisioni indipendenti (#67, ADR 0018 punti 17 e 18). +- **Fase 9** (scelte nell'ADR 0020, nessun pacchetto nuovo): + - Sicurezza (#68): password e codice per ciò che conta, limite unico ai tentativi, elenco delle chiamate ammesse ai broker, segreti mascherati, pagine chiuse di base. + - Salvataggi e ripristino (#69): ripartenza protetta che ricostruisce dai broker, impronta del database, copie vecchie rifiutate, migrazione fallita senza danni, `access reset`. + - Consegna (#70, #71): CI, pubblicazione sui tag `v*` (`tools/`, anche a mano), controllo di salute più severo, template Unraid definitivo con test. + - Manuali (#72): `MANUALE.md`, `RUNBOOK.md`, `GO-LIVE.md`, controllati frase per frase sul codice e provati installando da zero su SQLite e PostgreSQL. La prova ha trovato e fatto correggere: ripristino impossibile con SQLite senza file, conto prudente senza via d'uscita, stop mancante ignorabile, chiusura delle posizioni impossibile a bot fermo, chiave rifiutata confusa con un broker muto, ripartizione del capitale assente dall'interfaccia. + - Esportazione per la dichiarazione dei redditi (#73). + - Strategie candidate, migliorie in osservazione e revisione trimestrale (#74). + ## In corso Nulla. ## Prossimo passo -1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55. -2. La Fase 9 — Rifinitura e consegna in Docker, in una nuova sessione, sul branch `fase-9` da `main`. -3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. +1. L'utente decide se unire la pull request della Fase 9, pubblicare l'immagine e mettere il tag. +2. L'utente prova il template su Unraid seguendo `docs/MANUALE.md`. +3. Quando l'utente incolla il rapporto della release `v0.7.0`, si analizza, si salva in `docs/diagnostica/` e si chiude #55. +4. La Fase 10 — Applicazione desktop, in una nuova sessione, sul branch `fase-10` da `main`. +5. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. + +## Cosa resta debole + +- **Nessuna strategia ha superato il backtest.** `crypto_trend` no (calo massimo del 32,8% contro il 25%; probabilità di sovra-adattamento 0,835 contro 0,40 su BTC, ETH e SOL); le due azionarie non sono ancora provate; la candidata crypto non ha superato il protocollo. Oggi il bot osserva e basta. +- **I conti reali non esistono nel codice** e nessuna fase li prevede: creazione, chiavi, guardia e avvio sono da scrivere e provare. +- **Gli adapter non hanno mai parlato con un conto di prova vero**: la batteria di conformità passa solo sulle risposte d'esempio della documentazione. Ordini, stop, ricostruzione dopo un ripristino e codici di una chiave rifiutata vanno verificati dal vivo. +- **Crypto sempre nel simulatore interno**: manca la scelta per strategia tra simulatore e conto di prova (SPEC 7.1), quindi lo scostamento vero delle crypto non si può misurare. +- **Incidenti critici**: il requisito di 12.3 conta solo l'arresto per perdita del 15%, la specifica chiede di più. +- **Prova di durata (#55)** non chiusa: manca il rapporto della release di prova. +- **Il modello** è appena migliore della frequenza di base e ha studiato solo `crypto_trend`. +- **Dati**: gli universi azionari passati usano i flag di oggi; la storia crypto prima di novembre 2023 viene da Binance in USDT; gli archivi della SEC non sono mai stati letti dal vivo. +- **Un acquisto tagliato da un limite di rischio** non lascia una riga nel diario, solo nelle decisioni. +- **Importazione CSV** solo da riga di comando, e il Laboratorio legge solo le serie di Binance. +- **La guardia** apre solo i conti di prova e non può proteggere le posizioni del simulatore mentre il motore è fermo. +- **L'interfaccia è HTTP** e va tenuta nella rete di casa; chi è nella rete può bloccare l'accesso per 15 minuti. +- **Unraid e pubblicazione** non provati sul server dell'utente. ## Da sapere @@ -162,13 +188,14 @@ Nulla. | Far girare la release `v0.7.0` e incollare il rapporto in chat | Ora, per il tempo che vuoi | La prova di durata (#55) resta aperta | | Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria e Alpaca News (#107) spente; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa | | Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa | -| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | +| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN`, e il via al primo tag `v*` | Ora (pubblicazione dell'immagine) | Pubblicazione a mano | | Token del bot Telegram e chat autorizzata (facoltativi), da Impostazioni → Telegram | Fase 6 | Nessun avviso sul telefono; comandi provati con un finto server | | Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme | | Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | | Se mandare alla SEC un nome e un contatto, e quali (facoltativo, #107) | Fase 7 | Niente comunicati EDGAR dei singoli titoli; resta il feed generale della SEC | | Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale | -| Prova del template su Unraid | Fase 9 | Criterio in attesa | +| Prova del template su Unraid, seguendo `docs/MANUALE.md` 2.6 | Ora | Criterio in attesa | +| Decidere sulla pull request #110 (test SQLite in memoria nella CI) | Quando vuoi | La CI resta come è | | Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa | Le chiavi non vanno mai scritte nel repository: si mettono nel file `.env` locale (modello in `.env.example`) oppure, più avanti, dall'interfaccia. diff --git a/docs/SVILUPPO.md b/docs/SVILUPPO.md index f78caf4..b3d7071 100644 --- a/docs/SVILUPPO.md +++ b/docs/SVILUPPO.md @@ -15,6 +15,7 @@ Regole di lavoro per chi scrive il codice, persona o agente. Riassumono le sezio | Pacchetti ammessi | `docs/adr/0004-componenti-esterni.md` | | Logo | `docs/design/logo/` (ADR 0005) | | Fatti verificati sulle API | `docs/API-NOTES.md` (nasce nella Fase 0) | +| Manuali per l'utente (si aggiornano insieme al codice) | `docs/MANUALE.md`, `docs/RUNBOOK.md`, `docs/GO-LIVE.md` | | Template Unraid | `deploy/unraid/anubis.xml` | | Lavori, milestone, pacchetti, release | https://gitea.encke-hake.ts.net/BalboSoft/Anubis | diff --git a/docs/adr/0020-scelte-fase-9.md b/docs/adr/0020-scelte-fase-9.md new file mode 100644 index 0000000..d98d2f7 --- /dev/null +++ b/docs/adr/0020-scelte-fase-9.md @@ -0,0 +1,80 @@ +# 0020 — Scelte della Fase 9 (rifinitura e consegna in Docker) + +Data: 2026-12-01 · Stato: accettata · Precisa SPEC 4.6, 7.4, 8.4, 8.7, 10.5, 12.2–12.4, 13.5, 15.1–15.5 e appendice E; sostituisce il punto 12 dell'ADR 0018 per gli esiti della revisione trimestrale + +## Contesto + +La Fase 9 chiude i lavori lasciati indietro dalle altre e prepara la consegna in Docker. Dove la specifica lasciava spazio si è scelta la via più prudente. Il numero 0019 è usato nella pull request #110, ancora aperta. + +## Decisione + +### Sicurezza (#68) + +1. Una sessione aperta non basta per cambiare la password, il secondo fattore, o l'indirizzo e il servizio a cui va la chiave del modello linguistico. Cambiare la password chiede quella attuale ma non il codice: chi ha perso il telefono deve poter chiudere le sessioni altrui. Cambiando password o secondo fattore le altre sessioni finiscono. +2. Non chiedono la password: annullare la promozione di un modello e la fiducia in una fonte di notizie. Possono solo cambiare una prudenza già limitata da altre regole. +3. Il limite ai tentativi è doppio: 5 in 15 minuti per indirizzo e 20 in tutto. Chi è nella rete di casa può quindi tenere fuori l'utente per un quarto d'ora; non può entrare. +4. Il filtro sui nomi (`AllowedHosts`) è spento di base: su Unraid l'indirizzo non si conosce in anticipo. +5. Il diario non si maschera in scrittura: le sue frasi sono fisse e non contengono segreti. Registri e notifiche sì. +6. La pagina d'errore in Docker mostra indirizzo e utente del database, mai la password: senza, non si capisce cosa correggere. +7. Le chiavi dei cookie (`web-keys`) restano in chiaro nella cartella dei dati, leggibile solo dall'utente del bot (ADR 0007). +8. Le pagine escono con `Cache-Control: no-store`. + +### Salvataggi e ripristino (#69) + +9. Un conto senza chiavi non blocca la ripartenza protetta: non si può leggere, e senza chiavi non riceve nemmeno ordini. +10. Una copia a mano del file SQLite, o di tutta la cartella dei dati, non si distingue dall'originale se esistono solo conti del simulatore interno: lì non c'è un broker da interrogare. Con un conto di prova la si scopre dagli ordini sconosciuti. +11. OKX racconta 89 giorni di esecuzioni. Un'esecuzione il cui ordine OKX ha dimenticato non si può attribuire a una strategia: si segnala e resta da controllare a mano. +12. Con SQLite, se il file manca e `installation.json` c'è, la pagina d'errore offre le stesse scelte del database vuoto. Il file nasce solo da una scelta confermata con la password; se nel frattempo torna, si usa quello. Prima di questa scelta il ripristino con SQLite era impossibile. +13. Durante la ricostruzione non si può nemmeno "Chiudere tutte le posizioni": il registro non è ancora quello vero. Dopo sì, anche a bot fermo e senza ripartire. + Finché un conto non è ricostruito, per lui non si scrive, non si confronta e non si vende niente. Una ricostruzione interrotta riprende dallo stesso punto (`rebuild_since`, migrazione 0015) e la protezione scatta prima della prima riga scritta. + Le esecuzioni ricostruite sono storia: entrano con i frazionamenti della loro data, senza vendite e senza avvisi sul telefono. Una "chiusura di tutte le posizioni" rimasta a metà nel salvataggio si lascia cadere, con un avviso. + I dividendi contano le azioni dopo i frazionamenti e spettano anche a ciò che è stato venduto negli ultimi 90 giorni. + +### Consegna (#70, #71) + +14. La versione sta solo in `Directory.Build.props`; un tag `v*` diverso fa fallire la pubblicazione. `latest` si sposta solo in avanti. +15. Nel template il segnale di vita è mascherato, diversamente dall'appendice E: il suo indirizzo è di fatto un segreto. +16. L'icona del template è il logo dell'ADR 0005. Se il repository non è leggibile senza accesso, Unraid non la mostra. +17. Il controllo di salute guarda database, pianificatore, motore e prezzi in diretta di OKX; non Alpaca, che di notte tace. +18. Le connessioni a PostgreSQL non provano Kerberos: si entra con la password, e la libreria non è nell'immagine. + +### Dichiarazione dei redditi (#73) + +19. Il costo di ciò che è venduto si ricalcola dalle esecuzioni di tutto il conto, non dai lotti per strategia: per la legge la posizione è una sola. Il metodo (LIFO di base, oppure FIFO) vale per azioni e crypto e si può cambiare quando si vuole. +20. Conta il giorno italiano; il cambio è quello BCE del giorno o l'ultimo precedente, purché non più vecchio di 7 giorni. Oltre, la cella resta vuota e lo dice. +21. Un file per mondo: simulazione e conti di prova insieme, soldi veri a parte. Residui e allineamenti si elencano ma non sono vendite. I dividendi sono lordi, alla data di stacco. Le spese che Alpaca addebita a parte (`FEE`, `DIVNRA`) non si leggono. + +### Strategie candidate (#74) + +22. Le regole delle due candidate sono state fissate prima di ogni prova. `crypto_relative_momentum` è stata provata una volta, su un solo universo, e **non ha superato** il protocollo (DSR 0,744; calo massimo 35,3%): è archiviata e non decide. `stock_ath_breakout` aspetta lo storico di Alpaca; i massimi storici si contano dal 2016, dove comincia quello storico. +23. Le candidate non hanno quota, capitale né strada verso un ordine. Passare da candidata a strategia di base resta una decisione dell'utente (SPEC 12.3). Le loro osservazioni non riempiono il diario. + +### Migliorie in osservazione (#74) + +24. Ogni miglioria si misura sugli esempi dell'archivio, quindi sui segnali nuovi, dopo la decisione e senza poterla toccare. I pesi delle strategie sono le quote 40/45/15. Il tetto alla volatilità si applica agli ingressi dopo i correttivi, su 90 giorni, con 365 o 252 giorni l'anno. +25. Il settore sono le prime due cifre del codice SIC. Un settore sconosciuto non viene mai limitato. La richiesta alla SEC parte solo se l'utente ha scritto un contatto, che si conserva cifrato, si inserisce solo dall'interfaccia e va solo alla SEC. +26. L'orario d'ingresso si confronta sulle barre al minuto, senza spread; la scelta del modello non considera l'ordine di cassa. L'effetto è una quota dell'investito, raggruppato per mese. + +### Revisione trimestrale (#74) + +27. Le prove che il DSR conta sono fissate nel piano, così una prova ripresa dopo un riavvio conta le stesse. Tra l'esito incluso nel programma e quello della revisione vale il più recente per dati, a parità di versione della strategia. +28. Una revisione sposta qualcosa solo per le strategie in osservazione o simulazione senza capitale: con capitale l'unico effetto è la condizione di retrocessione. Una strategia che supera passa in simulazione dopo 90 giorni di osservazione, a meno che l'utente abbia scelto diversamente; il passaggio automatico avviene solo al primo vero avvio. +29. La revisione usa la tabella dei costi aggiornata: per gli esiti che nascono così sostituisce il punto 12 dell'ADR 0018. Le candidate sono escluse. Le strategie azionarie senza dati risultano "in attesa". +30. La riga delle trimestrali di 10.5 non si misura. Le frequenze di base si ricalcolano, ma il modello non si sostituisce da solo. Parte dal 15 del mese e recupera una volta se il bot era spento. + +### Impostazioni e conti (#72, SPEC 7.4 e 13.5) + +31. La ripartizione del capitale tra le strategie di un broker si cambia dall'interfaccia; con soldi veri in gioco qualunque cambio chiede frase, password e codice, perché abbassare una quota ne alza un'altra. I parametri delle strategie non si cambiano dall'interfaccia. I CSV si importano solo da riga di comando. +32. Una chiave rifiutata (risposta 401 o 403) è distinta da un broker che tace; su OKX sono esclusi i codici 50102 e 50112, che parlano dell'orologio. Non è verificato dal vivo. +33. Dopo i 15 minuti la scelta c'è anche se la differenza è sparita; uno stop mancante non si può lasciare fuori; a broker muto la scelta non cambia niente. +34. Passare ai soldi veri in questa versione è impossibile: mancano la creazione del conto reale, le sue chiavi e la guardia. Nessuna fase lo prevede; va chiesto. + +## Alternative scartate + +- **Creare da soli un file SQLite vuoto quando manca.** È la trappola 20: un disco scollegato diventerebbe un'installazione nuova. +- **Applicare subito le migliorie che sembrano buone.** SPEC 8.7 le vuole in osservazione. +- **Ritoccare la candidata crypto dopo il risultato.** Sarebbe una seconda prova mascherata da prima. + +## Conseguenze + +Nessun pacchetto nuovo. Ciò che resta debole è in `docs/STATE.md`, sezione "Cosa resta debole". diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 4fc2de5..f5f311c 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -152,7 +152,8 @@ internal sealed partial class AnubisHost( /// /// A choice that failed or was cut halfway leaves nothing open that could create the missing file, and what it had - /// begun to write steps aside: moved and not deleted, because in the meantime the true file may have come back. + /// begun to write steps aside, moved and not deleted. In the meantime the true file may have come back: that one is + /// not touched, and the loop finds it. /// internal async Task AbandonChoiceAsync() { @@ -165,6 +166,11 @@ internal sealed partial class AnubisHost( _db = null; _createdByChoice = false; var path = Config.Db!.SqlitePath!; + if (!File.Exists(path) || !await IsLeftoverAsync().ConfigureAwait(false)) + { + return; + } + var aside = path + ".incompleto-" + clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture); foreach (var part in new[] { "", "-wal", "-shm" }) { @@ -182,6 +188,31 @@ internal sealed partial class AnubisHost( } } + /// + /// A file a choice left halfway: without an installation, or with the sealed one of an import not renewed yet. One + /// that cannot be read is not certainly that. + /// + private async Task IsLeftoverAsync() + { + try + { + await using var db = Database.Open(Config.Db!, allowCreate: false); + if ((await Migrations.StatusAsync(db, CancellationToken.None).ConfigureAwait(false)).IsEmpty) + { + return true; + } + + var row = await Installation.ReadRowAsync(db, CancellationToken.None).ConfigureAwait(false); + return row is null ? !await Installation.HasDataAsync(db, CancellationToken.None).ConfigureAwait(false) + : row.ProtectedRestart && row.Fingerprint != Installation.ReadFile(Config.Data)?.Fingerprint; + } + catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException) + { + LogStepFailed(logger, ex); + return false; + } + } + /// The choice is done: the database it opened is the one in use. internal void KeepChoice() => _createdByChoice = false; diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 956a967..0eea896 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -310,6 +310,9 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .chart-axis { position: relative; } .chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; } .chart-plot { position: relative; } +.chart-days { position: relative; height: 18px; margin: 8px 84px 0 64px; } +.chart-days span { position: absolute; transform: translateX(-50%); color: var(--text-3); font-size: 13px; white-space: nowrap; } +.chart-days span:first-child { transform: none; } .chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } .chart .grid { stroke: var(--rule-inner); stroke-width: 1; } .chart .area { fill: var(--text); opacity: .05; } @@ -796,7 +799,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; } .half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; } .half + .half { border-left: 1px solid var(--rule); } - .segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; } + .segmented, .cell-change, .cell-extra, .long, .chart-axis, .chart-days { display: none; } .lead { margin-top: 12px; } .big-result { gap: 12px; } .big-number { font-size: 46px; line-height: 48px; } diff --git a/src/Anubis.Server/Components/EquityChart.razor b/src/Anubis.Server/Components/EquityChart.razor index 3039dcb..1206889 100644 --- a/src/Anubis.Server/Components/EquityChart.razor +++ b/src/Anubis.Server/Components/EquityChart.razor @@ -48,6 +48,12 @@ @Text(Points[^1].Equity, 0) +
@EquityLabel @if (benchLine.Length > 0) @@ -102,6 +108,9 @@ private string Text(decimal amount, int decimals = 2) => Native ? Format.Money(amount, Currency, decimals: decimals) : Shell.Money(amount, Currency, decimals: decimals); + // Five dates at even distances, first and last included; fewer when there are not enough days. + private IEnumerable Days() => Enumerable.Range(0, 5).Select(i => i * (Points.Count - 1) / 4).Distinct(); + private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture); private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%"; diff --git a/src/Anubis/Core/Format.cs b/src/Anubis/Core/Format.cs index a3ab409..ca1106b 100644 --- a/src/Anubis/Core/Format.cs +++ b/src/Anubis/Core/Format.cs @@ -166,6 +166,11 @@ public static class Format public static string LongDate(DateOnly date) => string.Create(CultureInfo.InvariantCulture, $"{date.Day} {_monthsLong[date.Month - 1]} {date.Year}"); + /// A day under a chart that covers days: 12 ago, or ago 2024 over more than a year. + public static string AxisDay(DateOnly day, int span) => span > 370 + ? string.Create(CultureInfo.InvariantCulture, $"{_months[day.Month - 1]} {day.Year}") + : string.Create(CultureInfo.InvariantCulture, $"{day.Day} {_months[day.Month - 1]}"); + /// How long ago, in words: 4 secondi fa, 3 minuti fa. public static string Ago(TimeSpan elapsed) { diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index afdfff4..2a06bcb 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -561,8 +561,11 @@ public sealed partial class MarketDataService : IDisposable await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false); } - /// Splits and dividends of the stock universe from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10). - public async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) + /// Splits and dividends of the stocks the bot follows or still owes for, from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10). + public Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) => RefreshCorporateActionsAsync([], null, cancellationToken); + + /// The same with more symbols, at least back to : what a rebuild of an account is about to write. + public async Task RefreshCorporateActionsAsync(IReadOnlyCollection more, DateOnly? since, CancellationToken cancellationToken) { if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca) { @@ -570,8 +573,15 @@ public sealed partial class MarketDataService : IDisposable } var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); - var universe = await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false); - if (universe.Count == 0) + var symbols = (await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false)).Select(m => m.Symbol).Concat(more) + .ToHashSet(StringComparer.Ordinal); + + // Also what is held or was sold lately and left the universe: its splits and dividends are still owed. + symbols.UnionWith(await _db.ReadAsync(s => s.QueryAsync( + "SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (EXISTS (SELECT 1 FROM positions p WHERE p.instrument_id = i.id) " + + "OR EXISTS (SELECT 1 FROM fills f WHERE f.instrument_id = i.id AND f.executed_at >= @at))", r => r.Text("symbol"), + ("v", Venues.Alpaca), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false)); + if (symbols.Count == 0) { return; } @@ -580,11 +590,18 @@ public sealed partial class MarketDataService : IDisposable var last = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT created_at FROM corporate_actions ORDER BY created_at DESC LIMIT 1", r => r.Moment("created_at")) .ConfigureAwait(false)).Select(m => (DateTimeOffset?)m).FirstOrDefault(), cancellationToken).ConfigureAwait(false); var from = last is { } known && DateOnly.FromDateTime(known.UtcDateTime) < today ? DateOnly.FromDateTime(known.UtcDateTime) : today; - var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken) - .ConfigureAwait(false); + if (since is { } far && far < from) + { + from = far; + } + + var actions = await alpaca.FetchCorporateActionsAsync(symbols.Order(StringComparer.Ordinal).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken).ConfigureAwait(false); await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false); } + /// How long a stock sold still owes the dividends of when it was held: a rebuild or a long stop brings them late. + public static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90); + private async Task PruneAsync(CancellationToken cancellationToken) { await new BarStore(_db, _clock).PruneMinutesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs index 19b9d3b..4254f8d 100644 --- a/src/Anubis/Platform/Installation.cs +++ b/src/Anubis/Platform/Installation.cs @@ -108,7 +108,7 @@ public static class Installation private static readonly string[] _dataTables = ["users", "accounts", "orders", "fills", "cash_ledger"]; - private static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s => + public static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s => { foreach (var table in _dataTables) { @@ -179,7 +179,7 @@ public static class Installation // Sessions of the old database do not survive: everyone signs in again. await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false); - await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + await DisarmAsync(s, clock, null, cancellationToken).ConfigureAwait(false); await Trading.Diary.NotifyAsync(s, clock, "protected_restart", $"{reason}: il database ha una nuova impronta e il bot riparte protetto, con \"Ferma tutto\" acceso. Guarda cosa ho ricostruito e riparti dalla pagina Rischio.", cancellationToken).ConfigureAwait(false); @@ -191,24 +191,27 @@ public static class Installation /// /// Switches the protected restart on without changing the fingerprint: the accounts hold orders this database never - /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. + /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. What was asked or + /// begun from on is of today, not of the copy, and stays. /// - public static Task ProtectAsync(Database db, IClock clock, CancellationToken cancellationToken = default) + public static Task ProtectAsync(Database db, IClock clock, DateTimeOffset before, string message, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(clock); return db.WriteAsync(async s => { await s.ExecuteAsync("UPDATE installation SET protected_restart = @p, renewed_at = @r", cancellationToken, ("p", true), ("r", clock.UtcNow)).ConfigureAwait(false); - await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + await DisarmAsync(s, clock, before, cancellationToken).ConfigureAwait(false); + await Trading.Diary.NotifyAsync(s, clock, "protected_restart", message, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// /// SPEC 15.1: "Ferma tutto" on, every strategy with real money in exit only until it is confirmed again, and no - /// order planned before the restore still waiting to leave (it may already have left, after the archive). + /// order planned before the restore still waiting to leave (it may already have left, after the archive). The same + /// for the protective sales of the archive: what still needs one is decided again on the rebuilt position. /// - private static async Task DisarmAsync(DbSession s, IClock clock, CancellationToken cancellationToken) + private static async Task DisarmAsync(DbSession s, IClock clock, DateTimeOffset? before, CancellationToken cancellationToken) { var now = clock.UtcNow; var key = Core.SettingsStore.BotState.Key; @@ -237,9 +240,18 @@ public static class Installation await s.ExecuteAsync("UPDATE planned_orders SET status = @d, outcome = @o, updated_at = @t WHERE status = @p", cancellationToken, ("d", Trading.PlannedStates.Dropped), ("o", ProtectedRestartReason), ("t", now), ("p", Trading.PlannedStates.Pending)).ConfigureAwait(false); + var until = before ?? DateTimeOffset.MaxValue; + foreach (var sale in (await s.QueryAsync("SELECT e.id, e.started_at FROM executions e JOIN accounts a ON a.id = e.account_id WHERE e.status = @w AND e.purpose = 'protective' AND a.environment <> @sim", + r => (Id: r.Id("id"), Started: r.Moment("started_at")), ("w", Trading.ExecutionStates.Working), ("sim", Trading.TradingEnvironments.Simulation)).ConfigureAwait(false)) + .Where(e => e.Started < until)) + { + await s.ExecuteAsync("UPDATE executions SET status = @c, reason = @r, finished_at = @t, updated_at = @t WHERE id = @id", cancellationToken, + ("c", Trading.ExecutionStates.Canceled), ("r", ProtectedRestartReason), ("t", now), ("id", sale.Id)).ConfigureAwait(false); + } + // A "close all positions" of before the restore may be done already: going on with it would sell what came after. var bot = await s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Json("state").Text, ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false); - if (bot is not null && JsonSerializer.Deserialize(bot, Trading.RiskEngine.Json) is { CloseAll: true }) + if (bot is not null && JsonSerializer.Deserialize(bot, Trading.RiskEngine.Json) is { CloseAll: true } pending && !(pending.CloseAllSince >= until)) { await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken, ("j", new DbJson(JsonSerializer.Serialize(new Trading.BotRiskState(), Trading.RiskEngine.Json))), ("t", now), ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false); diff --git a/src/Anubis/Supervision/GuardRepair.cs b/src/Anubis/Supervision/GuardRepair.cs index c0ed4f6..41676ea 100644 --- a/src/Anubis/Supervision/GuardRepair.cs +++ b/src/Anubis/Supervision/GuardRepair.cs @@ -49,8 +49,9 @@ public static class GuardRepair } // 2. What the bot holds now: the state's quantity plus the fills of its own orders since then, never more than the account has. - var fills = (await broker.GetFillsAsync(state.WrittenAt, cancellationToken).ConfigureAwait(false)) - .Where(f => f.ExecutedAt > state.WrittenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList(); + var writtenAt = account.WrittenAt ?? state.WrittenAt; + var fills = (await broker.GetFillsAsync(writtenAt, cancellationToken).ConfigureAwait(false)) + .Where(f => f.ExecutedAt > writtenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList(); var positions = await broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false); var stops = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)) .Where(o => o.IsOpen && o.Side == OrderSide.Sell && ClientOrderIds.Parse(o.ClientOrderId) is { Purpose: OrderPurpose.Stop } parts && parts.Installation == state.Installation) diff --git a/src/Anubis/Supervision/GuardState.cs b/src/Anubis/Supervision/GuardState.cs index 6ecf457..50daab1 100644 --- a/src/Anubis/Supervision/GuardState.cs +++ b/src/Anubis/Supervision/GuardState.cs @@ -11,7 +11,11 @@ namespace Anubis.Supervision; public sealed record GuardState(DateTimeOffset WrittenAt, string Installation, IReadOnlyList Accounts); public sealed record GuardAccount(Guid AccountId, string Name, string Broker, string Environment, bool FractionalStopsAreDayOnly, - IReadOnlyList Positions, IReadOnlyList Orders); + IReadOnlyList Positions, IReadOnlyList Orders) +{ + /// When these figures were read, if earlier than the file: an account whose ledger is not up to date yet keeps those of before. + public DateTimeOffset? WrittenAt { get; init; } +} /// /// A position of a strategy: quantity, stop level already on the tick, lot, and what the guard needs to name a stop diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs index 8422c58..a21ea31 100644 --- a/src/Anubis/Trading/Ledger.cs +++ b/src/Anubis/Trading/Ledger.cs @@ -428,9 +428,9 @@ public sealed class Ledger(Database db, IClock clock) }, cancellationToken); /// Writes the latest price of an instrument on the positions that hold it, for their value. - public Task MarkAsync(Guid instrumentId, decimal price, CancellationToken cancellationToken) => - db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE instrument_id = @i", cancellationToken, - ("p", price), ("now", clock.UtcNow), ("i", instrumentId)), cancellationToken); + public Task MarkAsync(Guid accountId, Guid instrumentId, decimal price, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i", cancellationToken, + ("p", price), ("now", clock.UtcNow), ("a", accountId), ("i", instrumentId)), cancellationToken); /// Sets the protective level shown with a position. public Task SetStopAsync(Guid accountId, Guid instrumentId, string strategy, decimal? stop, CancellationToken cancellationToken) => diff --git a/src/Anubis/Trading/OrderManager.Rebuild.cs b/src/Anubis/Trading/OrderManager.Rebuild.cs index c566db1..4e3d3a2 100644 --- a/src/Anubis/Trading/OrderManager.Rebuild.cs +++ b/src/Anubis/Trading/OrderManager.Rebuild.cs @@ -86,12 +86,30 @@ public sealed partial class OrderManager } } - var onlyStops = written == 0 && unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0); - if (protect is not null && (unclear.Count > 0 || (unknown.Count > 0 && !onlyStops))) + var recordedBefore = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT execution_id FROM fills WHERE account_id = @a", r => r.Text("execution_id"), + ("a", _account.AccountId)).ConfigureAwait(false)).ToHashSet(StringComparer.Ordinal), cancellationToken).ConfigureAwait(false); + if (RefreshSplits is not null && (begun is not null || unknown.Count > 0 || fills.Any(f => !recordedBefore.Contains(f.ExecutionId)))) + { + var symbols = fills.Select(f => f.Symbol).Concat(open.Select(o => o.Symbol)).ToHashSet(StringComparer.Ordinal); + await RefreshSplits(symbols, DateOnly.FromDateTime(since.UtcDateTime), cancellationToken).ConfigureAwait(false); + } + + // What an interrupted attempt wrote does not count here: if it had to, it protected before its first row. + var onlyStops = unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0); + if (protect is not null && (unclear.Count > 0 || !onlyStops)) { await protect(cancellationToken).ConfigureAwait(false); } + foreach (var row in await HalfWrittenAsync(cancellationToken).ConfigureAwait(false)) + { + // Cut between the row and its state: the broker is asked again. + var symbol = (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!.Symbol; + var own = fills.Where(f => f.ClientOrderId == row.ClientOrderId).ToList(); + var remote = open.FirstOrDefault(o => o.ClientOrderId == row.ClientOrderId) ?? await _broker.GetOrderAsync(row.ClientOrderId, symbol, cancellationToken).ConfigureAwait(false); + await SettleRebuiltAsync(row, symbol, remote, own, cancellationToken).ConfigureAwait(false); + } + foreach (var (clientId, parts, instrumentId, own, resting) in unknown) { var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol; @@ -107,42 +125,89 @@ public sealed partial class OrderManager written++; } - if (written > 0) + // The same for one the database knows of an execution that is over: the restore ended the archive's protective sales. + foreach (var resting in open.Where(o => ClientOrderIds.Parse(o.ClientOrderId)!.Purpose != OrderPurpose.Stop)) { - var recorded = await SyncFillsFromAsync(since, cancellationToken, replay: true).ConfigureAwait(false); - var positions = await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false); - foreach (var instrumentId in positions.Select(p => p.InstrumentId).Distinct()) + if (await OrderByClientIdAsync(resting.ClientOrderId, cancellationToken).ConfigureAwait(false) is { ExecutionId: { } execution } row + && await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE id = @id AND status = @w", ("id", execution), ("w", ExecutionStates.Working)), cancellationToken) + .ConfigureAwait(false) == 0) { - await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false); + await CancelAndReadAsync(row, (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!, "execution_over", cancellationToken).ConfigureAwait(false); } - - await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false); - foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null)) - { - var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; - unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire."); - } - - var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." + - (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since); - await _db.WriteAsync(async s => - { - await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken, - ("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false); - await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - return new RebuildReport(written, recorded, unclear, onlyStops); } - if (unclear.Count > 0) + // Also when every order was known: the executions of while the bot was off meet the splits of their time, and + // only then a split or a dividend of today finds the quantities it needs. + var replay = new Replay(Quiet: written > 0); + var recorded = await SyncFillsFromAsync(since, cancellationToken, replay).ConfigureAwait(false); + if (written == 0) { - await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken) - .ConfigureAwait(false); + await SellRestOfStopsAsync(replay, cancellationToken).ConfigureAwait(false); + if (recorded > 0 && AfterFills is not null) + { + await AfterFills(cancellationToken).ConfigureAwait(false); + } + + if (unclear.Count > 0) + { + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken) + .ConfigureAwait(false); + } + + return new RebuildReport(0, recorded, unclear); } - return new RebuildReport(0, 0, unclear); + foreach (var instrumentId in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct()) + { + await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false); + } + + await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false); + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null)) + { + var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; + unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire."); + } + + unclear.AddRange(replay.Refused.DistinctBy(f => f.ExecutionId).Select(f => + $"{f.Symbol}: {(f.Side == OrderSide.Buy ? "un acquisto" : "una vendita")} di {Format.Quantity(f.Quantity)} non torna con il registro, controlla la posizione prima di ripartire.")); + if (AfterFills is not null) + { + await AfterFills(cancellationToken).ConfigureAwait(false); + } + + var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." + + (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since); + await _db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken, + ("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false); + await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + return new RebuildReport(written, recorded, unclear, onlyStops && written == unknown.Count); } + /// + /// A stop of while the bot was off that fired only in part, or one of Alpaca's two: the rest is sold at once (SPEC 7.2). + /// Only where the stop is the last thing that happened to the position. + /// + private async Task SellRestOfStopsAsync(Replay replay, CancellationToken cancellationToken) + { + foreach (var ((instrumentId, strategy), _) in replay.Last.Where(l => l.Value == OrderPurpose.Stop)) + { + if (await _ledger.PositionAsync(_account.AccountId, instrumentId, strategy, cancellationToken).ConfigureAwait(false) is { Quantity: > 0m } rest) + { + await ProtectiveSaleAsync(instrumentId, strategy, rest.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false); + } + } + } + + private Task> HalfWrittenAsync(CancellationToken cancellationToken) => + _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status = 'created' AND reason = @r", ReadOrder, ("a", _account.AccountId), ("r", RebuiltReason)), + cancellationToken); + + private const string RebuiltReason = "rebuilt from the broker"; + /// The splits with an ex-date up to , in the ledger only: each is applied once. private async Task ReplaySplitsAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken) { @@ -157,7 +222,7 @@ public sealed partial class OrderManager ? [] : [.. (await Splits(instrument, cancellationToken).ConfigureAwait(false)).Where(s => s.ChangesShares && ExDate(s) <= until).OrderBy(s => s.ExDate).Select(s => (instrument, s))]; - private static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + internal static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); private string Beyond(DateTimeOffset since) => _broker.FillHistory is { } reach && since < _clock.UtcNow - reach ? $" Il broker racconta solo gli ultimi {reach.Days} giorni: quello che è successo prima va confrontato a mano." @@ -207,8 +272,8 @@ public sealed partial class OrderManager await s.ExecuteAsync("UPDATE account_status SET rebuild_since = @since, rebuild_orders = COALESCE(rebuild_orders, 0) + 1, updated_at = @now WHERE account_id = @a", cancellationToken, ("since", since), ("now", now), ("a", _account.AccountId)).ConfigureAwait(false); await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false); - await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = 'rebuilt from the broker' WHERE id = @id", cancellationToken, - ("b", remote?.BrokerOrderId), ("at", created), ("id", row.Id)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = @r WHERE id = @id", cancellationToken, + ("b", remote?.BrokerOrderId), ("at", created), ("r", RebuiltReason), ("id", row.Id)).ConfigureAwait(false); if (_account.Environment == TradingEnvironments.Live) { // The archive may be older than the promotion: what the bot holds on the real account gets its stops and @@ -217,11 +282,18 @@ public sealed partial class OrderManager ("a", _account.AccountId), ("x", true), ("now", now), ("s", parts.Strategy)).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); - remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt) + await SettleRebuiltAsync(row, remote?.Symbol ?? own[0].Symbol, remote, own, cancellationToken).ConfigureAwait(false); + } + + /// The state of a rebuilt order: the broker's, or what its executions say when the broker forgot it. + private Task SettleRebuiltAsync(OrderRow row, string symbol, BrokerOrder? remote, List own, CancellationToken cancellationToken) + { + var filled = own.Sum(f => f.Quantity); + return ApplyRemoteAsync(row, remote ?? new BrokerOrder(row.ClientOrderId, null, symbol, row.Side, row.Kind, row.Quantity, + filled > 0m ? OrderStatus.Filled : OrderStatus.Canceled, filled, own.Count > 0 ? own[^1].ExecutedAt : _clock.UtcNow) { - AverageFillPrice = DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled), - }; - await ApplyRemoteAsync(row, remote, "rebuilt from the broker", cancellationToken).ConfigureAwait(false); + AverageFillPrice = filled > 0m ? DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled) : null, + }, RebuiltReason, cancellationToken); } /// diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index d1e9b23..b3d3afc 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -141,6 +141,12 @@ public sealed partial class OrderManager : IDisposable /// public bool AwaitingRebuild { get; set; } + /// + /// Asks the splits of these symbols since a day again, before executions of the past are written: without them a + /// sale of new shares would be refused. A failure leaves the account waiting (SPEC 15.1). + /// + public Func, DateOnly, CancellationToken, Task>? RefreshSplits { get; init; } + /// Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5). public Func? AfterFills { get; init; } @@ -408,6 +414,12 @@ public sealed partial class OrderManager : IDisposable await CancelAndReadAsync(current, instrument, reason, cancellationToken).ConfigureAwait(false); } + if (AwaitingRebuild) + { + // Its executions cannot be read yet: the startup ends it after the rebuild, with the stop of what was bought. + continue; + } + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false); canceled.Add(exec.Id); @@ -752,7 +764,7 @@ public sealed partial class OrderManager : IDisposable /// With the executions are history (SPEC 15.1): they are written with the splits of their /// time, and nothing is done about them. What to do today is decided afterwards, on the position that results. /// - private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, bool replay = false) + private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, Replay? replay = null) { var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false); var recorded = 0; @@ -769,7 +781,7 @@ public sealed partial class OrderManager : IDisposable continue; } - if (replay) + if (replay is not null) { await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); } @@ -789,6 +801,7 @@ public sealed partial class OrderManager : IDisposable { await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_refused_fill", $"Un'esecuzione su {_account.Name} non torna con il mio registro: la controllo nella riconciliazione. ({ex.Message})", cancellationToken), cancellationToken).ConfigureAwait(false); + replay?.Refused.Add(fill); continue; } @@ -798,6 +811,11 @@ public sealed partial class OrderManager : IDisposable } recorded++; + if (replay is not null) + { + replay.Last[(row.InstrumentId, row.Strategy)] = row.Purpose; + } + var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false); await _db.WriteAsync(async s => { @@ -818,20 +836,20 @@ public sealed partial class OrderManager : IDisposable await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text, new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false); - if (!replay) + if (replay is null or { Quiet: false }) { // Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14). await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); - if (!replay && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) + if (replay is null && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) { // A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2). await ProtectiveSaleAsync(row.InstrumentId, row.Strategy, outcome.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false); } } - if (recorded > 0 && AfterFills is not null) + if (replay is null && recorded > 0 && AfterFills is not null) { await AfterFills(cancellationToken).ConfigureAwait(false); } @@ -839,6 +857,17 @@ public sealed partial class OrderManager : IDisposable return recorded; } + /// + /// A reading of the past: what the ledger refused, and the purpose of the last execution recorded of each position. + /// Quiet when the executions are those of after an archive, days old: they do not reach the phone as new. + /// + private sealed record Replay(bool Quiet) + { + public List Refused { get; } = []; + + public Dictionary<(Guid Instrument, string Strategy), OrderPurpose> Last { get; } = []; + } + private async Task RefreshOpenOrdersAsync(CancellationToken cancellationToken) { var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)), diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs index 22f175c..dfc7aed 100644 --- a/src/Anubis/Trading/PaperBroker.cs +++ b/src/Anubis/Trading/PaperBroker.cs @@ -446,13 +446,20 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable /// /// After an absence (SPEC 7.3): waiting purchases are cancelled; stops and sales that would have triggered are /// filled at their level, or at the open of the bar that already passed it. Bars come from the one-minute store. + /// With only the stretch before it, the rest at the next call. /// - public async Task CatchUpAsync(Func>> minuteBars, CancellationToken cancellationToken) + public async Task CatchUpAsync(Func>> minuteBars, CancellationToken cancellationToken, + DateTimeOffset? to = null) { ArgumentNullException.ThrowIfNull(minuteBars); var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); var from = book.SeenUntil; - var until = _clock.UtcNow; + var until = to ?? _clock.UtcNow; + if (until < from) + { + return 0; + } + var bars = new Dictionary>(StringComparer.Ordinal); foreach (var symbol in book.Orders.Where(o => IsOpen(o) && o.Request.Side == OrderSide.Sell).Select(o => o.Request.Symbol).Distinct(StringComparer.Ordinal)) { diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index b640d39..4bda061 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -172,6 +172,7 @@ public sealed partial class TradingService : IDisposable { _db = db ?? throw new ArgumentNullException(nameof(db)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _since = clock.UtcNow; _bus = bus ?? throw new ArgumentNullException(nameof(bus)); _secrets = secrets ?? throw new ArgumentNullException(nameof(secrets)); _market = market; @@ -362,6 +363,7 @@ public sealed partial class TradingService : IDisposable MarketOpen = MarketOpenAsync, PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), Splits = SplitsAsync, + RefreshSplits = _market is null || account.Broker != Venues.Alpaca ? null : (symbols, since, ct) => _market.RefreshCorporateActionsAsync(symbols, since, ct), AwaitingRebuild = account.Environment != TradingEnvironments.Simulation, AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false), Gate = Risk is null ? null : Risk.GateAsync, @@ -411,9 +413,20 @@ public sealed partial class TradingService : IDisposable } var accounts = new List(); + GuardState? before = null; foreach (var manager in _managers.Values) { - accounts.Add(await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false)); + var account = await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false); + if (manager.AwaitingRebuild) + { + // Its ledger may be older than the account: the guard keeps what the last state said, at its time, or nothing. + before ??= Supervision.GuardFiles.ReadState(GuardFiles); + account = before is not null && before.Installation == InstallationCode && before.Accounts.FirstOrDefault(a => a.AccountId == account.AccountId) is { } known + ? known with { WrittenAt = known.WrittenAt ?? before.WrittenAt } + : account with { Positions = [] }; + } + + accounts.Add(account); } Supervision.GuardFiles.WriteState(GuardFiles, new GuardState(_clock.UtcNow, InstallationCode, accounts)); @@ -443,19 +456,18 @@ public sealed partial class TradingService : IDisposable { if (manager.Broker is PaperBroker paper) { - await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); - await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); + await CatchUpAsync(manager, paper, cancellationToken).ConfigureAwait(false); } else { await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); Guard?.Step("esecuzioni dal broker " + name); await RebuildAsync(manager, cancellationToken).ConfigureAwait(false); - - // After the rebuild: a split or a dividend needs the quantities held at its date (SPEC 15.1). - await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); } + // After the executions of meanwhile: a split or a dividend needs the quantities held at its date (SPEC 15.1). + await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); + Guard?.Step("riconciliazione " + name); await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); Guard?.Step("ordini rimasti aperti " + name); @@ -469,33 +481,84 @@ public sealed partial class TradingService : IDisposable } } + /// The simulator's absence (SPEC 7.3), one stretch per split: the orders of before it meet the prices of before it. + internal async Task CatchUpAsync(OrderManager manager, PaperBroker paper, CancellationToken cancellationToken) + { + var splits = new List<(Instrument Instrument, CorporateAction Split)>(); + foreach (var id in (await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct()) + { + if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { IsCrypto: false } instrument) + { + continue; + } + + foreach (var split in await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false)) + { + if (!await AppliedAsync(manager.Account.AccountId, split.SourceKey, cancellationToken).ConfigureAwait(false)) + { + splits.Add((instrument, split)); + } + } + } + + foreach (var (instrument, split) in splits.OrderBy(s => s.Split.ExDate)) + { + await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken, OrderManager.ExDate(split)).ConfigureAwait(false); + await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false); + await manager.ApplySplitAsync(instrument, split, cancellationToken).ConfigureAwait(false); + } + + await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); + await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false); + } + /// /// SPEC 15.1: what the account did after the archive is written back before anything compares ledger and account. /// Finding something on a database nobody declared restored means it is an old copy put back by hand, or a dump: /// the protected restart starts here, as it would have after an import. /// - internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) => - manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct)); + internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) + { + var protectedNow = false; + try + { + await manager.RebuildAsync(cancellationToken, async ct => + { + await ProtectAsync(manager, ct).ConfigureAwait(false); + protectedNow = true; + }).ConfigureAwait(false); + } + finally + { + // "Ferma tutto" also where the other accounts are already at work. + foreach (var other in _managers.Values.Where(m => protectedNow && m != manager && AccountReady(m.Account.AccountId))) + { + await GuardAsync("ordini " + other.Account.Name, () => other.CancelWorkingAsync(Platform.Installation.ProtectedRestartReason, cancellationToken: cancellationToken), + cancellationToken).ConfigureAwait(false); + } + } + } + + // What was asked or begun before this moment may be of an old copy of the database; what comes after is of now. + private readonly DateTimeOffset _since; private async Task ProtectAsync(OrderManager manager, CancellationToken cancellationToken) { - if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true } - && await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken) - .ConfigureAwait(false) == "\"stopped\"") + if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true } + || await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken) + .ConfigureAwait(false) != "\"stopped\"") { - return; + await Platform.Installation.ProtectAsync(_db, _clock, _since, + $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.", + cancellationToken).ConfigureAwait(false); } - await Platform.Installation.ProtectAsync(_db, _clock, cancellationToken).ConfigureAwait(false); + // Also when an attempt cut right after the write had already protected: the names of the stops depend on it. var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); - foreach (var each in _managers.Values) + foreach (var each in _managers.Values.Append(manager)) { each.StopGeneration = generation; } - - await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "protected_restart", - $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.", - cancellationToken), cancellationToken).ConfigureAwait(false); } /// Zero until the first restore, then the moment of the last one. @@ -807,21 +870,32 @@ public sealed partial class TradingService : IDisposable /// public async Task MarkPositionsAsync(CancellationToken cancellationToken) { - var held = (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct().ToList(); - foreach (var id in held) + foreach (var held in (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).GroupBy(p => p.InstrumentId)) { - if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } instrument) + if (await _catalog.GetAsync(held.Key, cancellationToken).ConfigureAwait(false) is not { } instrument + || await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is not { Bid: > 0m, Ask: > 0m } quote || quote.Ask < quote.Bid) { continue; } - if (await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote && quote.Ask >= quote.Bid) + foreach (var account in held.GroupBy(p => p.AccountId)) { - await Ledger.MarkAsync(id, quote.Mid, cancellationToken).ConfigureAwait(false); + if (!await SharesOfAnotherTimeAsync(account.Key, instrument, account.Min(p => p.OpenedAt), cancellationToken).ConfigureAwait(false)) + { + await Ledger.MarkAsync(account.Key, held.Key, quote.Mid, cancellationToken).ConfigureAwait(false); + } } } } + /// + /// The quantity in the ledger is not the one today's price is about: an account not rebuilt yet, or a split still to be + /// applied. Valued all the same it would show a loss that is not there, and the limits of SPEC 9.2 would act on it. + /// + private async Task SharesOfAnotherTimeAsync(Guid accountId, Instrument instrument, DateTimeOffset openedAt, CancellationToken cancellationToken) => + _managers.TryGetValue(accountId, out var manager) && (manager.AwaitingRebuild || (!instrument.IsCrypto + && await PendingSplitAsync(accountId, instrument, cancellationToken).ConfigureAwait(false) is { } split && openedAt < OrderManager.ExDate(split))); + public async Task TickAllAsync(CancellationToken cancellationToken) { await RetryAccountsAsync(cancellationToken).ConfigureAwait(false); @@ -891,7 +965,7 @@ public sealed partial class TradingService : IDisposable } } - private async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken) + internal async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken) { if (manager.Account.Broker != Venues.Alpaca) { @@ -912,21 +986,28 @@ public sealed partial class TradingService : IDisposable // What was sold since still owes the dividends of when it was held: a rebuild or a long stop brings them late. var traded = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT instrument_id FROM fills WHERE account_id = @a AND executed_at >= @at", r => r.Id("instrument_id"), - ("a", manager.Account.AccountId), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false); - var held = new Dictionary(StringComparer.Ordinal); + ("a", manager.Account.AccountId), ("at", _clock.UtcNow - MarketDataService.SoldStillOwed)), cancellationToken).ConfigureAwait(false); + var owed = new Dictionary(StringComparer.Ordinal); foreach (var id in positions.Select(p => p.InstrumentId).Concat(traded).Distinct()) { if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument) { - held[instrument.Symbol] = instrument; + owed[instrument.Symbol] = instrument; } } - foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol))) + var held = positions.Select(p => p.InstrumentId).ToHashSet(); + foreach (var action in actions.Where(a => owed.ContainsKey(a.Symbol))) { - var instrument = held[action.Symbol]; + var instrument = owed[action.Symbol]; if (action.ChangesShares) { + // Only where something is held: a purchase not read yet must still find its split. + if (!held.Contains(instrument.Id)) + { + continue; + } + // The ledger and, on the simulator, the broker's book, together and once. await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); } @@ -937,8 +1018,6 @@ public sealed partial class TradingService : IDisposable } } - private static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90); - private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken) { var key = "div:" + action.SourceKey; diff --git a/tests/Anubis.Tests/FormatTests.cs b/tests/Anubis.Tests/FormatTests.cs index 2ae347c..acb3c02 100644 --- a/tests/Anubis.Tests/FormatTests.cs +++ b/tests/Anubis.Tests/FormatTests.cs @@ -92,6 +92,8 @@ public sealed class FormatTests Assert.AreEqual("mer 31 dic 2025", Format.ShortDate(new DateTimeOffset(2025, 12, 31, 10, 0, 0, TimeSpan.Zero), now, _rome)); Assert.AreEqual("Venerdì 9 ottobre 2026, ore 08:21", Format.LongDateTime(now, _rome)); Assert.AreEqual("12 agosto 2026", Format.LongDate(new DateOnly(2026, 8, 12))); + Assert.AreEqual("12 ago", Format.AxisDay(new DateOnly(2026, 8, 12), 58)); + Assert.AreEqual("ago 2026", Format.AxisDay(new DateOnly(2026, 8, 12), 900)); Assert.AreEqual("4 secondi fa", Format.Ago(TimeSpan.FromSeconds(4))); Assert.AreEqual("1 minuto fa", Format.Ago(TimeSpan.FromSeconds(65))); } diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs index 975543c..874fe1f 100644 --- a/tests/Anubis.Tests/LedgerTests.cs +++ b/tests/Anubis.Tests/LedgerTests.cs @@ -180,7 +180,7 @@ public sealed class LedgerTests .ConfigureAwait(false); } - await rig.Ledger.MarkAsync(instrument.Id, price, _none).ConfigureAwait(false); + await rig.Ledger.MarkAsync(account.AccountId, instrument.Id, price, _none).ConfigureAwait(false); await AssertBooksAsync(rig, account, strategy, step).ConfigureAwait(false); } } @@ -363,7 +363,7 @@ public sealed class LedgerTests // A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain. var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, StrategyNames.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false); - await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false); + await rig.Ledger.MarkAsync(okx.AccountId, btc.Id, 68000m, _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(5)); await book.TakeAsync(_none).ConfigureAwait(false); await capital.SetAsync(Venues.Okx, 8000m, "test", _none).ConfigureAwait(false); diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs index a8de6d2..e42be0c 100644 --- a/tests/Anubis.Tests/LiveStockSupport.cs +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -209,7 +209,7 @@ internal sealed class StockRig : IAsyncDisposable await MinutesAsync(3).ConfigureAwait(false); foreach (var symbol in Stocks) { - await Rig.Ledger.MarkAsync(_instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false); + await Rig.Ledger.MarkAsync(Alpaca.AccountId, _instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false); } await Equity.TakeAsync(none).ConfigureAwait(false); diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index 054c295..6bac5df 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -239,7 +239,7 @@ internal sealed class LiveRig : IAsyncDisposable foreach (var coin in Coins) { - await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false); + await Rig.Ledger.MarkAsync(Okx.AccountId, _instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false); } await Equity.TakeAsync(none).ConfigureAwait(false); diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs index 9849940..c850e1e 100644 --- a/tests/Anubis.Tests/RestoreServerTests.cs +++ b/tests/Anubis.Tests/RestoreServerTests.cs @@ -113,6 +113,28 @@ public sealed class RestoreServerTests } Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself."); + + // The true file comes back while a choice is at work, and the choice fails: it is not taken away. + using (await server.Host.ExclusiveAsync(CancellationToken.None)) + { + var db = server.Host.OpenForChoice(); + File.Copy(away, file); + Assert.IsFalse((await Migrations.StatusAsync(db, CancellationToken.None)).IsEmpty); + await server.Host.AbandonChoiceAsync(); + Assert.IsTrue(File.Exists(file), "The file that came back stays in its place."); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!)) + { + File.Delete(f); + } + + // What a choice began to write is another thing: it steps aside. + await Migrations.MigrateAsync(server.Host.OpenForChoice(), SystemClock.Instance, null, CancellationToken.None); + await server.Host.AbandonChoiceAsync(); + Assert.IsFalse(File.Exists(file)); + Assert.HasCount(1, Directory.GetFiles(Path.GetDirectoryName(file)!, "*.incompleto-*").Where(f => !f.EndsWith("-wal", StringComparison.Ordinal) && !f.EndsWith("-shm", StringComparison.Ordinal)).ToList()); + } + File.Copy(away, file); await server.WaitForAsync(HostMode.Ready); } diff --git a/tests/Anubis.Tests/RestoreTests.cs b/tests/Anubis.Tests/RestoreTests.cs index a447fdb..e14b003 100644 --- a/tests/Anubis.Tests/RestoreTests.cs +++ b/tests/Anubis.Tests/RestoreTests.cs @@ -325,6 +325,9 @@ public sealed class RestoreTests Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE reason = 'rebuilt from the broker'", r => r.Id("id")), "Interrupted after the orders."); Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value, "The protection comes before the first row."); + // One of them was cut right after its row: it still has no state. + await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET status = 'created', filled_quantity = 0 WHERE reason = 'rebuilt from the broker' AND purpose <> 'stop'", _none), _none); + // The last execution made it into the ledger: what comes before it is still to be read. var last = (await a.Paper.GetFillsAsync(DateTimeOffset.MinValue, _none)).MaxBy(f => f.ExecutedAt)!; await rig.Ledger.RecordFillAsync(new LedgerFill(a.Context.AccountId, a.Eth.Id, StrategyNames.CryptoTrend, last.ExecutionId, last.Side, last.Quantity, last.Price, last.Fee, @@ -333,6 +336,7 @@ public sealed class RestoreTests // The next attempt knows every order already, and finishes all the same. await service.RebuildAsync(manager, _none); await a.SameLedgerAsync(rig, "The ledger is the one that was lost, stops included."); + Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE status = 'created'", r => r.Id("id")), "Every rebuilt order has the state the broker says."); await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); await manager.AlignStopsAsync(_none); CollectionAssert.AreEqual(stops, (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList(), "No stop was touched."); @@ -474,14 +478,31 @@ public sealed class RestoreTests await using var restored = await rig.RestoreAsync(archive); await Installation.RenewAsync(restored.Db, new DataDirectory(Path.Combine(folder, "data")), restored.Clock, "Salvataggio ripristinato", _none); - var again = restored.Manager(broker, context, splits: SplitsAsync); + var asked = new List<(string Symbols, DateOnly Since)>(); + var photographs = new List(); + var down = true; + var again = restored.Manager(broker, context, splits: async (i, ct) => down ? [] : await SplitsAsync(i, ct), refreshSplits: (symbols, since, _) => + { + asked.Add((string.Join(',', symbols), since)); + return down ? throw new MarketDataException("rete giù") : Task.CompletedTask; + }, afterFills: async ct => photographs.Add((await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, ct))!.Quantity)); + again.AwaitingRebuild = true; again.StopGeneration = restored.Clock.UtcNow.UtcTicks; + var known = await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id")); + await Assert.ThrowsExactlyAsync(() => again.RebuildAsync(_none)); + Assert.IsTrue(again.AwaitingRebuild, "Without the splits nothing is replayed."); + Assert.HasCount(known.Count, await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id"))); + down = false; var report = await again.RebuildAsync(_none); + Assert.AreEqual(2, asked.Count(a => a == ("MSFT", new DateOnly(2026, 11, 9))), "Back to a day before the last execution of the archive."); + CollectionAssert.AreEqual(new[] { 22m }, photographs, "One photograph, when every split is in its place."); Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear)); var position = (await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!; Assert.AreEqual((22m, 180m), (position.Quantity, position.StopPrice)); Assert.IsEmpty(await restored.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_refused_fill'", r => r.Text("message"))); Assert.HasCount(1, await restored.QueryAsync("SELECT id FROM applied_actions WHERE source_key = 'split-msft'", r => r.Id("id"))); + await again.RebuildAsync(_none); + Assert.HasCount(2, asked, "Nothing new to write: no need to ask."); var reconciled = await new Reconciler(restored.Db, restored.Clock, restored.Ledger).ReconcileAsync(again, _none); Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message))); } @@ -491,12 +512,261 @@ public sealed class RestoreTests } } + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task StoppingAnAccountNotRebuiltYetKeepsTheStopOfAPurchase() + { + // The purchase filled and the engine died before reading it; "Ferma tutto" comes while the account waits. + await using var a = await Account.OpenAsync(); + a.Rig.Refresh(); + await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 57_000m, StartAggressive = true }, _none); + a.Broker.FailFillsAt = 2; + await Assert.ThrowsExactlyAsync(() => a.Manager.TickAsync(_none)); + a.Rig.Refresh(); + await a.Paper.PumpAsync(_none); + + var manager = a.Rig.Manager(a.Broker, a.Context); + manager.AwaitingRebuild = true; + Assert.IsEmpty(await manager.CancelWorkingAsync("manual_stop")); + await manager.RebuildAsync(_none); + Assert.HasCount(1, await manager.CancelWorkingAsync(LiveReasons.Restart)); + Assert.AreEqual(57_000m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice); + Assert.AreEqual(57_000m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ExecutionsOfWhileTheBotWasOffComeBeforeTheSplitsAndTheDividends() + { + await using var rig = await TradingRig.CreateAsync(); + var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")); + var nvda = await rig.InstrumentAsync(TradingRig.Stock("NVDA")); + var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false); + await paper.DepositAsync(100_000m, "USD", _none); + await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Demo); + using var service = Service(rig); + Task> SplitsAsync(Instrument i, CancellationToken ct) => rig.Db.ReadAsync>(async s => + [.. await s.QueryAsync("SELECT source_key FROM corporate_actions WHERE symbol = @s AND kind = 'split'", r => new CorporateAction(i.Symbol, "split", new DateOnly(2026, 11, 12), "test", r.Text("source_key")) { Ratio = 10m }, ("s", i.Symbol))], ct); + OrderManager Manager() => rig.Manager(broker, context, splits: SplitsAsync); + async Task TurnsAsync(OrderManager manager) + { + for (var i = 0; i < 3; i++) + { + rig.Refresh(); + await paper.PumpAsync(_none); + await manager.TickAsync(_none); + rig.Clock.Advance(_minute); + } + } + + Task<(Guid?, string?)> BuyAsync(OrderManager manager, Instrument instrument, decimal quantity) => manager.SubmitAsync( + new TradeIntent(instrument.Id, StrategyNames.EquityMomentum, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none); + + // 10 MSFT with their stop; NVDA bought and sold before, then bought again: filled, and the engine dies before reading it. + rig.Quote("MSFT", 399.9m, 400m); + rig.Quote("NVDA", 399.9m, 400m); + var first = Manager(); + await BuyAsync(first, msft, 10m); + await TurnsAsync(first); + await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD"), _none); + await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD"), _none); + rig.Clock.Advance(_minute); + await BuyAsync(first, nvda, 10m); + broker.FailFillsAt = 2; + await Assert.ThrowsExactlyAsync(() => first.TickAsync(_none)); + rig.Refresh(); + await paper.PumpAsync(_none); + + // Off: the stop of MSFT fires on Wednesday; Thursday, 10-for-1 for both and a dividend of MSFT. + rig.Clock.Advance(TimeSpan.FromDays(1)); + rig.Quote("MSFT", 350m, 350.1m); + await paper.PumpAsync(_none); + rig.Clock.Advance(TimeSpan.FromDays(1)); + rig.Quote("MSFT", 35m, 35.01m); + rig.Quote("NVDA", 40m, 40.01m); + await rig.Db.WriteAsync(async s => + { + foreach (var (symbol, kind, ratio, cash) in new[] { ("MSFT", "split", (decimal?)10m, (decimal?)null), ("NVDA", "split", 10m, null), ("MSFT", "cash_dividend", null, 1m) }) + { + await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, @s, @k, '2026-11-12', @r, @c, 'USD', 'test', @key, @now)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", symbol), ("k", kind), ("r", ratio), ("c", cash), ("key", kind + symbol), ("now", rig.Clock.UtcNow)); + } + }, _none); + + var second = Manager(); + second.AwaitingRebuild = true; + + var report = await second.RebuildAsync(_none); + Assert.AreEqual(0, report.Orders); + await service.CorporateActionsAsync(second, _none); + Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))?.Quantity ?? 0m, "The stop sold the 10 old shares."); + Assert.AreEqual(100m, (await rig.Ledger.PositionAsync(context.AccountId, nvda.Id, StrategyNames.EquityMomentum, _none))!.Quantity, "The purchase finds its split."); + Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")), "Sold before the ex-date: nothing is owed."); + Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id"))); + Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill' AND message LIKE '%Vend%MSFT%'", r => r.Id("id")), "The sale of the stop reaches the phone."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task TheRestOfAStopThatFiredInPartWhileOffIsSold() + { + await using var rig = await TradingRig.CreateAsync(); + var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")); + var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false); + await paper.DepositAsync(100_000m, "USD", _none); + await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Demo); + var first = rig.Manager(broker, context); + rig.Quote("MSFT", 399.9m, 400m); + await first.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 1.5m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none); + for (var i = 0; i < 3; i++) + { + rig.Refresh(); + await paper.PumpAsync(_none); + await first.TickAsync(_none); + rig.Clock.Advance(_minute); + } + + // The stop of the fraction is a day order and is over; that of the whole share fires while the bot is off. + var stops = await paper.GetOpenOrdersAsync(_none); + Assert.HasCount(2, stops); + await paper.CancelOrderAsync(stops.Single(o => o.Quantity == 0.5m).ClientOrderId, "MSFT", _none); + rig.Clock.Advance(TimeSpan.FromHours(1)); + rig.Quote("MSFT", 350m, 350.1m); + await paper.PumpAsync(_none); + + var second = rig.Manager(broker, context); + second.AwaitingRebuild = true; + await second.RebuildAsync(_none); + Assert.AreEqual(0.5m, (await rig.QueryAsync("SELECT quantity FROM executions WHERE purpose = 'protective' AND status = 'working'", r => r.Money("quantity"))).Single()); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task TheProtectiveSalesOfTheArchiveAreNotContinued() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none); + var simulated = await a.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation); + await a.Rig.Manager(a.Rig.Paper(PaperOptions.Okx(), simulated.AccountId, persist: false), simulated) + .SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none); + var (rig, _) = await a.RestoreAsync(await a.ArchiveAsync()); + async Task StatusAsync(Guid account) => (await rig.QueryAsync("SELECT status FROM executions WHERE account_id = @a AND purpose = 'protective'", r => r.Text("status"), ("a", account))).Single(); + Assert.AreEqual(ExecutionStates.Canceled, await StatusAsync(a.Context.AccountId)); + Assert.AreEqual(ExecutionStates.Working, await StatusAsync(simulated.AccountId), "The simulator went back in time with its sales."); + + // One of an execution that is over, still open on the account, is canceled there too. + a.Rig.Refresh(); + await a.Manager.CancelWorkingAsync("prova"); + await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none); + await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.004m, OrderPurpose.Exit, Ids.NewId(a.Rig.Clock)), _none); + await a.Manager.TickAsync(_none); + Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList()); + await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none); + await a.Rig.Manager(a.Broker, a.Context).RebuildAsync(_none); + Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList()); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ProtectionFromTheLoopStopsTheOtherAccountsAndKeepsWhatIsOfToday() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + + foreach (var (asked, kept) in new[] { ("2026-11-07T10:00:00+00:00", false), ("2026-12-31T10:00:00+00:00", true) }) + { + var rig = await a.Rig.RestoreAsync(archive); + a.Restored.Add(rig); + await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none); + using var service = Service(rig); + await service.StartAsync(_none); + var simulator = service.Managers.Single(m => m.Account.Broker == Venues.Okx); + rig.Clock.Advance(_minute); + var (buy, _) = await simulator.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(rig.Clock)), _none); + await AskCloseAllAsync(rig, asked); + var manager = rig.Manager(a.Broker, a.Context); + await service.RebuildAsync(manager, _none); + Assert.AreEqual(ExecutionStates.Canceled, (await rig.QueryAsync("SELECT status FROM executions WHERE id = @id", r => r.Text("status"), ("id", buy))).Single()); + var state = (await rig.QueryAsync("SELECT state FROM risk_state WHERE world = 'bot'", r => r.Json("state").Text)).Single(); + Assert.AreEqual(kept, System.Text.Json.JsonDocument.Parse(state).RootElement.GetProperty("close_all").GetBoolean(), asked); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); + } + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnAttemptCutRightAfterTheProtectionStillNamesTheStopsAnew() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + var rig = await a.Rig.RestoreAsync(archive); + a.Restored.Add(rig); + await Installation.ProtectAsync(rig.Db, rig.Clock, rig.Clock.UtcNow, "prova", _none); + using var service = Service(rig); + var manager = rig.Manager(a.Broker, a.Context); + await service.RebuildAsync(manager, _none); + Assert.AreEqual((await Installation.ReadRowAsync(rig.Db, _none))!.RenewedAt.UtcTicks, manager.StopGeneration); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AResumedRebuildOfTheGuardsStopsDoesNotStopTheBot() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single(); + await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none); + Task PlaceAsync(int sequence) => a.Paper.SubmitOrderAsync(new OrderRequest(ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, + OrderPurpose.Stop, "GGGGGGGG", sequence), a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity / 2m, TimeInForce.Gtc) + { StopPrice = 57_000m }, _none); + using var service = Service(a.Rig); + await PlaceAsync(1); + a.Broker.FailFillsAt = 2; + await Assert.ThrowsExactlyAsync(() => service.RebuildAsync(a.Manager, _none)); + await PlaceAsync(2); + await service.RebuildAsync(a.Manager, _none); + Assert.IsFalse((await Installation.ReadRowAsync(a.Rig.Db, _none))!.ProtectedRestart); + Assert.IsEmpty(await a.Rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task TheGuardCountsFromTheMomentTheFiguresOfTheAccountWereRead() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var known = await a.Manager.GuardAccountAsync(_none); + var read = a.Rig.Clock.UtcNow; + a.Rig.Clock.Advance(_minute); + await a.SellAsync(a.Btc, 0.004m); + var held = (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + await a.Paper.SubmitOrderAsync(new OrderRequest("a-mano", a.Btc.Symbol, OrderSide.Buy, OrderKind.Market, 0.5m, TimeInForce.Gtc), _none); + await a.TurnsAsync(a.Manager, 2); + foreach (var stop in await a.Paper.GetOpenOrdersAsync(_none)) + { + await a.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none); + } + + var state = new Anubis.Supervision.GuardState(a.Rig.Clock.UtcNow, TradingRig.Installation, [known with { WrittenAt = read }]); + var outcome = await Anubis.Supervision.GuardRepair.RunAsync(state, state.Accounts[0], a.Broker, a.Rig.Clock, _none); + Assert.AreEqual(held, outcome.Placed.Single().Quantity, "What was sold after the figures, not what the user holds."); + } + private static TradingService Service(TradingRig rig) => new(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp()); - private static Task AskCloseAllAsync(TradingRig rig) => rig.Db.WriteAsync(s => s.ExecuteAsync( + private static Task AskCloseAllAsync(TradingRig rig, string since = "2026-11-07T10:00:00+00:00") => rig.Db.WriteAsync(s => s.ExecuteAsync( "INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'bot', @j, @t, @t)", _none, - ("id", Ids.NewId(rig.Clock)), ("j", new DbJson("{\"close_all\":true,\"close_all_since\":\"2026-11-07T10:00:00+00:00\"}")), ("t", rig.Clock.UtcNow)), _none); + ("id", Ids.NewId(rig.Clock)), ("j", new DbJson($"{{\"close_all\":true,\"close_all_since\":\"{since}\"}}")), ("t", rig.Clock.UtcNow)), _none); private static async Task CloseAllAsync(TradingRig rig, OrderManager manager) { diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs index 681ec81..ea16025 100644 --- a/tests/Anubis.Tests/RiskEngineTests.cs +++ b/tests/Anubis.Tests/RiskEngineTests.cs @@ -503,7 +503,7 @@ public sealed class RiskEngineTests ("id", planned), ("a", live.Account.AccountId), ("i", s.Btc.Id), ("no", false), ("t", s.Rig.Clock.UtcNow)), _none); await Installation.CheckAsync(s.Rig.Db, new DataDirectory(TempFolder.Create("reconfirm")), s.Rig.Clock, _none); - await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, _none); + await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, s.Rig.Clock.UtcNow, "prova", _none); // Stopped, exit only, with its counts untouched; what was planned does not leave; the stop stays. Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value); diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs index 5c58158..4cb6901 100644 --- a/tests/Anubis.Tests/TradingServiceTests.cs +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -92,6 +92,10 @@ public sealed class TradingServiceTests await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, source, source_key, created_at) VALUES (@id, 'MSFT', 'split', '2026-11-11', @r, 'test', 'k', @now)", _none, ("id", Ids.NewId(rig.Clock)), ("r", 2m), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromDays(2)); + service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow)); + await service.PhotographAsync(_none).ConfigureAwait(false); + Assert.AreEqual(400m, (await service.Ledger.PositionAsync(paper.Account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice, + "Old shares at the price of the new ones would be a loss that is not there."); var before = http.Requests.Count; await service.CorporateActionsAsync(_none).ConfigureAwait(false); await service.ReconcileAllAsync(_none).ConfigureAwait(false); @@ -170,6 +174,10 @@ public sealed class TradingServiceTests Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); rig.Clock.Advance(TimeSpan.FromDays(1)); + service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow)); + await service.PhotographAsync(_none).ConfigureAwait(false); + Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice, + "The split is not applied yet: the photograph waits for it."); await service.CorporateActionsAsync(_none).ConfigureAwait(false); await service.CorporateActionsAsync(_none).ConfigureAwait(false); var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!; @@ -189,4 +197,139 @@ public sealed class TradingServiceTests await service.PhotographAsync(_none).ConfigureAwait(false); Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice); } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSimulatorsAbsenceMeetsASplitAtItsDate() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + using var service = Service(rig, new FakeHttp()); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); + await service.StartAsync(_none).ConfigureAwait(false); + var manager = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca); + var paper = (PaperBroker)manager.Broker; + await paper.DepositAsync(10_000m, "USD", _none).ConfigureAwait(false); + await service.Ledger.RecordCapitalAsync(manager.Account.AccountId, StrategyNames.EquityMomentum, 10_000m, "USD", "test", _none).ConfigureAwait(false); + await manager.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none) + .ConfigureAwait(false); + for (var i = 0; i < 6; i++) + { + service.Quotes.Put(new Quote("MSFT", 399.9m, 400m, rig.Clock.UtcNow)); + await paper.PumpAsync(_none).ConfigureAwait(false); + await manager.TickAsync(_none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromSeconds(20)); + } + + Assert.HasCount(1, await paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)); + + // Off. Wednesday it falls through the stop and comes back; Thursday 2-for-1 and a dividend. + var day = new DateTimeOffset(2026, 11, 11, 16, 0, 0, TimeSpan.Zero); + await new BarStore(rig.Db, rig.Clock).UpsertMinuteAsync(msft.Id, [new Bar(day, 365, 366, 350, 364, 1000), new Bar(day.AddDays(1), 199, 201, 198, 200, 1000)], "test", BarQuality.Ok, _none) + .ConfigureAwait(false); + await rig.Db.WriteAsync(async s => + { + foreach (var (kind, ratio, cash) in new[] { ("split", (decimal?)2m, (decimal?)null), ("cash_dividend", null, 1m) }) + { + await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, 'MSFT', @k, '2026-11-12', @r, @c, 'USD', 'test', @k, @now)", + _none, ("id", Ids.NewId(rig.Clock)), ("k", kind), ("r", ratio), ("c", cash), ("now", rig.Clock.UtcNow)).ConfigureAwait(false); + } + }, _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromDays(3)); + await service.CatchUpAsync(manager, paper, _none).ConfigureAwait(false); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + + Assert.IsEmpty(await service.Ledger.PositionsAsync(manager.Account.AccountId, _none).ConfigureAwait(false), "The stop of before the split met the prices of before it."); + Assert.IsEmpty(await paper.GetPositionsAsync(_none).ConfigureAwait(false)); + Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task UntilItIsRebuiltTheGuardKeepsWhatItKnewOfAnAccount() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var folder = TempFolder.Create("guard-state"); + try + { + var paths = new Anubis.Supervision.GuardPaths(folder); + var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{}", System.Net.HttpStatusCode.BadRequest)); + using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32], + new Dictionary { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" }), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None, + new Guid("0193a7c0-0000-7000-8000-0000000000aa"), http) + { GuardFiles = paths }; + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); + await service.StartAsync(_none).ConfigureAwait(false); + var account = service.Managers.Single(m => m.Account.Environment == TradingEnvironments.Demo).Account; + await service.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); + + // Nor is it valued at a price of today: the shares of the ledger may be those of another time. + service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow)); + await service.PhotographAsync(_none).ConfigureAwait(false); + Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice); + async Task<(DateTimeOffset At, Anubis.Supervision.GuardAccount Account)> WrittenAsync() + { + await service.WriteGuardStateAsync(_none).ConfigureAwait(false); + var state = Anubis.Supervision.GuardFiles.ReadState(paths)!; + return (state.WrittenAt, state.Accounts.Single(a => a.AccountId == account.AccountId)); + } + + Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions, "Nothing known: no stop is put on a ledger that may be old."); + + // What the last state said, with its time, however often it is written again. + var first = rig.Clock.UtcNow; + var known = (await WrittenAsync().ConfigureAwait(false)).Account with { Positions = [new Anubis.Supervision.GuardPosition(msft.Id, "MSFT", StrategyNames.EquityMomentum, 4m, 380m, 0.0001m, false, "KKKKKKKK", 3)] }; + Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, service.InstallationCode, [known with { WrittenAt = null }])); + for (var i = 0; i < 2; i++) + { + rig.Clock.Advance(TimeSpan.FromSeconds(10)); + var (at, again) = await WrittenAsync().ConfigureAwait(false); + Assert.AreEqual(rig.Clock.UtcNow, at); + Assert.AreEqual((4m, first), (again.Positions.Single().Quantity, again.WrittenAt!.Value)); + } + + // Of another installation: not of this account's past. + Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, "OTHR", [known])); + Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task SplitsAndDividendsAreAskedAlsoForWhatLeftTheUniverse() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{\"corporate_actions\":{},\"next_page_token\":null}")); + var bus = new EventBus(); + var secrets = new SecretStore(rig.Db, rig.Clock, new byte[32], new Dictionary { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" }); + using var market = new MarketDataService(rig.Db, rig.Clock, bus, new SettingsStore(rig.Db, rig.Clock, bus), secrets, null, http); + await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false); + Assert.IsEmpty(http.Requests, "Nothing to ask about."); + + var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + foreach (var (symbol, sold) in new[] { ("MSFT", false), ("NVDA", true), ("OLDX", true) }) + { + var stock = await rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false); + var buy = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD"); + var sell = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD"); + var at = rig.Clock.UtcNow - TimeSpan.FromDays(symbol == "OLDX" ? 120 : 30); + await rig.Ledger.RecordFillAsync(buy with { ExecutedAt = at }, _none).ConfigureAwait(false); + if (sold) + { + await rig.Ledger.RecordFillAsync(sell with { ExecutedAt = at.AddDays(1) }, _none).ConfigureAwait(false); + } + } + + await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false); + StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNVDA&"); + StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-11-03&"); + await market.RefreshCorporateActionsAsync(["NEWX"], new DateOnly(2026, 10, 20), _none).ConfigureAwait(false); + StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNEWX%2CNVDA&"); + StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-10-13&"); + } } diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index e9c953f..5f0957e 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -114,7 +114,8 @@ internal sealed class TradingRig : IAsyncDisposable } public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func>? marketOpen = null, - Func>? pendingSplit = null, Func>>? splits = null) + Func>? pendingSplit = null, Func>>? splits = null, + Func, DateOnly, CancellationToken, Task>? refreshSplits = null, Func? afterFills = null) { var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync) { @@ -123,6 +124,8 @@ internal sealed class TradingRig : IAsyncDisposable MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)), PendingSplit = pendingSplit, Splits = splits, + RefreshSplits = refreshSplits, + AfterFills = afterFills, }; _owned.Add(manager); return manager;