Merge pull request 'Fase 6 — Motore dal vivo in simulazione' (#92) from fase-6 into main
ci / test (postgres) (push) Successful in 10m0s
ci / test (sqlite) (push) Successful in 4m48s
ci / image (push) Successful in 1m31s

This commit was merged in pull request #92.
This commit is contained in:
Alby96 committed 2026-11-11 22:30:53 +01:00
commit 7291f5d15b
71 files changed
+9857 -267

No files matched your search

+3
View File
@@ -63,3 +63,6 @@ jobs:
git checkout -q FETCH_HEAD
- name: Build image (no publish)
run: docker build -f deploy/docker/Dockerfile -t anubis:ci .
# The guard drill inside the image (issue #48): offline, its own SQLite database in a temporary folder.
- name: Guard drill in the image
run: docker run --rm anubis:ci drill
+8 -2
View File
@@ -6,14 +6,19 @@ WORKDIR /src
COPY global.json Directory.Build.props Directory.Packages.props ./
COPY src/Anubis/Anubis.csproj src/Anubis/packages.lock.json src/Anubis/
COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json src/Anubis.Server/
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode
COPY src/Anubis.Guard/Anubis.Guard.csproj src/Anubis.Guard/packages.lock.json src/Anubis.Guard/
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode && \
dotnet restore src/Anubis.Guard/Anubis.Guard.csproj --locked-mode
COPY src/Anubis/ src/Anubis/
COPY src/Anubis.Server/ src/Anubis.Server/
COPY src/Anubis.Guard/ src/Anubis.Guard/
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
COPY docs/design/logo/ docs/design/logo/
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
COPY docs/backtests/ docs/backtests/
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
@@ -27,7 +32,8 @@ ENV ANUBIS_PLATFORM=docker \
PGID=100
EXPOSE 8787
VOLUME /data
# Starts as root only to give /data to PUID:PGID, then runs the app as that user (entrypoint.sh).
# Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts
# the engine. "docker run --rm <image> drill" runs the guard drill instead (issue #48).
# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy.
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
+3 -2
View File
@@ -1,9 +1,10 @@
#!/bin/sh
# Container start (SPEC 15.2, issue #16). As root: prepare /data for PUID:PGID (99:100 on Unraid), then drop to that
# user with setpriv, which is part of the base image (no gosu). Started as another user (docker run --user): go straight on.
# The process is the guard (SPEC 9.3, ADR 0012): it starts the engine, watches it and passes the stop on to it.
set -eu
app="/app/Anubis.Server.dll"
app="/app/Anubis.Guard.dll"
if [ "$(id -u)" != "0" ]; then
exec dotnet "$app" "$@"
@@ -19,7 +20,7 @@ case "$uid$gid" in
esac
mkdir -p /data
for folder in db models research import backups logs web-keys; do
for folder in db models research import backups logs web-keys guard; do
mkdir -p "/data/$folder"
done
# Only what does not already belong to PUID:PGID, so a large data folder does not slow every start.
+2
View File
@@ -7,6 +7,8 @@ services:
context: .
dockerfile: deploy/docker/Dockerfile
image: gitea.encke-hake.ts.net/balbosoft/anubis:dev
# The guard gives the engine up to 55 seconds to close in order (SPEC 9.3).
stop_grace_period: 60s
ports:
- "8787:8787"
environment:
+18 -18
View File
@@ -13,9 +13,9 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Completata |
| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Completata (azioni in attesa delle chiavi Alpaca) |
| 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) | Da fare |
| 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Da fare |
| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Da fare |
| 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 |
@@ -184,25 +184,25 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta.
**Lavori**
- [ ] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione
- [ ] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri
- [ ] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6)
- [ ] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot"
- [ ] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema
- [ ] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita
- [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale
- [x] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione
- [x] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri
- [x] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6)
- [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot"
- [x] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema
- [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita
- [x] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale
- [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6`
**Criteri di accettazione**
- [ ] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi
- [ ] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati
- [ ] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker
- [ ] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono
- [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca)
- [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px)
- [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale
- [ ] I comandi Telegram funzionano (o, senza token, superano i test con un finto server)
- [x] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi (`TheLiveEngineMakesTheSameTradesAsTheBacktest` su 40 giorni di `crypto_trend`, `TheStockSideMakesTheSameTradesAsTheBacktest` su 6 settimane di `equity_meanrev`)
- [x] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati (`TenDaysWithFaultsEndReconciledWithoutDuplicateOrders`: 14 giorni con rete giù, risposta persa, ripartenza con un ordine a metà e database irraggiungibile, su SQLite e PostgreSQL)
- [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm <immagine> drill` in `tasks ci` e nella CI: 7 controlli su 7)
- [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`)
- [x] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) — partita l'11/11/2026 alle 21:44 nel container `anubis-prova`; il rapporto si verifica in Fase 7 (#55)
- [x] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) (`TheDemoPanoramicaShowsAccountsPositionsAndLimits`; fotografie di `tasks screenshots`, confronto nella prova di #51)
- [x] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale (`TheDiaryFiltersAndSearches`; a 390 px `scrollWidth` uguale alla larghezza su `/`, `/diario` e `/diario?cerca=…`)
- [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests`
## Fase 7 — Notizie
+20 -6
View File
@@ -4,7 +4,7 @@ Aggiornato: 2026-11-11
## Fase corrente
**Fase 5 — Strategie, portafoglio, rischio: completata.** La prossima è la Fase 6 (Motore dal vivo in simulazione), da iniziare con il via dell'utente. Nessuna delle tre strategie è ancora in simulazione: `crypto_trend` non ha superato il backtest e le due azionarie aspettano le chiavi di Alpaca. Restano in attesa delle chiavi demo di OKX e di Alpaca anche le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2).
**Fase 6 — Motore dal vivo in simulazione: completata.** La prova di durata di 48 ore è partita a fine fase, l'11 novembre 2026 alle 21:44 (ora italiana), sull'immagine Docker di questo PC (solo crypto, senza chiavi); il suo rapporto si controlla come primo passo della Fase 7 (Notizie), da iniziare con il via dell'utente. 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
@@ -77,6 +77,14 @@ Aggiornato: 2026-11-11
- Stadi verso i soldi veri: osservazione, simulazione, reale ridotto, reale. Senza la procedura di 12.4 nessun ordine raggiunge un conto reale; una strategia retrocessa gestisce le uscite delle posizioni reali fino a zero; il gemello simulato resta fuori dai totali. In simulazione entra solo una strategia che ha superato il backtest.
- Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 32,8% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio.
- Schermate Operazioni (con la scheda "perché" e l'esportazione CSV), Strategie e Rischio come i mockup 03, 04 e 07; in Impostazioni limiti, protezione per le operazioni in giornata e scenari. Fermare, chiudere e ripartire passano dal motore del rischio; alzare un limite mentre una strategia usa soldi veri chiede frase e password.
- **Fase 6** (scelte nell'ADR 0012):
- Motore dal vivo: ogni decisione passa dalla stessa chiamata del backtest (`DecideOnce`), agli orari di 5.5. Ogni decisione ha una chiave scritta nella stessa transazione dei suoi ordini pianificati e delle righe del diario, quindi una ripartenza non decide né manda niente due volte. Parità con il backtest provata su 40 giorni di `crypto_trend` e 6 settimane di `equity_meanrev`; 14 giorni con guasti iniettati finiscono riconciliati e senza ordini doppi.
- Recupero dopo un'assenza (5.6): l'assenza si misura dall'ultimo lavoro finito. I lavori persi si rifanno una volta o si saltano con il motivo. Le decisioni in ritardo aggiornano solo le uscite. Un'assenza di più di un giorno resta in Panoramica finché non la vedi.
- Processo di guardia: in Docker è il processo principale e il genitore del motore. Interviene dopo due minuti di silenzio, un avvio fermo dieci minuti o un'uscita senza preavviso. Annulla gli ordini a metà, rimette gli stop, avvisa e fa ripartire il motore. La terza ripartenza forzata in un'ora scrive il file STOP. La prova (`drill`) gira anche dentro l'immagine, in `tasks ci` e nella CI.
- Diario con le frasi fisse dell'appendice B e confronto "senza bot" (40% BTC, 60% SPY, ogni versamento investito nel suo giorno).
- Telegram: coda con stato, nuovi tentativi e abbandono dopo un giorno; comandi dal telefono solo dalla chat configurata e solo se recenti, `/ferma` con `/conferma`; riepilogo del mattino, stato facoltativo, segnale di vita ogni minuto. Sezione in Impostazioni.
- Schermate Panoramica e Diario e sistema come i mockup 01, 08 e 09.
- `anubis soak`: il rapporto di una prova di durata, letto dai registri del bot mentre lavora.
## In corso
@@ -84,12 +92,17 @@ Nulla.
## Prossimo passo
Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il processo di guardia, il recupero dopo un'assenza, il Diario, Panoramica, Telegram e la prova di durata di 48 ore. Con le chiavi del conto paper di Alpaca si possono fare i backtest azionari (`anubis backtest base`) e chiudere i criteri in attesa delle Fasi 2 e 3.
1. Controllare il rapporto della prova di durata, da venerdì 13 novembre dopo le 22:45 (ora italiana), così la finestra comprende per intero le sedute USA di giovedì e venerdì. Il container è `anubis-prova`, l'ora di partenza è in `artifacts/prova-48h/inizio.txt`:
`docker exec -u 99:100 -e HOME=/tmp anubis-prova dotnet /app/Anubis.Server.dll soak --from 2026-11-11T20:44:31Z --hours 49 --platform docker --out /tmp/prova.md`
poi `docker cp anubis-prova:/tmp/prova.md docs/prova-di-durata-fase-6.md` (issue #55).
2. Poi la Fase 7, notizie. 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.
## Da sapere
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
- La modalità dimostrativa mostra solo le parti già costruite: strategie e notizie della Panoramica arrivano con le loro fasi. Nella demo il motore di trading è spento.
- La modalità dimostrativa mostra le schermate costruite fin qui. Notizie e apprendimento appaiono solo con i dati dell'appendice F: fuori dalla demo arrivano con le Fasi 7 e 8. Nella demo il motore di trading e Telegram sono spenti.
- In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo.
- La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4).
- Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata.
- Il capitale affidato si decide in euro in Impostazioni → Conti e chiavi. Finché non c'è, le strategie osservano soltanto.
- `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`.
@@ -97,7 +110,7 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
- Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta (ADR 0010, punto 13); i backtest delle strategie di base li convertono in euro con il cambio BCE del giorno (ADR 0011, punto 10).
- `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti.
- Il motore dal vivo (Fase 6) deve far girare una strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati.
- Il motore dal vivo fa girare ogni strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati.
- Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati).
- Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove.
- I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti.
@@ -109,11 +122,12 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc
| Cosa | Da quando serve | Senza |
|---|---|---|
| Via libera per la Fase 6 | Subito | Non si parte |
| Via libera per la Fase 7 | Subito | Non si parte |
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; 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 |
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
| 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 |
| Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale |
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
+11
View File
@@ -90,6 +90,17 @@ Apri la radice del repository in VS Code con l'estensione C# (`ms-dotnettools.cs
Le attività `check`, `test` e `dev` sono anche in Terminale → Esegui attività. L'estensione è dell'editor, non del progetto: non entra nell'elenco dell'ADR 0004.
## Guardia e prova di durata
- In Docker il processo principale è la guardia (`Anubis.Guard.dll`), che avvia il server come processo figlio (ADR 0012). Fuori da Docker, con `tasks dev` o da VS Code, il server gira da solo, senza guardia.
- La prova della guardia blocca davvero il motore con una vendita a metà e controlla che tutto torni a posto:
- `dotnet run --project src/Anubis.Guard -- drill` sul computer;
- `docker run --rm <immagine> drill` dentro l'immagine.
La fanno anche `tasks ci` e la CI.
- Il rapporto di una prova di durata si legge mentre il bot lavora: `docker exec -u 99:100 -e HOME=/tmp <container> dotnet /app/Anubis.Server.dll soak --hours 48 --platform docker`, con l'utente del bot (`PUID:PGID`) perché i file del database restino suoi. Esce con 0 se tutto è regolare e con 4 se qualcosa va guardato. Senza `--from` la finestra sono le ultime `--hours` ore; con `--from` comincia lì e dura `--hours` ore, che sono anche la durata minima richiesta.
- Gli appigli per le prove (`ANUBIS_FAULT`, `ANUBIS_DRILL_OKX_URL`) non si usano mai su un'installazione vera.
## Pacchetti e consegne
- **Docker**: immagine `gitea.encke-hake.ts.net/balbosoft/anubis`, pubblicata dalla CI sui tag `v*` nella sezione Packages del repository (ADR 0002). I tag `fase-N` non pubblicano nulla.
+148
View File
@@ -0,0 +1,148 @@
# 0012 — Scelte della Fase 6: motore dal vivo in simulazione
Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 5.5, 5.6, 7.4, 7.5, 9.3, 9.4, 13, 14) e gli ADR 0009–0011, senza aggiungere componenti esterni
## Contesto
La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il recupero dopo un'assenza, il processo di guardia, il diario con le frasi dell'appendice B, Telegram con il segnale di vita, le schermate Panoramica e Diario e sistema, e la prova di durata in tempo reale. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
## Decisione
**1. Il motore dal vivo decide con la stessa chiamata del backtest.**
- Ogni decisione passa da `DecideOnce`, la stessa funzione che usa il motore di backtest, così prova e simulazione non possono divergere. Il test di parità lo controlla su 40 giorni di `crypto_trend` e su 6 settimane di `equity_meanrev`, con correttivi e rischio attivi.
- Gli orari sono quelli di 5.5:
- chiusura crypto alle 00:05 UTC;
- segnali azionari 20 minuti dopo la chiusura di Wall Street;
- uscite di `equity_meanrev` 5 minuti prima della chiusura;
- ordini azionari e stop del giorno all'apertura.
- Una strategia gira con i parametri scritti nel suo file dell'esito (`parameters`), cioè quelli che si sono qualificati, non con quelli predefiniti.
- Il motore parte dal pianificatore solo dopo che i conti sono stati riconciliati.
**2. Ogni decisione si prende una volta sola, anche attraverso le ripartenze.**
- La decisione ha una chiave (`run_key`: strategia e chiusura su cui decide). Questa chiave viene scritta nella stessa transazione delle righe di decisione, degli ordini pianificati e delle righe del diario: o c'è tutto o non c'è niente.
- L'id di ogni ordine pianificato è l'id della decisione dell'intenzione, e da lì viene la chiave dell'ordine. Una ripartenza che trova l'esecuzione già presente non la manda una seconda volta.
- Gli ordini azionari decisi dopo la chiusura aspettano l'apertura nella tabella `planned_orders`. Ognuno ha una scadenza e un prezzo di riferimento.
- La prova accelerata copre 14 giorni con un guasto diverso nei giorni indicati: rete giù, una risposta persa, una ripartenza con un ordine a metà e il database irraggiungibile. Su SQLite e PostgreSQL termina riconciliata e senza ordini doppi.
**3. Il recupero dopo un'assenza (5.6).**
- L'assenza si misura all'avvio dall'ultimo lavoro finito (`jobs.last_finished_at`). Sotto i 5 minuti è una ripartenza, non un'assenza.
- Ogni assenza va nel diario. Una più lunga di un giorno resta in cima alla Panoramica finché l'utente non l'ha vista.
- Ogni lavoro dichiara cosa fare con le esecuzioni perse:
- salvataggio, cambi, calendario di borsa e pulizia girano una volta alla ripartenza, comunque in ritardo;
- un lavoro con una scadenza si salta dopo quella scadenza, e il diario lo dice.
- Le azioni societarie si leggono prima che la riconciliazione rimetta gli stop.
- Una decisione presa in ritardo per l'assenza va nel diario come recuperata. Un'entrata il cui prezzo si è mosso troppo o che è scaduta si lascia cadere, con il suo motivo.
**4. La guardia è il processo principale e il genitore del motore (9.3, 9.4).**
- In Docker il punto d'ingresso è `Anubis.Guard.dll`, che avvia `Anubis.Server.dll` come processo figlio con gli stessi argomenti.
- I due processi parlano su una pipe locale con nome (`ANUBIS_GUARD_PIPE`), un messaggio JSON per riga:
- il motore manda il battito, i passi dell'avvio, le chiavi dei conti (tenute solo in memoria) e gli stop che decide;
- la guardia manda solo "stop".
- La guardia interviene in tre casi:
- due minuti senza battito;
- un avvio fermo sullo stesso passo per dieci minuti;
- un'uscita del motore senza preavviso.
- Un salto dell'orologio oltre 30 secondi (computer sospeso) non conta come silenzio.
- Quando interviene, la guardia:
1. ferma il motore;
2. annulla i nostri acquisti e le nostre vendite rimasti aperti sui conti di prova;
3. rimette gli stop che le posizioni richiedono, leggendoli dal file di stato che il motore scrive ogni dieci secondi;
4. scrive una nota e avvisa l'utente;
5. fa ripartire il motore.
- La terza ripartenza forzata in un'ora scrive il file STOP.
- Gli stop rimessi dalla guardia saltano 500 numeri di sequenza (`GuardRepair.SequenceGap`), così il loro id non si scontra mai con uno che il motore stava per mandare.
- Alla ripartenza il motore, prima di riconciliare:
- adotta gli stop della guardia;
- annulla gli ordini che aveva lasciato aperti (motivo `restart`);
- pianifica di nuovo le uscite già decise, che seguono così le regole di 5.6.
- Lo stop del container (SIGTERM) passa al motore, che chiude in ordine e non viene fatto ripartire. Il compose e il template Unraid concedono 60 secondi; la guardia ne aspetta 55.
- **I conti reali per ora sono fuori dalla guardia.** La guardia apre solo conti di prova. Avrà i conti reali con la fase dei soldi veri, quando riceverà anche la procedura di avvio di 12.4. Oggi nessuna strategia usa soldi veri.
- La guardia usa il runtime condiviso di ASP.NET (`FrameworkReference`): server e guardia stanno così nella stessa cartella `/app` dell'immagine, con le stesse librerie.
**5. La prova della guardia ha due appigli, solo per la prova.**
- `ANUBIS_FAULT=hang-mid-sale` blocca il ciclo principale subito dopo l'invio di una vendita. La guardia non lo passa mai al motore che fa ripartire.
- `ANUBIS_DRILL_OKX_URL` indirizza il conto OKX della prova a un finto OKX. Funziona solo con indirizzi locali (loopback).
- La prova (`Anubis.Guard drill`) gira con processi veri in una cartella temporanea, anche dentro l'immagine Docker: lo fanno `tasks ci` e la CI. Fa sette controlli:
- la guardia è intervenuta;
- il motore è ripartito;
- la vendita era partita;
- la vendita rimasta a metà è stata annullata;
- lo stop è tornato per l'intera quantità;
- la vendita già decisa è ripartita con un ordine nuovo;
- la nota è nel diario.
**6. Il diario si scrive con frasi fisse.**
- Le frasi nel tono dell'appendice B vengono da modelli (`DiaryText`) riempiti solo con ciò che è successo: esecuzioni con il risultato dell'operazione che chiudono, stop alzati, chiusura crypto, segnali azionari, segnali in osservazione, recupero e assenza.
- Le frasi dei codici motivo stanno nella libreria (`ReasonCatalog`), condivise da motore e schermate. Un test controlla che ogni codice abbia la sua frase.
- I generi del diario sono quelli della schermata: Ordini, Decisioni, Sistema, Notizie, Apprendimento.
**7. Il confronto "senza bot" (7.5).**
- Ogni movimento di capitale viene investito nel suo giorno: 40% in BTC/EUR e 60% in SPY rettificato, convertito con il cambio BCE. Poi non si tocca più.
- Un prelievo vende i due nella proporzione che hanno raggiunto.
- I prezzi sono le chiusure del giorno prima, così un versamento non sembra mai un guadagno.
- Senza lo storico di SPY (niente chiavi Alpaca) la fotografia lascia vuoto il confronto, invece di mostrarne metà.
**8. Telegram (14).**
- Ogni avviso va prima in coda (`notifications`), nella stessa transazione di ciò che racconta, e poi si spedisce. Il passo di spedizione gira ogni dieci secondi e manda al massimo 20 messaggi.
- Ogni messaggio ha uno stato: in attesa, spedito, oppure non riuscito con il suo errore.
- Rete giù e 429 si riprovano dopo 1, 2, 4… fino a 60 minuti, o dopo l'attesa indicata da Telegram se è più lunga; al massimo 8 tentativi.
- Un rifiuto di Telegram è definitivo.
- Un messaggio che non è partito entro un giorno si abbandona con il motivo, invece di arrivare tardi come se fosse una notizia.
- I comandi si leggono con il long polling. Valgono solo:
- dalla chat configurata (le altre si ignorano in silenzio);
- se hanno meno di 5 minuti, così un /pausa di ieri non mette in pausa oggi.
- `/ferma` chiede `/conferma` entro due minuti; qualsiasi altro comando nel frattempo la annulla.
- Ripartire dopo "Ferma tutto", i soldi veri, i limiti e le chiavi restano nell'interfaccia.
- Lavori in programma:
- riepilogo del mattino alle 08:00, recuperabile entro quattro ore;
- stato ogni ora o alle 20:00, solo se l'impostazione `telegram.status` lo chiede.
- Nella modalità dimostrativa Telegram è spento.
- Il passo Telegram del primo avvio resta in Impostazioni → Telegram: la pagina del primo avvio non ha ancora un database dove tenere i segreti. Quella pagina lo dice, e sul desktop raccomanda il segnale di vita.
**9. Il segnale di vita.** Ogni minuto, se c'è un indirizzo, il bot chiama un servizio esterno (per esempio un controllo di Healthchecks.io).
- L'indirizzo viene da `ANUBIS_HEARTBEAT_URL`, oppure dal segreto `HEARTBEAT_URL` impostato da Impostazioni.
- È il servizio esterno ad avvisare se le chiamate smettono: copre il caso in cui bot e guardia sono spenti insieme.
**10. Panoramica e Diario e sistema (13.6).**
- Le prossime mosse vengono dai lavori del pianificatore che sono mosse del bot; i lavori a intervallo (ogni minuto, ogni 5 minuti) non compaiono. Gli eventi del calendario economico tra le mosse ci sono solo nella demo, che usa i valori dell'appendice F.10; fuori dalla demo la riga "Prossima decisione" dice "tra X, alle HH:MM".
- Notizie e Apprendimento, fuori dalla demo, dicono "non ancora attivo" fino alle Fasi 7 e 8.
- Il Diario filtra per genere con semplici collegamenti, senza JavaScript. Il filtro Rischio raccoglie i codici del motore del rischio e quelli di ordini o stop rifiutati, chiavi con prelievo, conto prudente, intervento della guardia e salto dell'orologio. La ricerca ignora maiuscole e accenti, guarda le ultime 5.000 righe e ne mostra al massimo 200. "Mostra i giorni precedenti" aggiunge 7 giorni e compare solo se ci sono righe più vecchie.
- Non esiste ancora una pagina per una singola operazione: "Perché l'ho comprata e venduta" porta a Operazioni filtrata su quel titolo, dove la scheda "perché" si apre.
- Il computer che lo ospita: il processore è la quota di questo processo dall'ultima lettura; la memoria è quella del processo sul limite che .NET vede (nel container, il limite del container); lo spazio è quello del disco della cartella dei dati.
- "Scarica i registri tecnici" (`/api/registri.zip`) chiede l'accesso e mette nello zip solo i file `anubis-*.log` della cartella dei registri, già oscurati quando sono stati scritti.
**11. La prova di durata.**
- `anubis soak` legge i registri del bot su una finestra di tempo e scrive un rapporto, senza cambiare niente. Può girare mentre il bot lavora, in Docker con `docker exec`. I suoi controlli:
- durata coperta;
- bot al lavoro dall'inizio alla fine (vedi il punto 12);
- nessun ordine né decisione doppia;
- nessuna differenza inspiegata e ultima riconciliazione in regola per ogni conto;
- nessuno spegnimento;
- nessun intervento della guardia;
- una decisione `crypto_trend` per ogni chiusura giornaliera.
- La prova gira sull'immagine Docker di questo PC, con un volume suo, senza chiavi: conto crypto sul simulatore interno con prezzi veri di OKX, nessuna parte azionaria.
- `crypto_trend` non ha superato il backtest (ADR 0011, punto 13), quindi resta in osservazione: decide ogni notte, ma non manda ordini. Non la porto in simulazione per far vedere ordini: sarebbe aggirare il suo esito. Gli ordini, le ripartenze e i guasti sono coperti dalla prova accelerata (punto 2) e dalla prova della guardia (punto 5).
**12. Correzioni dopo la revisione indipendente.** Una revisione del codice della fase ha trovato nove difetti; le correzioni scelte sono queste.
- **Un conto parte solo quando è in ordine.** All'avvio ogni conto prima adotta gli stop messi dalla guardia, poi controlla la chiave, si riconcilia, riprende o annulla ciò che era rimasto a metà e allinea gli stop. Solo se tutto riesce il conto è "pronto". Finché non lo è, il motore non decide su di lui e non gli manda ordini pianificati; il ciclo riprova l'avvio ogni minuto. Prima, un broker che non rispondeva all'avvio lasciava il conto lavorare su un registro non riconciliato.
- **Gli stop della guardia si adottano prima di tutto il resto.** La nota della guardia si cancella solo quando ogni stop che ha messo risulta nel registro degli ordini; se l'adozione si interrompe, la nota resta e si riprova.
- **Un turno di conto ha un tempo massimo**: 45 secondi per il giro degli ordini, 60 per un nuovo avvio. Un broker lento non tiene più fermo il segnale di vita per i due minuti dopo i quali la guardia interviene: il turno si interrompe, si scrive nel registro e si riprova al giro dopo. Un motore davvero bloccato resta in silenzio e la guardia lo sente.
- **Il segnale di vita guarda anche il pianificatore.** Se il pianificatore, dove girano le decisioni, tace da 30 minuti (i suoi lavori più lunghi durano pochi minuti), il ciclo degli ordini smette di battere e la guardia interviene.
- **Le uscite alla chiusura di `equity_meanrev` sono ordini pianificati**, scritti nella stessa transazione che prende la chiave della decisione, con scadenza alla chiusura della sessione. Il rilascio li manda subito; una vendita con scadenza parte già aggressiva (limite vicino al prezzo opposto). Prima venivano mandate direttamente: un riavvio a metà poteva perderle o mandarle due volte.
- **La ripresa trova anche l'ordine pianificato non ancora collegato** alla sua esecuzione (riavvio tra l'invio e la scrittura del collegamento), dalla chiave dell'ordine, e lo chiude prima di ripianificare il resto.
- **Una decisione azionaria fatta dopo l'apertura** (per esempio dopo un'assenza) è segnata in ritardo e segue le regole del recupero.
- **I cicli di Telegram non si fermano per un errore inatteso** (database occupato, rete): scrivono nel registro e riprovano.
- **Lo spegnimento lungo si vede in Panoramica** (SPEC 5.6): un avviso in cima dice per quanto il bot è rimasto spento e rimanda al diario, finché l'utente non preme "Ho visto".
- **Una decisione in ritardo aspetta i suoi dati.** Dopo uno spegnimento, al primo battito i dati del giorno prima non sono ancora arrivati: una decisione fatta dopo le 12:00 UTC li chiede e li aspetta fino a 30 minuti, invece di chiudersi subito come "senza dati" e andare persa. Il difetto si è visto all'avvio della prova di durata.
- **Il rapporto della prova di durata non conta più le righe di riconciliazione**, che si scrivono solo quando c'è una differenza. Legge invece:
- quando i lavori in programma hanno cominciato e quando hanno finito l'ultima volta;
- gli spegnimenti, scritti a ogni ripartenza dopo almeno 5 minuti;
- gli interventi della guardia, per un ciclo fermo con il processo vivo;
- lo stato di ogni conto: riconciliato negli ultimi 15 minuti della finestra e in modalità normale.
- Il segnale di vita in `http://` è accettato solo verso indirizzi della rete di casa (10.x, 172.16-31.x, 192.168.x, locali e i loro equivalenti IPv6); il rapporto della prova di durata non conta una chiusura giornaliera avvenuta meno di 30 minuti prima della fine della finestra.
## Conseguenze
- Un riavvio, un crash o un'assenza non producono decisioni né ordini doppi: le chiavi e le transazioni lo garantiscono, e i test lo provano su entrambi i motori.
- I conti reali, quando arriveranno, avranno bisogno che anche la guardia sappia aprirli: è scritto qui per non dimenticarlo.
- Il rapporto della prova di durata si controlla come primo passo della Fase 7.
+2
View File
@@ -4,6 +4,8 @@
<RootNamespace>Anubis.Guard</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- The same shared runtime as the engine: in the image both live in /app (ADR 0012). -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\Anubis\Anubis.csproj" />
</ItemGroup>
</Project>
+49 -3
View File
@@ -1,3 +1,49 @@
// Placeholder: the guard process (SPEC 9.3) arrives in phase 6 (ADR 0003).
await Console.Error.WriteLineAsync("Anubis.Guard non è ancora disponibile: arriva nella Fase 6.").ConfigureAwait(false);
return 2;
using System.Collections;
using System.Runtime.InteropServices;
using Anubis.Core;
using Anubis.Platform;
using Anubis.Supervision;
// The guard (SPEC 9.3, ADR 0012): the main process of the container and the parent of the engine. Its arguments go to
// the engine as they are. "drill" runs the guard drill in a temporary folder instead.
if (args is ["drill", ..])
{
return await GuardDrill.RunAsync(GuardLaunch.Server(), Console.Out, CancellationToken.None).ConfigureAwait(false);
}
var environment = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var paths = new GuardPaths(DataRoot(args, environment));
var logger = new LineLogger(Console.Out.WriteLine);
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
var clock = SystemClock.Instance;
var guardian = new Guardian(paths, clock, new GuardOptions(),
start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start),
(account, keys) => GuardBrokers.Create(http, clock, account, keys),
(text, keys, ct) => GuardBrokers.AlertAsync(http, logger, keys, text, ct),
logger);
// The stop of the container (SIGTERM) or Ctrl+C: passed on to the engine, which closes in order and is not restarted.
using var shutdown = new CancellationTokenSource();
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop);
using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop);
return await guardian.RunAsync(shutdown.Token).ConfigureAwait(false);
void Stop(PosixSignalContext context)
{
context.Cancel = true;
shutdown.Cancel();
}
// The engine's data folder: --data-dir when given, /data in Docker, the user's folder on desktop (SPEC 15.2, 15.6).
static string DataRoot(string[] args, Dictionary<string, string?> environment)
{
var index = Array.IndexOf(args, "--data-dir");
if (index >= 0 && index + 1 < args.Length)
{
return Path.GetFullPath(args[index + 1]);
}
var platform = Array.IndexOf(args, "--platform") is var p and >= 0 && p + 1 < args.Length ? args[p + 1] : environment.GetValueOrDefault("ANUBIS_PLATFORM");
return platform == "docker" ? "/data" : DataDirectory.ForCurrentUser().Root;
}
+110 -10
View File
@@ -5,6 +5,7 @@ using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Supervision;
using Anubis.Trading;
namespace Anubis.Server;
@@ -38,7 +39,7 @@ internal sealed record HostChanged(HostMode Mode);
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler,
MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null);
MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null, TelegramServices? Telegram = null);
/// <summary>
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
@@ -55,6 +56,9 @@ internal sealed partial class AnubisHost(
ILogger<AnubisHost> logger,
ServerOverrides? overrides = null) : BackgroundService
{
/// <summary>A scheduler silent this long is stuck: the engine stops beating, so the guard steps in.</summary>
public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30);
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
private readonly Lock _gate = new();
@@ -66,16 +70,22 @@ internal sealed partial class AnubisHost(
private CancellationTokenSource? _schedulerStop;
private MarketDataService? _market;
private TradingService? _trading;
private TelegramServices? _telegram;
private Laboratory? _lab;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
public StartupConfig Config { get; private set; } = initialConfig;
/// <summary>The channel to the guard that started this engine (SPEC 9.3); null without one.</summary>
public GuardLink? Guard { get; init; }
public bool IsDemo => options.Demo;
public HostStatus Status => _status;
public IClock Clock => clock;
/// <summary>The running services; null until the first successful start.</summary>
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
@@ -176,6 +186,12 @@ internal sealed partial class AnubisHost(
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
}
// With trading the beat of a running engine comes from the trading loop, so a blocked loop is noticed.
if (_status.Mode != HostMode.Ready || _trading is null)
{
Guard?.Beat();
}
await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false);
}
@@ -213,6 +229,7 @@ internal sealed partial class AnubisHost(
}
Config.Data.Ensure();
Guard?.Step("database");
// A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20).
_db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile));
@@ -234,6 +251,8 @@ internal sealed partial class AnubisHost(
return;
}
Guard?.Step("migrazioni e identità");
// Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays
// empty, so a backup taken with an older schema can still be restored into it.
var backups = new Backups(Config.Data, clock);
@@ -271,6 +290,7 @@ internal sealed partial class AnubisHost(
return;
}
Guard?.Step("servizi");
var key = Config.SecretKey.GetOrCreateKey();
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
@@ -288,12 +308,24 @@ internal sealed partial class AnubisHost(
var scheduler = new Scheduler(clock, bus);
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger)
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger,
Guard is null ? null : GuardDrill.DrillOkx(environment))
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct),
Path.Combine(Config.Data.Root, "STOP"))
{
Guard = Guard,
GuardFiles = Guard is null ? null : new GuardPaths(Config.Data.Root),
// The drill's fault is honored only under a guard, which never passes it to an engine it restarts.
Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable),
// The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take
// minutes), and the guard must hear it (SPEC 9.3).
OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence,
}
: null;
if (_trading is not null)
{
@@ -311,8 +343,33 @@ internal sealed partial class AnubisHost(
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
StartScheduler(scheduler, backups);
// Telegram and the sign of life (SPEC 14): not in the demo, and in tests only with their fake network.
_telegram = options.Demo || (overrides is not null && overrides.TelegramHttp is null)
? null
: new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram);
// Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6).
var lastDues = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
try
{
if (!options.Demo)
{
await new AbsenceBook(_db, clock) { Zone = Config.TimeZone }.RecordAsync(cancellationToken).ConfigureAwait(false);
}
foreach (var (name, due) in await _db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE last_due_at IS NOT NULL",
r => (r.Text("name"), r.Moment("last_due_at"))), cancellationToken).ConfigureAwait(false))
{
lastDues[name] = due;
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogStepFailed(logger, ex);
}
StartScheduler(scheduler, backups, lastDues);
SetStatus(HostMode.Ready, null);
}
@@ -431,14 +488,15 @@ internal sealed partial class AnubisHost(
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
private void StartScheduler(Scheduler scheduler, Backups backups)
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
{
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2) });
foreach (var job in (_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []))
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
{
scheduler.Add(job);
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
_schedulerStop = new CancellationTokenSource();
@@ -446,6 +504,7 @@ internal sealed partial class AnubisHost(
var market = _market;
var trading = _trading;
var lab = _lab;
var telegram = _telegram;
_schedulerLoop = Task.Run(async () =>
{
using var runs = bus.Subscribe<JobRun>();
@@ -453,6 +512,7 @@ internal sealed partial class AnubisHost(
var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token);
var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token);
var testing = lab is null ? Task.CompletedTask : RunLabAsync(lab, token);
var writing = telegram is null ? Task.CompletedTask : RunTelegramAsync(telegram, token);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
@@ -464,6 +524,7 @@ internal sealed partial class AnubisHost(
await collecting.ConfigureAwait(false);
await dealing.ConfigureAwait(false);
await testing.ConfigureAwait(false);
await writing.ConfigureAwait(false);
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
@@ -498,6 +559,21 @@ internal sealed partial class AnubisHost(
}
}
private async Task RunTelegramAsync(TelegramServices telegram, CancellationToken cancellationToken)
{
try
{
await telegram.RunAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
LogTelegramFailed(logger, ex);
}
}
private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken)
{
try
@@ -525,7 +601,13 @@ internal sealed partial class AnubisHost(
{
await _db!.WriteAsync(async s =>
{
var description = _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
var description = run.Description ?? _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
if (AbsenceBook.MissedLine(run with { Description = description }, Config.TimeZone) is { } line)
{
await Diary.WriteAsync(s, clock, DiaryKinds.System, run.Outcome == JobOutcome.Completed ? "job_recovered" : "job_skipped", line,
new { job = run.Name, due = run.DueUtc }, cancellationToken).ConfigureAwait(false);
}
var updated = await s.ExecuteAsync(
"UPDATE jobs SET last_due_at = @d, last_started_at = @s, last_finished_at = @f, last_outcome = @o, last_error = @e, updated_at = @f WHERE name = @n",
("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc), ("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error), ("n", run.Name)).ConfigureAwait(false);
@@ -571,6 +653,8 @@ internal sealed partial class AnubisHost(
_trading = null;
_lab?.Dispose();
_lab = null;
_telegram?.Dispose();
_telegram = null;
}
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
@@ -582,6 +666,19 @@ internal sealed partial class AnubisHost(
var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1;
var since = previous.Mode == mode ? previous.Since : clock.UtcNow;
_status = new HostStatus(mode, detail, identity, since, attempts);
if (mode == HostMode.Ready)
{
// Trading tells the guard by itself when its own startup steps are done.
if (_trading is null || _trading.IsStarted)
{
Guard?.Set(GuardStages.Running);
}
}
else
{
Guard?.Set(mode == HostMode.Starting ? GuardStages.Starting : GuardStages.Waiting);
}
if (previous.Mode != mode)
{
LogMode(logger, mode);
@@ -610,6 +707,9 @@ internal sealed partial class AnubisHost(
[LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")]
private static partial void LogMarketDataFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Telegram stopped")]
private static partial void LogTelegramFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Laboratory stopped")]
private static partial void LogLabFailed(ILogger logger, Exception exception);
+136
View File
@@ -522,6 +522,123 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.events dt { color: var(--text-3); }
.limits-form { max-width: none; margin-bottom: 8px; }
/* ---- Panoramica, under the top block (mockup 01) ---- */
.phone-only { display: none !important; }
.next-decision { display: flex; align-items: flex-start; gap: 10px; color: var(--text-2); font-size: 14px; }
.next-decision .icon { margin-top: 2px; color: var(--text-3); }
.overview-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; align-items: stretch; }
.overview-row-wide { grid-template-columns: minmax(0, 1.85fr) minmax(0, 1fr); align-items: start; }
.overview-empty { grid-column: span 2; display: flex; flex-direction: column; gap: 8px; color: var(--text-2); }
.overview-account { display: flex; flex-direction: column; }
.overview-account h2 { font-size: 15px; line-height: 22px; }
.overview-account .account-value { margin: 12px 0 0; gap: 12px; }
.overview-account .account-equity { font-size: 28px; line-height: 34px; }
.split-bar.thin { height: 8px; margin-top: 16px; }
.split-key { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 10px; color: var(--text-2); font-size: 13px; }
.split-key > span { display: inline-flex; align-items: center; }
.split-key .swatch { width: 9px; height: 9px; margin-right: 4px; }
.split-key .swatch:last-of-type { margin-right: 8px; }
.split-key strong { color: var(--text); font-weight: 600; margin-left: 6px; font-variant-numeric: tabular-nums; }
.month { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); }
.month > div { display: flex; flex-direction: column; }
.month strong { font-weight: 650; font-variant-numeric: tabular-nums; }
.spark-mini { width: 120px; height: 36px; flex: none; overflow: visible; }
.spark-mini polyline { fill: none; stroke: var(--text-2); stroke-width: 1.5; stroke-linejoin: round; }
.spark-mini circle { fill: var(--text); }
.overview-account > .note { margin-top: 14px; }
.status-pill { display: inline-flex; align-items: center; gap: 6px; font-size: 13.5px; font-weight: 600; }
.status-pill.attention { color: var(--attention); }
.overview-risk { display: flex; flex-direction: column; }
.overview-risk .panel-head { margin-bottom: 10px; }
.overview-risk > .note { margin-top: 14px; }
.overview-risk .more { margin-top: 10px; align-self: flex-start; }
.limit-list { display: flex; flex-direction: column; gap: 12px; }
.limit { display: flex; flex-direction: column; gap: 6px; }
.limit-line { display: flex; justify-content: space-between; gap: 12px; color: var(--text-2); font-size: 13.5px; font-variant-numeric: tabular-nums; }
.limit-line strong { color: var(--text); font-weight: 650; }
.usage.notched { overflow: visible; }
.notch { position: absolute; top: -4px; width: 2px; height: 14px; margin-left: -1px; background: var(--text); border-radius: 1px; }
.panel-head h2 .note { margin-left: 8px; }
.overview-positions { padding-bottom: 6px; }
.strategy-list { list-style: none; margin: 0; padding: 0; }
.strategy-list li { display: flex; flex-direction: column; gap: 4px; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); }
.strategy-list li:first-child { padding-top: 4px; }
.strategy-line { display: flex; justify-content: space-between; gap: 12px; font-variant-numeric: tabular-nums; }
.strategy-line strong { display: inline-flex; align-items: center; font-weight: 650; }
.strategy-bar { display: block; height: 8px; margin: 4px 0 6px; }
.strategy-bar span { display: block; height: 100%; border-radius: 4px; }
.info-note { margin-top: 18px; padding: 12px 16px; border-radius: 10px; background: var(--info-bg); color: var(--link); font-size: 13.5px; }
.overview-tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 28px; align-items: start; }
.tile .panel-head { margin-bottom: 8px; }
.tile h2 { font-size: 15px; }
.news-list { list-style: none; margin: 0; padding: 0; }
.news-list li { display: flex; flex-direction: column; gap: 4px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
.news-list li:first-child { padding-top: 4px; }
.news-list li:last-child { border-bottom: 0; }
.news-list strong { font-weight: 600; }
.news-list .attention { align-items: flex-start; font-size: 13.5px; }
.news-list .attention .icon { margin-top: 2px; }
.news-list .muted { font-size: 13.5px; }
.tile > p + .limit { margin-top: 14px; }
.tile-facts { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; margin: 16px 0 0; padding-top: 12px; border-top: 1px solid var(--rule-inner); font-size: 13.5px; }
.tile-facts dt { color: var(--text-2); }
.tile-facts dd { margin: 0; text-align: right; font-weight: 600; }
.system-tiles { list-style: none; margin: 0; padding: 0; }
.system-tiles li { display: grid; grid-template-columns: 16px auto minmax(0, 1fr); gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--rule-inner); font-size: 13.5px; }
.system-tiles li:last-child { border-bottom: 0; }
.system-tiles .muted { text-align: right; }
.ok > .icon { color: var(--gain); }
.warn > .icon { color: var(--attention); }
.off > .icon { color: var(--text-3); }
.phone-list { list-style: none; margin: 0; padding: 0; }
.phone-list li { display: flex; justify-content: space-between; gap: 12px; padding: 14px 0; border-top: 1px solid var(--rule-inner); }
.phone-list li > span { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.phone-list .num { align-items: flex-end; text-align: right; font-variant-numeric: tabular-nums; }
.phone-list .sub { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: 14px; }
.phone-list .sub.gain, .phone-list strong.gain { color: var(--gain); }
.phone-list .sub.loss, .phone-list strong.loss { color: var(--loss); }
.phone-list .swatch { margin-right: 0; }
.phone-list .dot.down { background: var(--loss); }
/* ---- Diario e sistema (mockup 08) ---- */
.journal-columns { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 24px; align-items: start; }
.journal { padding: 24px 26px; }
.journal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; }
.journal-search { flex: 0 1 330px; }
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 8px; }
.chip { display: inline-flex; align-items: center; min-height: 32px; padding: 0 14px; border: 1px solid var(--control); border-radius: 999px; color: var(--text); text-decoration: none; font-size: 14px; }
.chip:hover { background: var(--surface-2); }
.chip.on { background: var(--text); border-color: var(--text); color: var(--surface); font-weight: 550; }
.journal-found { margin-top: 12px; }
.panel h3.journal-day { margin: 28px 0 0; padding-bottom: 10px; border-bottom: 2px solid var(--text); font-size: 14.5px; }
.journal-list { list-style: none; margin: 0; padding: 0; }
.journal-list li { display: grid; grid-template-columns: 44px 22px minmax(0, 1fr) auto; gap: 12px; align-items: start; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
.journal-list time { color: var(--text-3); font-variant-numeric: tabular-nums; }
.journal-icon { color: var(--text-2); margin-top: 1px; }
.attention-entry .journal-icon { color: var(--attention); }
.journal-text { min-width: 0; display: flex; flex-direction: column; gap: 4px; overflow-wrap: anywhere; }
.journal-text strong { font-weight: 650; }
.journal-rest { color: var(--text-2); }
.journal-kind { color: var(--text-3); font-size: 13.5px; text-align: right; }
.journal-more { display: flex; justify-content: center; margin-top: 18px; }
.journal-side { display: flex; flex-direction: column; gap: 24px; min-width: 0; }
.journal-side .panel-head { margin-bottom: 4px; }
.system-parts { list-style: none; margin: 0; padding: 0; }
.system-parts li { display: flex; align-items: flex-start; gap: 12px; padding: 12px 0; border-top: 1px solid var(--rule-inner); }
.system-parts li > .icon { margin-top: 2px; }
.system-parts li > span { display: flex; flex-direction: column; min-width: 0; }
.system-parts strong { font-weight: 600; }
.system-parts li > span > span { color: var(--text-2); }
.job-list li { grid-template-columns: 96px minmax(0, 1fr); }
.job-list li:last-child { border-bottom: 0; }
.host { display: flex; flex-direction: column; gap: 12px; }
.host > h2 { margin-bottom: 0; }
.host .btn { align-self: flex-start; }
@media (max-width: 1180px) {
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.overview-row-wide, .journal-columns { grid-template-columns: minmax(0, 1fr); }
}
/* ---- Service pages ---- */
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
@@ -601,3 +718,22 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.bottom-item.active { background: var(--surface-2); color: var(--text); font-weight: 650; }
.nav-item, .btn, .more-list a { min-height: 44px; }
}
/* Panoramica and Diario on the phone: mockup 09, and mockup 08 stacked in one column */
@media (max-width: 760px) {
.desk-only { display: none !important; }
.cells > .cell-extra { display: none; }
section.phone-only, div.phone-only, ul.phone-only { display: block !important; }
a.phone-only { display: inline-block !important; }
span.phone-only { display: inline !important; }
.overview-row, .overview-row-wide, .overview-tiles { grid-template-columns: minmax(0, 1fr); gap: 14px; }
.half-next .moves { margin-top: 4px; border-top: 1px solid var(--rule); }
.phone-list li:last-child { padding-bottom: 4px; }
.journal { padding: 18px; }
.journal-search { flex: 1 1 100%; }
.journal-list li { grid-template-columns: 40px 18px minmax(0, 1fr); gap: 4px 10px; }
.journal-kind { grid-column: 3; text-align: left; font-size: 12.5px; line-height: 16px; }
.chip { min-height: 40px; }
.journal-side { gap: 14px; }
.job-list li { grid-template-columns: 84px minmax(0, 1fr); }
}
+131 -60
View File
@@ -5,86 +5,157 @@
<PageTitle>Diario e sistema · Anubis</PageTitle>
<div class="columns">
<section class="panel">
<h2>Diario</h2>
@if (_entries.Count == 0)
@{
var d = _diary;
var s = _system;
}
<div class="journal-columns">
<section class="panel journal" aria-labelledby="diario">
<div class="journal-head">
<h2 id="diario">Diario</h2>
<form class="search journal-search" method="get" action="/diario" role="search">
@if (d.Filter != "tutto")
{
<input type="hidden" name="tipo" value="@d.Filter" />
}
<Icon Name="search" Size="16" />
<label class="visually-hidden" for="cerca-diario">Cerca nel diario</label>
<input id="cerca-diario" type="search" name="cerca" value="@d.Search" placeholder="Cerca nel diario" maxlength="100" />
</form>
</div>
<nav class="chips" aria-label="Tipo di voce">
@foreach (var (key, label, _) in DiaryView.Filters)
{
<a href="@d.Link(filter: key, range: DiaryView.DefaultRange)" class="chip @(key == d.Filter ? "on" : null)" aria-current="@(key == d.Filter ? "true" : null)">@label</a>
}
</nav>
@if (d.Search is { } search)
{
<p class="note">Ancora nessuna voce.</p>
<p class="note journal-found">
@(d.Days.Sum(x => x.Entries.Count) switch { 0 => "Nessuna voce", 1 => "Una voce", var n => $"{n} voci" }) con «@search»@(d.Truncated ? $", le {DiaryView.MaxSearchResults} più recenti" : "").
<a href="@(new DiaryView([], d.Filter, null, DiaryView.DefaultRange, false, false).Link())">Togli la ricerca</a>
</p>
}
else
@if (d.IsEmpty && d.Search is null)
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Tipo</th><th scope="col">Voce</th></tr></thead>
<tbody>
@foreach (var e in _entries)
{
<tr><td class="nowrap">@Format.ShortDate(e.At, Shell.Now, Shell.Zone)</td><td>@e.Kind</td><td>@e.Text</td></tr>
}
</tbody>
</table>
</div>
<p class="note">@(d.Filter == "tutto" ? "Ancora nessuna voce. Qui il bot scrive ogni decisione, ordine e controllo, in parole semplici, appena succede." : "Nessuna voce di questo tipo finora.")</p>
}
@foreach (var day in d.Days)
{
<h3 class="journal-day">@day.Heading</h3>
<ol class="journal-list">
@foreach (var e in day.Entries)
{
<li class="@(e.Attention ? "attention-entry" : null)">
<time datetime="@e.At.ToString("o", CultureInfo.InvariantCulture)">@TimeZoneInfo.ConvertTime(e.At, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)</time>
<Icon Name="@e.Icon" Size="18" Class="journal-icon" />
<div class="journal-text">
<p>@if (e.Lead is { } lead) {<strong>@lead</strong>}@foreach (var piece in e.Main) {if (piece.Class is { } css) {<strong class="@css">@piece.Text</strong>} else {@piece.Text}}</p>
@if (e.Rest is { } rest)
{
<p class="journal-rest">@rest</p>
}
@if (e.Trade is { } trade)
{
<a href="/operazioni?cerca=@Uri.EscapeDataString(trade)">Perché l'ho comprata e venduta</a>
}
</div>
<span class="journal-kind">@e.Kind</span>
</li>
}
</ol>
}
@if (d.HasOlder)
{
<div class="journal-more"><a class="btn" href="@d.Link(range: d.Range + 7)">Mostra i giorni precedenti</a></div>
}
</section>
<section class="panel">
<h2>Sistema</h2>
<dl class="facts">
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")</dd>
<dt>Database</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde</dd>
<dt>In funzione da</dt><dd>@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)</dd>
</dl>
<h3 class="list-title">Lavori in programma</h3>
<ul class="moves">
@foreach (var job in _upcoming)
{
<li><span class="move-time">@Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)</span><span>@job.Description</span></li>
}
</ul>
@if (_jobs.Count > 0)
{
<h3 class="list-title">Ultimi lavori</h3>
<ul class="moves moves-past">
@foreach (var job in _jobs)
<div class="journal-side">
<section class="panel" aria-labelledby="sistema">
<div class="panel-head">
<h2 id="sistema">Come sta il sistema</h2>
<span class="status-pill @(s.AllWell ? "gain" : "attention")"><Icon Name="@(s.AllWell ? "check" : "alert")" Size="16" />@(s.AllWell ? "Tutto regolare" : "Qualcosa da controllare")</span>
</div>
<ul class="system-parts">
@foreach (var part in s.Parts)
{
<li><span class="move-time">@(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")</span><span>@job.Description: @Outcome(job.Outcome)</span></li>
<li class="@PartClass(part.State)">
<Icon Name="@PartIcon(part.State)" Size="16" />
<span><strong>@part.Name</strong><span>@part.Detail</span></span>
</li>
}
</ul>
}
</section>
</section>
<section class="panel" aria-labelledby="lavori">
<h2 id="lavori">Lavori in programma</h2>
@if (s.Jobs.Count == 0)
{
<p class="note">Nessun lavoro in programma: il pianificatore parte con il motore.</p>
}
else
{
<ul class="moves job-list">
@foreach (var job in s.Jobs)
{
<li><span class="move-time">@job.Time</span><span>@job.Text</span></li>
}
</ul>
}
</section>
<section class="plain host" aria-labelledby="computer">
<h2 id="computer">Il computer che lo ospita</h2>
@foreach (var r in s.Resources)
{
<div class="limit">
<div class="limit-line"><span>@r.Label</span><span><strong>@r.Value</strong>@if (r.Of is { } of) {<span class="muted"> su @of</span>}</span></div>
<span class="usage @(r.Share >= 0.85m ? "high" : null)"><span style="width: @Css(r.Share * 100m)%"></span></span>
</div>
}
<p class="note">@s.Running</p>
<a class="btn" href="/api/registri.zip" download><Icon Name="download" Size="18" />Scarica i registri tecnici</a>
</section>
</div>
</div>
@code {
private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
private IReadOnlyList<UpcomingRun> _upcoming = [];
private DateTimeOffset _since;
private DiaryView _diary = null!;
private SystemView _system = null!;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "tipo")]
public string? Tipo { get; set; }
[SupplyParameterFromQuery(Name = "cerca")]
public string? Cerca { get; set; }
[SupplyParameterFromQuery(Name = "giorni")]
public string? Giorni { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
(_entries, _jobs) = await services.Db.ReadAsync(async s =>
{
var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200",
r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message")));
var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC",
r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome")));
return (entries, jobs);
}, ct);
_upcoming = services.Scheduler.Upcoming(10);
_since = Host.Status.Since;
_diary = await DiaryView.LoadAsync(Host.Services!.Db, Tipo, Cerca, Giorni, Shell.Now, Shell.Zone, ct);
_system = await SystemView.LoadAsync(Host, Shell, ct);
}
private static string Outcome(string? outcome) => outcome switch
private static string PartClass(PartState state) => state switch
{
"succeeded" => "fatto",
"failed" => "non riuscito",
"skipped" => "saltato, orario superato",
_ => "in attesa",
PartState.Ok => "ok",
PartState.Warn => "warn",
_ => "off",
};
private static string PartIcon(PartState state) => state switch
{
PartState.Ok => "tick",
PartState.Warn => "alert",
_ => "clock",
};
private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
}
@@ -23,6 +23,11 @@
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
"limiti" => "Limiti di rischio salvati.",
"rischio" => "Impostazione del rischio salvata.",
"telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.",
"telegram-prova" => "Messaggio di prova partito: controlla il telefono.",
"telegram-tolto" => "Telegram tolto: non ti scrivo più finché non lo rimetti.",
"segnale" => "Segnale di vita salvato: la prima chiamata è andata bene, da adesso lo chiamo ogni minuto.",
"segnale-tolto" => "Segnale di vita tolto.",
_ => "Fatto.",
})</p>
@@ -33,7 +38,7 @@
}
<nav class="tabs" aria-label="Sezioni delle impostazioni">
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
</nav>
<section class="panel" id="aspetto">
@@ -186,6 +191,93 @@
}
</section>
<section class="panel" id="telegram">
<h2>Telegram e segnale di vita</h2>
<p class="hint">Su Telegram ti scrivo il riepilogo del mattino, ogni acquisto e vendita con il risultato, gli avvisi di rischio, i blocchi e gli errori. Dalla stessa chat accetto /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (con conferma) e /aiuto; da altre chat nessun comando. Soldi veri, limiti e chiavi non si cambiano da Telegram.</p>
<dl class="facts">
<dt>Token del bot</dt><dd>@KeyState(_telegramToken)</dd>
<dt>Chat</dt><dd>@KeyState(_telegramChat)</dd>
<dt>Ultimo messaggio partito</dt><dd>@(_queue?.LastSentAt is { } sent ? Format.ShortDate(sent, Shell.Now, Shell.Zone) : "Nessuno")</dd>
@if (_queue is { } q && (q.Pending > 0 || q.Retrying > 0 || q.GaveUp > 0))
{
<dt>In attesa</dt><dd>@q.Pending in coda@(q.Retrying > 0 ? $", {q.Retrying} da ritentare" : "")@(q.GaveUp > 0 ? $", {q.GaveUp} non partiti" : "")</dd>
}
@if (_queue?.LastError is { } lastError)
{
<dt>Ultimo errore</dt><dd class="loss">@lastError</dd>
}
</dl>
@if (Shell.IsDemo)
{
<p class="hint">Nella modalità dimostrativa Telegram non si usa.</p>
}
else if (_telegramToken.FromEnvironment || _telegramChat.FromEnvironment)
{
<p class="hint">Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.</p>
}
else
{
<form method="post" action="/azioni/telegram" class="form" autocomplete="off">
<AntiforgeryToken />
<label for="tg-token">Token del bot (da @@BotFather)</label>
<input id="tg-token" name="token" type="password" autocomplete="off" spellcheck="false" maxlength="200" required />
<label for="tg-chat">Numero della chat</label>
<input id="tg-chat" name="chat" inputmode="numeric" autocomplete="off" spellcheck="false" maxlength="40" required />
<button class="btn" type="submit">Prova e salva</button>
</form>
<p class="hint">Prima di salvarli mando un messaggio di prova: se non parte, non salvo nulla. Il token non lo rimostro mai.</p>
}
@if (!Shell.IsDemo && _telegramToken.IsSet && _telegramChat.IsSet)
{
<form method="post" action="/azioni/telegram/prova" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Manda un messaggio di prova</button></form>
@if (!_telegramToken.FromEnvironment && !_telegramChat.FromEnvironment)
{
<form method="post" action="/azioni/telegram/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Tolgo token e chat? Non ti scrivo più su Telegram finché non li rimetti.">Togli Telegram</button></form>
}
}
<h3>Stato periodico</h3>
<form method="post" action="/azioni/impostazioni/@SettingsStore.TelegramStatus.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#telegram" />
<label for="tg-status">@SettingsStore.TelegramStatus.Label</label>
<select id="tg-status" name="valore" disabled="@(_telegramStatus.ReadOnly || Shell.IsDemo)" data-autosubmit>
@foreach (var value in SettingsStore.TelegramStatus.Allowed!)
{
<option value="@value" selected="@(value == _telegramStatus.Value)">@(value switch { "hourly" => "Ogni ora", "daily" => "Ogni sera alle 20:00", _ => "Mai" })</option>
}
</select>
<button class="btn btn-small" type="submit">Salva</button>
</form>
<h3>Segnale di vita</h3>
<p class="hint">Facoltativo. Se metti l'indirizzo di un servizio di controllo esterno (per esempio healthchecks.io), lo chiamo ogni minuto. Quando le chiamate si fermano è quel servizio ad avvisarti: è l'unico modo per sapere che il bot è spento quando è spento.</p>
<dl class="facts">
<dt>Indirizzo</dt><dd>@(Host.Services!.Telegram?.ConfiguredHeartbeat is not null ? "Dalla configurazione d'avvio (ANUBIS_HEARTBEAT_URL)" : KeyState(_heartbeat))</dd>
@if (Host.Services.Telegram is { } tg)
{
<dt>Ultima chiamata riuscita</dt><dd>@(tg.Heartbeat.LastOk is { } beat ? Format.ShortDate(beat, Shell.Now, Shell.Zone) : "Nessuna da quando il bot è partito")</dd>
@if (tg.Heartbeat.LastError is { } beatError)
{
<dt>Ultimo errore</dt><dd class="loss">@beatError</dd>
}
}
</dl>
@if (!Shell.IsDemo && Host.Services.Telegram is { ConfiguredHeartbeat: null })
{
<form method="post" action="/azioni/segnale-di-vita" class="form-inline" autocomplete="off">
<AntiforgeryToken />
<label for="hb-url">Indirizzo</label>
<input id="hb-url" name="indirizzo" type="url" autocomplete="off" spellcheck="false" maxlength="500" placeholder="https://hc-ping.com/…" required />
<button class="btn btn-small" type="submit">Prova e salva</button>
</form>
@if (_heartbeat.IsSet)
{
<form method="post" action="/azioni/segnale-di-vita/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Togli il segnale di vita</button></form>
}
}
</section>
<section class="panel" id="dati">
<h2>Dati</h2>
@@ -365,6 +457,11 @@
private List<SettingChange> _history = [];
private IReadOnlyList<BackupInfo> _backups = [];
private bool _hasSecondFactor;
private SecretStatus _telegramToken = new(Anubis.Notifications.TelegramSettings.TokenSecret, false, false, null);
private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft;
private string? _draftUri;
@@ -397,6 +494,11 @@
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
_backups = services.Backups.List();
_telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct);
_telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
_heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
_telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
_queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
var reconciler = new Reconciler(services.Db, Clock, ledger);
@@ -445,6 +547,12 @@
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
"telegram-rifiutato" => "Telegram non ha accettato token o chat, o non ha risposto: il messaggio di prova non è partito e non ho salvato nulla. Controlla il token di @BotFather e il numero della chat.",
"telegram-prova" => "Il messaggio di prova non è partito: controlla token e chat, o riprova tra poco.",
"telegram-vuoto" => "Servono il token del bot e il numero della chat.",
"telegram-ambiente" => "Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.",
"segnale" => "L'indirizzo non va bene: serve https:// (http solo nella rete di casa).",
"segnale-fallito" => "Il servizio di controllo non ha risposto bene alla prova: non ho salvato l'indirizzo.",
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
_ => PasswordMessages.For(Errore),
@@ -2,12 +2,28 @@
@page "/"
@inject AnubisHost Host
@inject ShellData Shell
@using Anubis.Trading
@using Anubis.Data
<PageTitle>Panoramica · Anubis</PageTitle>
@{
var o = _overview;
var p = _panorama;
var c = _currency;
var moves = p.DemoMoves ?? o.Next;
var last = p.DemoLast ?? o.Last;
// On the phone only the first two moves of the bot, without the calendar's events (SPEC 13.4).
var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet();
var v = p.Accounts;
}
@if (_absence is { } away)
{
<div class="notice notice-attention absence" role="status">
<Icon Name="alert" Size="16" />
<span>Sono stato spento per @Anubis.Trading.DiaryText.Duration(away.Length), fino a @Format.ShortDate(away.EndedAt, Shell.Now, Shell.Zone, withTime: false).ToLowerInvariant() alle @TimeZoneInfo.ConvertTime(away.EndedAt, Shell.Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture). Ho ripreso i lavori saltati con le regole del recupero: cosa ho fatto e cosa ho lasciato perdere è nel <a href="/diario?tipo=sistema">diario</a>.</span>
<form method="post" action="/azioni/assenza/@away.Id/vista"><AntiforgeryToken /><button class="btn btn-small" type="submit">Ho visto</button></form>
</div>
}
@if (!o.CapitalSet && !Shell.IsDemo)
{
@@ -42,7 +58,9 @@
<span class="big-number">@Shell.Money(o.Result.Amount, c, withSign: true)</span>
<span class="badge @(gain ? "badge-gain" : "badge-loss")"><Arrow Up="gain" />@Format.Percent(o.Result.Percent, 2, withSign: true)</span>
</div>
<p class="note">Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.</p>
var from = Format.LongDate(o.From);
var year = from.LastIndexOf(' ');
<p class="note">Dal @from[..year]<span class="desk-only">@from[year..]</span>, partendo da @Shell.Money(o.FromEquity, c).<span class="desk-only"> Commissioni già tolte.</span></p>
<div class="cells">
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
{
@@ -63,47 +81,322 @@
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
@if (_runningDays is { } days)
{
<span class="note">Attivo da @days giorni senza interruzioni</span>
<span class="note desk-only">Attivo da @days giorni senza interruzioni</span>
}
</div>
<p class="statement">@Statement(o)</p>
<h3 class="list-title">Prossime mosse</h3>
@if (o.Next.Count == 0)
@if (p.NextDecision is { } decision)
{
<p class="note">Niente in programma.</p>
<p class="next-decision desk-only"><Icon Name="clock" Size="16" />@decision</p>
}
<h3 class="list-title desk-only">Prossime mosse</h3>
@if (moves.Count == 0)
{
<p class="note">Niente in programma: le mosse compaiono quando il motore di trading lavora con almeno una strategia.</p>
}
else
{
<ul class="moves">
@foreach (var move in o.Next)
@for (var i = 0; i < moves.Count; i++)
{
<li><span class="move-time">@move.Time</span><span>@move.Text</span></li>
var move = moves[i];
<li class="@(phoneMoves.Contains(i) ? null : "desk-only")"><span class="move-time">@move.Time</span><span>@move.Text@if (move.Where is { } where) {<span class="muted desk-only"> (@where)</span>}</span></li>
}
</ul>
}
<h3 class="list-title">Ultime azioni</h3>
@if (o.Last.Count == 0)
<div class="desk-only">
<h3 class="list-title">Ultime azioni</h3>
@if (last.Count == 0)
{
<p class="note">Ancora nessuna voce nel diario.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in last)
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
}
</ul>
}
<a class="more" href="/diario">Apri il diario completo</a>
</div>
<a class="more phone-only" href="/diario">Tutte le mosse e il diario</a>
</div>
</section>
@* Accounts and the four limits (mockup 01); on the phone a compact list of the accounts (mockup 09). *@
<div class="overview-row">
@if (!v.HasAccounts)
{
<section class="panel overview-empty desk-only">
<p class="empty-title">Nessun conto ancora.</p>
<p>Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova compaiono quando ne aggiungi le chiavi in <a href="/impostazioni#conti">Impostazioni</a>.</p>
</section>
}
@foreach (var a in v.Accounts)
{
var up = a.Result >= 0;
var held = v.Positions.Where(x => x.AccountId == a.Id).ToList();
var slices = held.GroupBy(x => x.Strategy).OrderBy(g => StrategyNames.Base.ToList().FindIndex(b => b.Name == g.Key))
.Select(g => (Strategy: g.Key, Eur: g.Sum(x => x.ValueEur))).ToList();
var shares = Format.Shares([.. slices.Select(s => s.Eur), a.Eur(a.Cash)]);
var trend = p.Trends.GetValueOrDefault(a.Id);
<section class="panel overview-account desk-only" aria-label="@a.Name">
<div class="account-head">
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(Down(a) ? "Non risponde" : "Connesso")</span>
</div>
<div class="account-value">
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Shell.Money(a.Eur(a.Result), c, withSign: true) (@Format.Percent(a.Percent, 2, withSign: true))</span>
</div>
<div class="split-bar thin" role="img" aria-label="Investito @Shell.Money(a.InvestedEur, c), liquidità @Shell.Money(a.Eur(a.Cash), c)">
@for (var i = 0; i < slices.Count; i++)
{
if (shares[i] > 0)
{
<span style="width: @Css(shares[i])%; background: var(--s-@slices[i].Strategy.Replace('_', '-'))"></span>
}
}
@if (shares[^1] > 0)
{
<span style="width: @Css(shares[^1])%; background: var(--cash)"></span>
}
</div>
<div class="split-key">
<span>@foreach (var s in slices) {<span class="swatch" style="background: var(--s-@s.Strategy.Replace('_', '-'))"></span>}Investito <strong>@Shell.Money(a.InvestedEur, c)</strong></span>
<span><span class="swatch" style="background: var(--cash)"></span>Liquidità <strong>@Shell.Money(a.Eur(a.Cash), c)</strong></span>
</div>
<div class="month">
<div>
<span class="cell-label">Ultimi 30 giorni</span>
<strong>@(trend is null ? "—" : Shell.Money(trend.Month, c, withSign: true))</strong>
</div>
@if (trend is { Points.Count: > 1 } t)
{
<svg class="spark-mini" viewBox="0 0 120 36" role="img" aria-label="Andamento degli ultimi 30 giorni">
<polyline points="@Spark(t.Points)" />
<circle cx="@SparkEnd(t.Points).X" cy="@SparkEnd(t.Points).Y" r="2.5" />
</svg>
}
</div>
<p class="note">@AccountNote(a, held)</p>
</section>
}
<section class="panel overview-risk desk-only" aria-labelledby="rischio-sintesi">
<div class="panel-head">
<h2 id="rischio-sintesi">Rischio</h2>
<span class="status-pill @(p.LimitsKept ? "gain" : "attention")"><Icon Name="@(p.LimitsKept ? "check" : "alert")" Size="16" />@(p.LimitsKept ? "Tutti i limiti rispettati" : "Un limite chiede attenzione")</span>
</div>
<div class="limit-list">
@foreach (var l in p.Limits)
{
<div class="limit">
<div class="limit-line"><span>@l.Label</span><span><strong>@l.Value</strong> <span class="muted">su @l.Threshold</span></span></div>
<span class="usage @(l.Worst is null ? null : "notched") @(l.Share >= 0.8m ? "high" : null)">
<span style="width: @Css(l.Share * 100m)%"></span>
@if (l.Worst is { } w)
{
<i class="notch" style="left: @Css(w * 100m)%"></i>
}
</span>
</div>
}
</div>
@if (p.Limits[1].Worst is not null && _worst is { } worst)
{
<p class="note">Ancora nessuna voce nel diario.</p>
<p class="note">La tacca segna il calo peggiore finora: @Format.Percent(worst * 100m, 2).</p>
}
<a class="more" href="/rischio">Vedi tutti i limiti</a>
</section>
</div>
@if (v.HasAccounts)
{
<section class="panel phone-only" aria-labelledby="conti-telefono">
<h2 id="conti-telefono">Conti</h2>
<ul class="phone-list">
@foreach (var a in v.Accounts)
{
var up = a.Result >= 0;
<li>
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(Down(a) ? "non risponde" : "connesso")</span></span>
<span class="num"><strong>@Shell.Money(a.Eur(a.Equity), c)</strong><span class="sub @(up ? "gain" : "loss")"><Arrow Up="up" /><strong>@Shell.Money(a.Eur(a.Result), c, withSign: true)</strong></span></span>
</li>
}
</ul>
</section>
}
@* Positions by value and the strategies (mockup 01); on the phone the first four positions (mockup 09). *@
<div class="overview-row overview-row-wide">
<section class="panel overview-positions" aria-labelledby="posizioni-sintesi">
<div class="panel-head">
<h2 id="posizioni-sintesi">Posizioni aperte
@if (v.Positions.Count > 0)
{
<span class="note desk-only">@v.Positions.Count, per @Shell.Money(v.InvestedEur, c). Risultato aperto @Shell.Money(v.OpenResultEur, c, withSign: true)</span>
}
</h2>
@if (v.Positions.Count > 0)
{
<span class="note phone-only">@v.Positions.Count, risultato @Shell.Money(v.OpenResultEur, c, withSign: true)</span>
}
<a class="desk-only" href="/conti">Dettaglio</a>
</div>
@if (v.Positions.Count == 0)
{
<p class="note">Nessuna posizione aperta. Quando una strategia compra, qui vedi ogni posizione con il suo valore, il risultato e lo stop che la protegge.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in o.Last)
<div class="table-wrap desk-only">
<table class="table positions">
<thead>
<tr><th scope="col">Strumento</th><th scope="col">Strategia</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Stop</th></tr>
</thead>
<tbody>
@foreach (var x in v.Positions)
{
var gain = x.ResultEur >= 0;
<tr>
<th scope="row"><strong>@x.Symbol</strong> <span class="muted">@x.Name</span></th>
<td class="nowrap"><span class="swatch round" style="background: var(--s-@x.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(x.Strategy)</td>
<td class="num">@Shell.Money(x.ValueEur, c)</td>
<td class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(x.ResultEur, c, withSign: true) (@Format.Percent(x.Percent, 2, withSign: true))</strong></td>
<td class="num nowrap">@if (x.Stop is { } stop) {@Format.Money(stop, x.Currency, decimals: AccountsView.StopDecimals(stop))<span class="muted"> (@Format.Percent(x.Last == 0 ? 0 : (stop / x.Last - 1m) * 100m, 1))</span>} else {<span class="muted">nessuno</span>}</td>
</tr>
}
</tbody>
</table>
</div>
<ul class="phone-list phone-only">
@foreach (var x in v.Positions.Take(4))
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
var gain = x.ResultEur >= 0;
<li>
<span><strong>@x.Symbol</strong><span class="sub"><span class="swatch round" style="background: var(--s-@x.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(x.Strategy)</span></span>
<span class="num">@Shell.Money(x.ValueEur, c)<strong class="sub @(gain ? "gain" : "loss")">@Shell.Money(x.ResultEur, c, withSign: true)</strong></span>
</li>
}
</ul>
<a class="more" href="/diario">Tutto il diario</a>
<a class="more phone-only" href="/conti">@(v.Positions.Count > 4 ? $"Vedi le altre {v.Positions.Count - 4}" : "Vedi i conti")</a>
}
</section>
<section class="panel overview-strategies desk-only" aria-labelledby="strategie-sintesi">
<div class="panel-head">
<h2 id="strategie-sintesi">Strategie</h2>
<a href="/strategie">Dettaglio</a>
</div>
@if (p.Strategies.Count == 0)
{
<p class="note">Le strategie compaiono quando parte il motore di trading.</p>
}
else
{
<ul class="strategy-list">
@foreach (var s in p.Strategies)
{
<li>
<div class="strategy-line"><strong><span class="swatch round" style="background: @s.Color"></span>@s.Name</strong><strong>@Shell.Money(s.Result, c, withSign: true)</strong></div>
<span class="strategy-bar"><span style="width: @Css(Math.Max(s.Bar * 100m, 2m))%; background: @s.Color"></span></span>
<span class="note">@s.Stage</span>
<span class="note">@s.Trades</span>
</li>
}
</ul>
}
@if (!p.AnyLive)
{
<p class="info-note">Nessuna strategia usa soldi veri. Passano al conto reale solo dopo aver superato tutti i requisiti, e solo se lo confermi tu.</p>
}
</section>
</div>
<section class="panel phone-only" aria-labelledby="rischio-telefono">
<div class="panel-head">
<h2 id="rischio-telefono">Rischio</h2>
<span class="status-pill @(p.LimitsKept ? "gain" : "attention")"><Icon Name="@(p.LimitsKept ? "check" : "alert")" Size="16" />@(p.LimitsKept ? "Limiti rispettati" : "Da controllare")</span>
</div>
<div class="limit-list">
@foreach (var l in new[] { p.Limits[2], p.Limits[1] })
{
<div class="limit">
<div class="limit-line"><span>@l.Label</span><span><strong>@l.Value</strong> <span class="muted">su @l.Threshold.Replace(",00%", "%", StringComparison.Ordinal)</span></span></div>
<span class="usage @(l.Worst is null ? null : "notched")">
<span style="width: @Css(l.Share * 100m)%"></span>
@if (l.Worst is { } w)
{
<i class="notch" style="left: @Css(w * 100m)%"></i>
}
</span>
</div>
}
</div>
</section>
@* News, model and system (mockup 01): sections without a frame, under a dark rule (SPEC 13.2). *@
<div class="overview-tiles desk-only">
<section class="plain tile" aria-labelledby="notizie-sintesi">
<div class="panel-head"><h2 id="notizie-sintesi">Notizie che contano</h2><a href="/notizie">Tutte</a></div>
@if (p.News is null)
{
<p class="note">La lettura delle notizie non è ancora attiva. Quando lo sarà, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.</p>
}
else
{
<ul class="news-list">
@foreach (var n in p.News)
{
<li>
<span class="note">@n.When, @n.About</span>
<strong>@n.Title</strong>
<span class="@(n.Active ? "attention" : "muted")">@if (n.Active) {<Icon Name="alert" Size="16" />}@n.Effect</span>
</li>
}
</ul>
}
</section>
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
@if (p.Learning is not { } m)
{
<p class="note">L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.</p>
}
else
{
<p><strong>Il modello osserva e impara, ma non decide ancora.</strong></p>
<div class="limit">
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
</div>
<dl class="tile-facts">
<dt>Previsioni azzeccate</dt><dd>@m.Precision% su dati mai visti</dd>
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
</dl>
}
</section>
<section class="plain tile" aria-labelledby="sistema-sintesi">
<div class="panel-head"><h2 id="sistema-sintesi">Sistema</h2><a href="/diario">Dettaglio</a></div>
<ul class="system-tiles">
@foreach (var part in p.System.Tiles)
{
<li class="@PartClass(part.State)"><Icon Name="@PartIcon(part.State)" Size="16" /><span>@part.Name</span><span class="muted">@part.Detail</span></li>
}
</ul>
</section>
</div>
@code {
private Overview _overview = null!;
private PanoramaView _panorama = null!;
private string _currency = "EUR";
private string _period = "avvio";
private int? _runningDays;
private decimal? _worst;
private Anubis.Trading.Absence? _absence;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
@@ -118,8 +411,13 @@
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct);
_panorama = await PanoramaView.LoadAsync(Host, Shell, _overview, ct);
_worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null;
using var aggregates = Shell.Aggregates();
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
// SPEC 5.6: an absence longer than a day stays at the top until the user says they have seen it.
_absence = Shell.IsDemo ? null : await new Anubis.Trading.AbsenceBook(services.Db, Host.Clock).DeclaredAsync(ct);
}
private static string Statement(Overview o)
@@ -135,4 +433,60 @@
: $"{o.PositionsWithoutStop} senza stop";
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
}
private static bool Down(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.Unreachable;
private string AccountNote(AccountCard a, IReadOnlyList<PositionRow> held)
{
var count = held.Count == 1 ? "1 posizione" : $"{held.Count} posizioni";
if (held.Count == 0)
{
count = "Nessuna posizione aperta";
}
if (a.Broker != Venues.Alpaca)
{
var stops = held.Count(x => x.Stop is not null);
var stopText = held.Count == 0 ? "" : stops == 1 ? ", 1 stop attivo" : $", {stops} stop attivi";
return $"{count}{stopText}. Commissioni pagate finora: {Shell.Money(a.Eur(a.Fees), _currency)}.";
}
var fractions = held.Any(x => x.Quantity != decimal.Truncate(x.Quantity));
var stopsText = held.Count == 0 ? ""
: " Stop permanenti sulle azioni intere" + (!fractions ? "." : _panorama.FractionStops is { } back
? $"; sulle frazioni tornano alle {TimeZoneInfo.ConvertTime(back, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)}."
: "; sulle frazioni valgono fino alla chiusura.");
var dollars = a.Currency == "USD" && a.Rate > 0m ? $" Conto in dollari: {Format.Money(a.Equity, "USD")} al cambio {Format.Quantity(a.Rate)}." : "";
return count + "." + stopsText + dollars;
}
private static string PartClass(PartState state) => state switch
{
PartState.Ok => "ok",
PartState.Warn => "warn",
_ => "off",
};
private static string PartIcon(PartState state) => state switch
{
PartState.Ok => "tick",
PartState.Warn => "alert",
_ => "clock",
};
private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
private static string Spark(IReadOnlyList<decimal> points)
{
var (min, max) = (points.Min(), points.Max());
var range = Math.Max(0.01m, max - min);
return string.Join(' ', points.Select((x, i) => Css(i * 116m / (points.Count - 1) + 2m) + "," + Css(32m - (x - min) / range * 28m)));
}
private static (string X, string Y) SparkEnd(IReadOnlyList<decimal> points)
{
var (min, max) = (points.Min(), points.Max());
var range = Math.Max(0.01m, max - min);
return ("118", Css(32m - (points[^1] - min) / range * 28m));
}
}
@@ -12,7 +12,11 @@
}
else
{
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale, Telegram e segnale di vita si aggiungono dopo, dalle Impostazioni: Telegram ha un pulsante che manda un messaggio di prova.</p>
@if (Host.Config.Platform == Anubis.Platform.PlatformKind.Desktop)
{
<p class="hint">Su un computer di casa ti consiglio il segnale di vita (Impostazioni, sezione Telegram): un servizio esterno che ti avvisa quando il bot smette di chiamarlo. È l'unico modo per sapere che il bot è spento quando il computer è spento.</p>
}
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
+243
View File
@@ -0,0 +1,243 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Anubis.Core;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A piece of a diary line: plain text, or an amount coloured as a gain or a loss (always with its sign).</summary>
internal sealed record DiaryPiece(string Text, string? Class = null);
/// <summary>
/// A diary entry as the page draws it (mockup 08): the first sentence as the main line, the rest underneath; a rule
/// the bot changed shows its lead in bold; a sale that closed a trade links to its "why".
/// </summary>
internal sealed record DiaryEntry(DateTimeOffset At, string Kind, string Icon, string? Lead, IReadOnlyList<DiaryPiece> Main, string? Rest, bool Attention, string? Trade);
internal sealed record DiaryDay(DateOnly Day, string Heading, IReadOnlyList<DiaryEntry> Entries);
/// <summary>
/// The diary of "Diario e sistema" (SPEC 13.6): in order of time, grouped by local day, with filters by kind and a
/// search. Static pages: the filters and "Mostra i giorni precedenti" are links with query values.
/// </summary>
internal sealed partial record DiaryView(IReadOnlyList<DiaryDay> Days, string Filter, string? Search, int Range, bool HasOlder, bool Truncated)
{
/// <summary>The risk kind of the filters: not a kind of its own in the journal, but the codes of the risk engine and its relatives.</summary>
public const string RiskKind = "Rischio";
public const int DefaultRange = 2;
public const int MaxSearchResults = 200;
/// <summary>The filter chips, in the order of the mockup: query value, label, kind.</summary>
public static readonly IReadOnlyList<(string Key, string Label, string? Kind)> Filters =
[
("tutto", "Tutto", null),
("decisioni", "Decisioni", DiaryKinds.Decisions),
("ordini", "Ordini", DiaryKinds.Orders),
("notizie", "Notizie", DiaryKinds.News),
("rischio", "Rischio", RiskKind),
("apprendimento", "Apprendimento", DiaryKinds.Learning),
("sistema", "Sistema", DiaryKinds.System),
];
/// <summary>Journal codes that speak of risk without passing through risk_events: refused orders, keys, prudent accounts, the guard.</summary>
private static readonly string[] _riskCodes = ["order_rejected", "stop_rejected", "key_can_withdraw", "account_prudent", "guard_intervention", "clock_gap", "sell_not_filled"];
private const string RiskCondition = "(code IN (SELECT kind FROM risk_events) OR code IN ('order_rejected', 'stop_rejected', 'key_can_withdraw', 'account_prudent', 'guard_intervention', 'clock_gap', 'sell_not_filled'))";
private static readonly string[] _daysLong = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
private static readonly string[] _monthsLong = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
private static readonly CompareInfo _compare = CultureInfo.GetCultureInfo("it-IT").CompareInfo;
public bool IsEmpty => Days.Count == 0;
/// <summary>The query string of this view with one value changed, for the links of the page.</summary>
public string Link(string? filter = null, int? range = null)
{
var parts = new List<string>();
var f = filter ?? Filter;
if (f != "tutto")
{
parts.Add("tipo=" + Uri.EscapeDataString(f));
}
if (!string.IsNullOrEmpty(Search))
{
parts.Add("cerca=" + Uri.EscapeDataString(Search));
}
var r = range ?? Range;
if (r != DefaultRange)
{
parts.Add("giorni=" + r.ToString(CultureInfo.InvariantCulture));
}
return "/diario" + (parts.Count == 0 ? "" : "?" + string.Join('&', parts));
}
public static async Task<DiaryView> LoadAsync(Database db, string? filter, string? search, string? days, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var key = Filters.Any(f => f.Key == filter) ? filter! : "tutto";
var kind = Filters.First(f => f.Key == key).Kind;
var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
if (text is { Length: > 100 })
{
text = text[..100];
}
var range = int.TryParse(days, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, 3650) : DefaultRange;
var (where, parameters) = kind switch
{
null => ("1 = 1", Array.Empty<(string, object?)>()),
RiskKind => (RiskCondition, []),
_ => ("kind = @k AND NOT " + RiskCondition, new (string, object?)[] { ("k", kind) }),
};
var (rows, older, truncated) = await db.ReadAsync(async s =>
{
const string columns = "SELECT occurred_at, kind, code, message FROM journal WHERE ";
if (text is not null)
{
// The search reads the whole diary, newest first; the comparison is done here, the same on both engines,
// ignoring case and accents.
var all = await s.QueryAsync(columns + where + " ORDER BY occurred_at DESC LIMIT 5000", Row, parameters).ConfigureAwait(false);
var found = all.Where(r => _compare.IndexOf(r.Message, text, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0).ToList();
return (found.Take(MaxSearchResults).ToList(), false, found.Count > MaxSearchResults);
}
// The range ends on the newest day that has an entry, so a quiet bot never shows an empty page.
var latest = await s.FirstOrDefaultAsync("SELECT MAX(occurred_at) AS at FROM journal WHERE " + where, r => r.MomentOrNull("at"), parameters).ConfigureAwait(false);
if (latest is null)
{
return ([], false, false);
}
var today = LocalDay(now, zone);
var anchor = LocalDay(latest.Value, zone) is var last && last < today ? last : today;
var from = Start(anchor.AddDays(1 - range), zone);
var withFrom = parameters.Append(("from", from)).ToArray();
var list = await s.QueryAsync(columns + where + " AND occurred_at >= @from ORDER BY occurred_at DESC LIMIT 2000", Row, withFrom).ConfigureAwait(false);
var before = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE " + where + " AND occurred_at < @from", withFrom).ConfigureAwait(false);
return (list.ToList(), before > 0, list.Count >= 2000);
}, cancellationToken).ConfigureAwait(false);
var risky = rows.Count == 0 ? new HashSet<string>(StringComparer.Ordinal)
: (await db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT kind FROM risk_events", r => r.Text("kind")), cancellationToken).ConfigureAwait(false))
.Concat(_riskCodes).ToHashSet(StringComparer.Ordinal);
var day0 = LocalDay(now, zone);
var grouped = rows
.GroupBy(r => LocalDay(r.At, zone))
.Select(g => new DiaryDay(g.Key, Heading(g.Key, day0), [.. g.Select(r => Entry(r.At, risky.Contains(r.Code) ? RiskKind : r.Kind, r.Code, r.Message))]))
.ToList();
return new DiaryView(grouped, key, text, range, older, truncated);
static (DateTimeOffset At, string Kind, string Code, string Message) Row(DbRow r) => (r.Moment("occurred_at"), r.Text("kind"), r.Text("code"), r.Text("message"));
}
/// <summary>"Oggi, venerdì 9 ottobre", "Ieri, giovedì 8 ottobre", "Mercoledì 7 ottobre"; the year when it is not this one.</summary>
public static string Heading(DateOnly day, DateOnly today)
{
var name = $"{_daysLong[(int)day.DayOfWeek]} {day.Day.ToString(CultureInfo.InvariantCulture)} {_monthsLong[day.Month - 1]}" +
(day.Year == today.Year ? "" : " " + day.Year.ToString(CultureInfo.InvariantCulture));
return day == today ? "Oggi, " + name : day == today.AddDays(-1) ? "Ieri, " + name : char.ToUpperInvariant(name[0]) + name[1..];
}
/// <summary>Splits a diary sentence the way the mockup draws it.</summary>
public static DiaryEntry Entry(DateTimeOffset at, string kind, string code, string message)
{
ArgumentNullException.ThrowIfNull(message);
// The demo's row of appendix F says in words where the link goes; the link is drawn, the words are not.
var text = DemoLink().Replace(message, "").Trim();
string main;
string? rest = null;
string? lead = null;
var reason = text.IndexOf(" Motivo: ", StringComparison.Ordinal);
var attention = reason > 0;
if (attention)
{
// A rule changed by the bot: what it decided, in bold up to the colon, then why.
main = text[..reason];
rest = text[(reason + 1)..];
var colon = main.IndexOf(':', StringComparison.Ordinal);
if (colon > 0)
{
lead = main[..(colon + 1)];
main = main[(colon + 1)..];
}
}
else if (text.Length > 80 && SentenceEnd().Match(text) is { Success: true } end)
{
// Long entries: the first sentence on the main line, the explanation underneath. Short ones stay on one line.
main = text[..end.Index];
rest = text[(end.Index + end.Length)..];
}
else
{
main = text;
}
string? trade = null;
if (kind == DiaryKinds.Orders && Sale().Match(text) is { Success: true } sale)
{
// A sale that closed a trade: its "why" is on the Operazioni page, found by the instrument.
trade = sale.Groups["symbol"].Value.Split('/')[0];
}
return new DiaryEntry(at, kind, IconOf(kind), lead, Pieces(main), rest, attention, trade);
}
private static List<DiaryPiece> Pieces(string text)
{
var pieces = new List<DiaryPiece>();
var position = 0;
foreach (Match m in SignedAmount().Matches(text))
{
if (m.Index > position)
{
pieces.Add(new DiaryPiece(text[position..m.Index]));
}
pieces.Add(new DiaryPiece(m.Value, m.Value[0] == '+' ? "gain" : "loss"));
position = m.Index + m.Length;
}
if (position < text.Length)
{
pieces.Add(new DiaryPiece(text[position..]));
}
return pieces;
}
private static string IconOf(string kind) => kind switch
{
DiaryKinds.Orders => "arrows",
DiaryKinds.Decisions => "layers",
DiaryKinds.News => "news",
DiaryKinds.Learning => "network",
RiskKind => "shield",
_ => "sliders",
};
private static DateOnly LocalDay(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime);
private static DateTimeOffset Start(DateOnly day, TimeZoneInfo zone)
{
var local = day.ToDateTime(TimeOnly.MinValue);
return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime();
}
[GeneratedRegex(@"\s*\(con il collegamento ""[^""]*""\)")]
private static partial Regex DemoLink();
[GeneratedRegex(@"(?<=[.!?])\s+(?=[A-ZÀ-Ý0-9])")]
private static partial Regex SentenceEnd();
[GeneratedRegex(@"^Vendut[oaie] \S+ (?<symbol>\S+) a [^:]+: [+−]")]
private static partial Regex Sale();
[GeneratedRegex(@"(?<![\w])[+−]\d[\d.,]*\s?[€$]")]
private static partial Regex SignedAmount();
}
+53 -3
View File
@@ -174,6 +174,15 @@ internal static partial class Endpoints
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
});
// The technical logs of the data folder as one zip (SPEC 13.6, "Diario e sistema"). They are redacted when
// written (JsonLog); only the files the log writer names, read while it keeps writing the newest one.
api.MapGet("/registri.zip", (AnubisHost host, ShellData shell, IClock clock) =>
{
var folder = host.Config.Data.Logs;
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip");
});
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
{
@@ -195,7 +204,7 @@ internal static partial class Endpoints
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
{
var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
var (ok, message) = await BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message);
});
@@ -219,6 +228,32 @@ internal static partial class Endpoints
internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status);
/// <summary>The daily log files (anubis-*.log) of a folder in a zip, newest first; an empty zip when there are none yet.</summary>
internal static byte[] LogArchive(string folder)
{
using var buffer = new MemoryStream();
using (var zip = new System.IO.Compression.ZipArchive(buffer, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
{
var files = Directory.Exists(folder) ? Directory.EnumerateFiles(folder, "anubis-*.log").OrderDescending(StringComparer.Ordinal).ToList() : [];
foreach (var file in files)
{
try
{
using var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var entry = zip.CreateEntry(Path.GetFileName(file), System.IO.Compression.CompressionLevel.Optimal);
using var target = entry.Open();
source.CopyTo(target);
}
catch (IOException)
{
// A file removed by the rotation in the meantime: the others still go.
}
}
}
return buffer.ToArray();
}
private static async ValueTask<object?> CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var http = context.HttpContext;
@@ -255,7 +290,7 @@ internal static partial class Endpoints
/// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect
/// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14).
/// </summary>
internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, HttpContext context, CancellationToken ct)
internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, string by, CancellationToken ct)
{
var settings = host.Services!.Settings;
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
@@ -280,7 +315,6 @@ internal static partial class Endpoints
: "Comando non ammesso nello stato attuale del bot.");
}
var by = context.User.Identity?.Name ?? "utente";
if (host.Services.Trading is { Risk: { } risk } trading)
{
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
@@ -297,6 +331,7 @@ internal static partial class Endpoints
try
{
await risk.RestartAsync(by, ct).ConfigureAwait(false);
await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false);
return (true, target);
}
catch (InvalidOperationException ex)
@@ -307,9 +342,24 @@ internal static partial class Endpoints
}
await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false);
if (target != current)
{
// Blocks and unblocks reach the phone (SPEC 14), whoever gave the command.
await NotifyBotAsync(host, "bot_" + target, target switch
{
"paused" => $"Bot in pausa (da {by}): niente nuovi acquisti, stop e uscite proseguono.",
"active" => $"Bot ripartito dalla pausa (da {by}).",
"stopped" => $"«Ferma tutto» (da {by}): niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia.",
_ => $"Stato del bot: {target} (da {by}).",
}, ct).ConfigureAwait(false);
}
return (true, target);
}
private static Task NotifyBotAsync(AnubisHost host, string code, string message, CancellationToken ct) =>
host.Services!.Db.WriteAsync(s => Anubis.Trading.Diary.NotifyAsync(s, host.Clock, code, message, ct), ct);
// Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the
// page can tell how old its data are and warn when the link drops.
private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus)
+119 -2
View File
@@ -34,12 +34,29 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/telegram", SaveTelegramAsync);
signed.MapPost("/telegram/prova", TestTelegramAsync);
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
}
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
private static async Task<IResult> AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct)
{
if (!host.IsDemo && host.Services is { } services)
{
await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false);
}
return Results.Redirect("/");
}
private static string Back(IFormCollection form, string fallback)
{
var back = form["ritorno"].ToString();
@@ -159,7 +176,7 @@ internal static partial class Forms
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/impostazioni");
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key)
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
@@ -176,7 +193,7 @@ internal static partial class Forms
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
@@ -274,6 +291,106 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=chiavi#conti");
}
/// <summary>
/// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
/// </summary>
private static async Task<IResult> SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment
|| (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment)
{
return Results.Redirect(back + "?errore=telegram-ambiente#telegram");
}
var token = form["token"].ToString().Trim();
var chat = form["chat"].ToString().Trim();
if (token.Length is 0 or > 200 || chat.Length is 0 or > 40)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null)
{
return Results.Redirect(back + "?errore=telegram-rifiutato#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false);
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram#telegram");
}
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
private static async Task<IResult> TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram }
|| await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram");
}
private static async Task<IResult> RemoveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false);
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram-tolto#telegram");
}
/// <summary>The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.</summary>
private static async Task<IResult> SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var address = form["indirizzo"].ToString().Trim();
if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null)
{
return Results.Redirect(back + "?errore=segnale#telegram");
}
var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult<Uri?>(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
if (!await probe.BeatAsync(ct).ConfigureAwait(false))
{
return Results.Redirect(back + "?errore=segnale-fallito#telegram");
}
await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale#telegram");
}
private static async Task<IResult> RemoveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale-tolto#telegram");
}
private static async Task<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
+21 -9
View File
@@ -9,7 +9,8 @@ public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
internal sealed record NextMove(string Time, string Text);
/// <summary>A move of the bot with its time; <paramref name="Where"/> is the account, <paramref name="Calendar"/> marks an economic event.</summary>
internal sealed record NextMove(string Time, string Text, string? Where = null, bool Calendar = false);
internal sealed record LastAction(string When, string Text);
@@ -30,7 +31,8 @@ internal sealed record Overview(
int OpenOrders,
IReadOnlyList<NextMove> Next,
IReadOnlyList<LastAction> Last,
bool CapitalSet = true)
bool CapitalSet = true,
DateTimeOffset? NextDecision = null)
{
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")];
@@ -52,7 +54,7 @@ internal sealed record Overview(
var open = await s.CountAsync(
$"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " +
"AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false);
var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4",
var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 3",
r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false);
var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false);
return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0);
@@ -65,14 +67,18 @@ internal sealed record Overview(
.Select(g => g.Last())
.ToList();
var next = services.Scheduler.Upcoming(5)
// The moves are the jobs that decide or send orders (SPEC 13.2), not the background work that runs every minute.
var moves = services.Scheduler.Upcoming(200).Where(u => u.IsMove).Take(5).ToList();
var next = moves
.Select(u => new NextMove(TimeZoneInfo.ConvertTime(u.DueUtc, zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), u.Description))
.ToList();
var last = journal.Select(j => new LastAction(Format.ShortDate(j.At, now, zone), j.Text)).ToList();
DateTimeOffset? decision = moves.Count > 0 ? moves[0].DueUtc : null;
// Today's actions show the time alone, as in the mockup: "02:06", "Ieri 21:58".
var last = journal.Select(j => new LastAction(Today(Format.ShortDate(j.At, now, zone)), j.Text)).ToList();
if (daily.Count == 0)
{
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision);
}
var latest = daily[^1];
@@ -95,11 +101,17 @@ internal sealed record Overview(
};
var series = daily.Where(p => p.Day >= start.Day).ToList();
var cells = new List<PeriodResult> { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) };
if (daily[0].Benchmark is { } firstBenchmark && latest.Benchmark is { } lastBenchmark && firstBenchmark != 0)
// "Senza bot" since the first day it is known, with the same flows taken out as for the bot (SPEC 7.5).
if (daily.FirstOrDefault(p => p.Benchmark is not null) is { Benchmark: { } firstBenchmark } first && latest.Benchmark is { } lastBenchmark)
{
cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m));
var flows = latest.Flows - first.Flows;
var amount = lastBenchmark - firstBenchmark - flows;
var basis = firstBenchmark + flows;
cells.Add(new PeriodResult("Senza bot", amount, basis == 0m ? 0m : amount / basis * 100m));
}
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision);
}
private static string Today(string shortDate) => shortDate.StartsWith("Oggi ", StringComparison.Ordinal) ? shortDate["Oggi ".Length..] : shortDate;
}
+214
View File
@@ -0,0 +1,214 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>The last 30 days of an account: the result net of flows and the daily values in euro for the small line.</summary>
internal sealed record AccountTrend(decimal Month, IReadOnlyList<decimal> Points);
/// <summary>A news item of the "Notizie che contano" tile; <paramref name="Active"/> when its effect is still on.</summary>
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
/// <summary>A strategy at a glance: result, the bar against the best one, its stage in words and its trades.</summary>
internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades);
/// <summary>
/// Everything under the top block of the Panoramica (SPEC 13.6, mockup 01): accounts with their last 30 days, the
/// four main limits, positions, strategies, news, model and system. In demo mode the values of appendix F that
/// exist only as totals come from the aggregates (SPEC 13.1); outside it news and the model are not active yet.
/// </summary>
internal sealed record PanoramaView(
AccountsView Accounts,
IReadOnlyDictionary<Guid, AccountTrend> Trends,
IReadOnlyList<PanoramaLimit> Limits,
bool LimitsKept,
IReadOnlyList<PanoramaStrategy> Strategies,
bool AnyLive,
SystemView System,
IReadOnlyList<NextMove>? DemoMoves,
IReadOnlyList<LastAction>? DemoLast,
string? NextDecision,
IReadOnlyList<PanoramaNews>? News,
PanoramaLearning? Learning,
DateTimeOffset? FractionStops)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
public static async Task<PanoramaView> LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(overview);
var services = host.Services!;
var clock = host.Clock;
var risk = await RiskView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var accounts = await AccountsView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var strategies = await StrategiesView.LoadAsync(services, clock, false, cancellationToken).ConfigureAwait(false);
var system = await SystemView.LoadAsync(host, shell, cancellationToken).ConfigureAwait(false);
var trends = await TrendsAsync(services, accounts, shell.Now, shell.Zone, cancellationToken).ConfigureAwait(false);
// The four limits of the Panoramica, read from the same rows as the Rischio page.
var rows = risk.Rows.ToDictionary(r => r.Key);
var day = rows[RiskSettings.DailyLoss.Key];
var invested = rows[RiskSettings.MaxInvested.Key];
var biggest = rows[RiskSettings.MaxPosition.Key];
var fall = risk.Risk.Measures.Drawdown;
decimal? worst = risk.Drawdown.Count > 0 ? risk.Drawdown.Min(d => d.Drawdown) : null;
var stop = risk.Limits.DrawdownStop;
var limits = new List<PanoramaLimit>
{
new("Perdita di oggi", day.Now, day.Threshold, day.Usage ?? 0m),
new("Calo dal massimo", Format.Percent(fall * 100m, 2), Format.Percent(-stop * 100m, 2), stop <= 0m ? 0m : Math.Clamp(-fall / stop, 0m, 1m),
worst is { } w && stop > 0m ? Math.Clamp(-w / stop, 0m, 1m) : null),
new("Capitale investito", invested.Now, invested.Threshold, invested.Usage ?? 0m),
new("Posizione più grande" + (biggest.Detail is { } symbol ? $" ({symbol.Split('/')[0]})" : ""), biggest.Now, biggest.Threshold, biggest.Usage ?? 0m),
};
var kept = !risk.AnyBlock && risk.Rows.All(r => r.Usage is null or < 1m);
// Strategies: the bar compares each result with the best one; the stage says what is still missing.
var best = strategies.Cards.Select(c => Math.Abs(c.ResultEur)).DefaultIfEmpty(0m).Max();
var cards = strategies.Cards.Select(c => new PanoramaStrategy(c.Name, c.Color, c.ResultEur, best == 0m ? 0m : Math.Abs(c.ResultEur) / best, Stage(c), Trades(c))).ToList();
var anyLive = strategies.Cards.Any(c => StrategyStages.IsLive(c.Stage.Stage));
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
using var aggregates = shell.Aggregates();
if (aggregates is null)
{
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), null, null, fractions);
}
var root = aggregates.RootElement;
var demo = root.GetProperty("panoramica");
var moves = demo.GetProperty("mosse").EnumerateArray().Select(m => new NextMove(m.GetProperty("ora").GetString()!, m.GetProperty("testo").GetString()!,
m.TryGetProperty("dove", out var where) ? where.GetString() : null, m.GetProperty("calendario").GetBoolean())).ToList();
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
var model = root.GetProperty("apprendimento");
var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
c => decimal.Parse(c.GetProperty("trenta_giorni").GetString()!, _it), StringComparer.Ordinal);
var demoTrends = accounts.Accounts.ToDictionary(a => a.Id,
a => new AccountTrend(month.GetValueOrDefault(a.Name, trends.GetValueOrDefault(a.Id)?.Month ?? 0m), trends.GetValueOrDefault(a.Id)?.Points ?? []));
return new PanoramaView(accounts, demoTrends, limits, kept, cards, anyLive, system, moves, last, demo.GetProperty("prossima_decisione").GetString(), news, learning, fractions);
}
private static async Task<Dictionary<Guid, AccountTrend>> TrendsAsync(AppServices services, AccountsView accounts, DateTimeOffset now, TimeZoneInfo zone,
CancellationToken cancellationToken)
{
var shown = accounts.Accounts.ToDictionary(a => a.Id);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT taken_at, account_id, currency, equity, flows FROM equity_snapshots WHERE scope = 'account' AND world = @w AND taken_at >= @f ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Account: r.IdOrNull("account_id"), Currency: r.TextOrNull("currency"), Equity: r.Money("equity"), Flows: r.MoneyOrNull("flows") ?? 0m),
("w", world), ("f", now.AddDays(-32))), cancellationToken).ConfigureAwait(false);
var result = new Dictionary<Guid, AccountTrend>();
foreach (var group in rows.Where(r => r.Account is { } id && shown.ContainsKey(id)).GroupBy(r => r.Account!.Value))
{
var account = shown[group.Key];
decimal Eur(decimal amount, string? currency) => currency == "USD" ? account.Eur(amount) : amount;
var daily = group.GroupBy(r => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(r.At, zone).DateTime)).Select(g => g.Last()).ToList();
var latest = daily[^1];
var latestDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(latest.At, zone).DateTime);
var start = daily.LastOrDefault(p => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime) <= latestDay.AddDays(-30));
start = start == default ? daily[0] : start;
var month = Eur(latest.Equity, latest.Currency) - Eur(start.Equity, start.Currency) - (Eur(latest.Flows, latest.Currency) - Eur(start.Flows, start.Currency));
var points = daily.Where(p => p.At >= start.At).Select(p => Eur(p.Equity - p.Flows, p.Currency)).ToList();
result[group.Key] = new AccountTrend(month, points);
}
return result;
}
/// <summary>Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60".</summary>
private static string Stage(StrategyCard card)
{
var stage = card.Stage.Stage;
if (stage == StrategyStages.Observation)
{
return "In osservazione";
}
if (stage == StrategyStages.Real)
{
return "Con soldi veri";
}
var where = stage == StrategyStages.Reduced ? "In reale ridotto" : "In simulazione";
var missing = card.Requirements
.Where(r => !r.Met && r.Key is "days" or "trades")
.Select(r => (r.Key, Value: Whole(r.Value), Target: Whole(r.Target)))
.Where(r => r.Value is not null && r.Target is > 0)
.OrderBy(r => (decimal)r.Value!.Value / r.Target!.Value)
.FirstOrDefault();
return missing.Key switch
{
"days" => $"{where}, giorno {missing.Value} di {missing.Target}",
"trades" => $"{where}, {missing.Value} operazioni su {missing.Target}",
_ => where,
};
static int? Whole(string text)
{
var digits = new string(text.Where(char.IsAsciiDigit).ToArray());
return int.TryParse(digits, NumberStyles.None, _it, out var n) ? n : null;
}
}
private static string Trades(StrategyCard card)
{
var open = card.Open.Distinct().Count();
var positions = open switch
{
0 => "Nessuna posizione aperta",
1 => "1 posizione aperta",
_ => $"{open} posizioni aperte",
};
var closed = card.Closed switch
{
0 => "nessuna operazione chiusa",
1 => $"1 operazione chiusa ({(card.Winners == 1 ? "in guadagno" : "in perdita")})",
_ => $"{card.Closed} operazioni chiuse ({card.Winners} in guadagno)",
};
return positions + ", " + closed;
}
/// <summary>"Prossima decisione tra 7 ore e 14 minuti, alle 15:35."</summary>
private static string? Decision(DateTimeOffset? due, DateTimeOffset now, TimeZoneInfo zone)
{
if (due is not { } at || at <= now)
{
return null;
}
var wait = at - now;
var hours = (int)wait.TotalHours;
var minutes = wait.Minutes;
var span = (hours, minutes) switch
{
(0, <= 1) => "un minuto",
(0, _) => $"{minutes} minuti",
(1, 0) => "un'ora",
(_, 0) => $"{hours} ore",
(1, _) => $"un'ora e {minutes} minuti",
_ => $"{hours} ore e {minutes} minuti",
};
var time = TimeZoneInfo.ConvertTime(at, zone).ToString("HH:mm", _it);
return wait < TimeSpan.FromHours(24) ? $"Prossima decisione tra {span}, alle {time}." : $"Prossima decisione {Format.ShortDate(at, now, zone).ToLowerInvariant()}.";
}
}
+6
View File
@@ -18,6 +18,12 @@ if (args.Length >= 1 && args[0] == "backtest")
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
if (args.Length >= 1 && args[0] == "soak")
{
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;
+1 -58
View File
@@ -12,63 +12,6 @@ namespace Anubis.Server;
/// </summary>
internal static class ReasonTexts
{
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
};
// The exits in the few words of a table column; the full sentence stays for the "why" card.
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
{
@@ -85,7 +28,7 @@ internal static class ReasonTexts
/// <summary>Why a trade was closed, in a short sentence.</summary>
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
public static string Text(string code) => ReasonCatalog.Text(code);
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
+13 -1
View File
@@ -4,6 +4,7 @@ using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Server.Components;
using Anubis.Supervision;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
@@ -52,8 +53,12 @@ internal static class ServerApp
services.AddSingleton(clock);
services.AddSingleton(overrides ?? new ServerOverrides());
services.AddSingleton<EventBus>();
// Started by the guard (SPEC 9.3): the channel to it. Never in demo mode, which protects nothing.
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides));
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides)
{
Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService<ILogger<GuardLink>>()),
});
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
services.AddSingleton(new LoginLimiter(clock));
services.AddSingleton<ShellData>();
@@ -82,6 +87,13 @@ internal static class ServerApp
var app = builder.Build();
var host = app.Services.GetRequiredService<AnubisHost>();
if (host.Guard is { } guard)
{
// The guard asks for an orderly stop when the container stops; every stop of the engine is announced to it.
guard.StopRequested = app.Lifetime.StopApplication;
app.Lifetime.ApplicationStopping.Register(() => guard.AnnounceAsync("uscita").GetAwaiter().GetResult());
app.Lifetime.ApplicationStopped.Register(() => guard.DisposeAsync().AsTask().GetAwaiter().GetResult());
}
app.Use(SecurityHeaders);
app.Use((context, next) => LocalOnly(context, next, options, config));
+3
View File
@@ -76,6 +76,9 @@ internal sealed record ServerOverrides
public Func<Anubis.Brokers.IWebSocketTransport>? MarketSockets { get; init; }
/// <summary>Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram.</summary>
public HttpMessageHandler? TelegramHttp { get; init; }
/// <summary>True starts the accounts and the order managers in a test; off by default in tests.</summary>
public bool? Trading { get; init; }
}
+77
View File
@@ -0,0 +1,77 @@
using System.Collections;
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
using Anubis.Supervision;
namespace Anubis.Server;
/// <summary>
/// "anubis soak": the report of an endurance run in real time (SPEC 17, phase 6) from the bot's own records. It only
/// reads, so it can run while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
/// </summary>
internal static class SoakCommand
{
private const string Usage =
"Uso: anubis soak [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--hours 48] [--out file.md]\n" +
" senza --from la prova è delle ultime --hours ore fino a --to (o adesso).\n" +
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
/// <summary>0 when the run is in order, 4 when something must be looked at, 1 when the report could not be made.</summary>
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
{
output ??= Console.Out;
clock ??= new SystemClock();
var own = new Dictionary<string, string>(StringComparer.Ordinal);
var rest = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length)
{
own[args[i]] = args[++i];
}
else if (args[i] is "--help" or "-h")
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
else
{
rest.Add(args[i]);
}
}
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
try
{
var hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : 48;
var to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : clock.UtcNow;
var from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : to - TimeSpan.FromHours(hours);
var options = ServerOptions.Parse([.. rest], environment);
var config = options.LoadConfig(environment);
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
return 1;
}
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
var report = await SoakReporter.BuildAsync(db, from, to, TimeSpan.FromHours(hours), config.TimeZone, CancellationToken.None).ConfigureAwait(false);
var text = report.Markdown(config.TimeZone);
if (own.TryGetValue("--out", out var file))
{
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
}
await output.WriteAsync(text).ConfigureAwait(false);
return report.Passed ? 0 : 4;
}
catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException
or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
}
+332
View File
@@ -0,0 +1,332 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>How a component is doing: working, off by choice or not there yet, or in need of a look.</summary>
internal enum PartState
{
Ok,
Off,
Warn,
}
/// <summary>A component of the system with a line on how it is doing.</summary>
internal sealed record SystemPart(string Name, string Detail, PartState State);
/// <summary>A resource of the computer: what is used, out of how much, as a share for the bar.</summary>
internal sealed record HostResource(string Label, string Value, string? Of, decimal Share);
/// <summary>A job in the scheduler, with its time as people say it ("15:35", "Dom 03:00").</summary>
internal sealed record PlannedJob(string Time, string Text);
/// <summary>
/// The "Diario e sistema" right column and the Sistema tile of the Panoramica (SPEC 13.6, mockups 01 and 08): the
/// components with their state, the jobs in the scheduler, the resources of the computer, version and platform.
/// In demo mode the values of appendix F.10 (SPEC 13.1); otherwise the real services, process and disk.
/// </summary>
internal sealed record SystemView(
IReadOnlyList<SystemPart> Parts,
IReadOnlyList<SystemPart> Tiles,
IReadOnlyList<PlannedJob> Jobs,
IReadOnlyList<HostResource> Resources,
string Running)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
private static readonly string[] _days = ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"];
private static readonly string[] _months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
/// <summary>Nothing needs a look; components that are off by choice or not active yet do not count.</summary>
public bool AllWell => Parts.All(p => p.State != PartState.Warn);
public static async Task<SystemView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(shell);
using var aggregates = shell.Aggregates();
return aggregates is not null ? Demo(aggregates.RootElement, shell) : await RealAsync(host, shell, cancellationToken).ConfigureAwait(false);
}
private static SystemView Demo(JsonElement root, ShellData shell)
{
var system = root.GetProperty("sistema");
var accounts = root.GetProperty("conti").EnumerateArray().ToList();
var okxMs = accounts[0].GetProperty("risposta_ms").GetInt32();
var alpacaMs = accounts[1].GetProperty("risposta_ms").GetInt32();
var database = root.GetProperty("database").GetString()!;
var size = Format.Number(Dec(system, "database_gb"), 1) + " GB";
var telegram = system.GetProperty("telegram_ultimo").GetString();
var parts = new List<SystemPart>
{
new("Motore di trading", $"attivo, un controllo ogni {system.GetProperty("controllo_secondi").GetInt32()} secondi", PartState.Ok),
new("Prezzi da OKX Europe", $"in diretta, risposta in {okxMs} ms", PartState.Ok),
new("Prezzi da Alpaca", "collegato, " + Market(shell), PartState.Ok),
new("Lettura delle notizie", $"{system.GetProperty("notizie_fonti").GetInt32()} fonti, ultima lettura alle {system.GetProperty("notizie_ultima").GetString()}", PartState.Ok),
new("Database " + database, $"{size}, ultimo salvataggio alle {system.GetProperty("ultimo_salvataggio").GetString()}", PartState.Ok),
new("Telegram", $"collegato, ultimo messaggio alle {telegram}", PartState.Ok),
};
var tiles = new List<SystemPart>
{
new("OKX Europe", $"connesso, {okxMs} ms", PartState.Ok),
new("Alpaca", $"connesso, {alpacaMs} ms", PartState.Ok),
new("Prezzi di mercato", $"aggiornati {root.GetProperty("dati_aggiornati_secondi").GetInt32()} s fa", PartState.Ok),
new("Notizie", $"{root.GetProperty("notizie").GetProperty("lette_24h").GetInt32()} lette in 24 ore", PartState.Ok),
new("Database", $"{database}, {size}", PartState.Ok),
new("Telegram", $"ultimo messaggio alle {telegram}", PartState.Ok),
};
var jobs = system.GetProperty("lavori").EnumerateArray()
.Select(j => new PlannedJob(j.GetProperty("ora").GetString()!, j.GetProperty("testo").GetString()!)).ToList();
var memory = Dec(system, "memoria_gb");
var memoryTotal = system.GetProperty("memoria_totale_gb").GetDecimal();
var disk = Dec(system, "disco_gb");
var diskTotal = system.GetProperty("disco_totale_gb").GetDecimal();
var resources = new List<HostResource>
{
new("Processore", system.GetProperty("cpu_pct").GetInt32().ToString(_it) + "%", null, system.GetProperty("cpu_pct").GetDecimal() / 100m),
new("Memoria", Format.Number(memory, 1) + " GB", Format.Number(memoryTotal), memory / memoryTotal),
new("Spazio per i dati", Format.Number(disk, 1) + " GB", Format.Number(diskTotal), disk / diskTotal),
};
var started = DateOnly.ParseExact(root.GetProperty("avvio").GetString()!, "yyyy-MM-dd", _it);
var running = $"Anubis {root.GetProperty("versione").GetString()} in {root.GetProperty("piattaforma").GetString()}, acceso dal {started.Day} {_months[started.Month - 1]}: " +
$"{root.GetProperty("giorno").GetInt32()} giorni senza interruzioni.";
return new SystemView(parts, tiles, jobs, resources, running);
}
private static async Task<SystemView> RealAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
{
var services = host.Services!;
var now = shell.Now;
var zone = shell.Zone;
var parts = new List<SystemPart>();
var tiles = new List<SystemPart>();
// The trading engine, and the state the user chose for the bot.
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var trading = services.Trading;
parts.Add(trading switch
{
null => new SystemPart("Motore di trading", "spento: le strategie non lavorano", PartState.Off),
{ IsStarted: false } => new SystemPart("Motore di trading", "non è ancora partito: se non parte entro qualche minuto, guarda i registri tecnici", PartState.Warn),
_ when bot == "stopped" => new SystemPart("Motore di trading", "fermo con Ferma tutto: riparte solo con la tua conferma, dalla pagina Rischio", PartState.Warn),
_ => new SystemPart("Motore di trading",
$"{(bot == "paused" ? "in pausa" : "attivo")}, un controllo ogni {(int)trading.TickInterval.TotalSeconds} secondi", PartState.Ok),
});
// The two price feeds: the live OKX connection, the state of the Alpaca source.
var market = services.MarketData;
var sources = market is null ? [] : await new SourceStateStore(services.Db, host.Clock).ListAsync(cancellationToken).ConfigureAwait(false);
var okx = sources.FirstOrDefault(s => s.Source == MarketDataService.OkxSource);
var (okxPart, okxTile) = market switch
{
null => (new SystemPart("Prezzi da OKX Europe", "spenti", PartState.Off), new SystemPart("OKX Europe", "spento", PartState.Off)),
{ LiveConnected: true } => (new SystemPart("Prezzi da OKX Europe", "in diretta", PartState.Ok), new SystemPart("OKX Europe", "connesso", PartState.Ok)),
_ when Failing(okx) => (new SystemPart("Prezzi da OKX Europe", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("OKX Europe", "non risponde", PartState.Warn)),
_ => (new SystemPart("Prezzi da OKX Europe", "in collegamento", PartState.Off), new SystemPart("OKX Europe", "in collegamento", PartState.Off)),
};
parts.Add(okxPart);
var alpaca = sources.FirstOrDefault(s => s.Source == MarketDataService.AlpacaSource);
var (alpacaPart, alpacaTile) = (market, alpaca) switch
{
(null, _) => (new SystemPart("Prezzi da Alpaca", "spenti", PartState.Off), new SystemPart("Alpaca", "spento", PartState.Off)),
(_, null) => (new SystemPart("Prezzi da Alpaca", "in attesa del primo collegamento", PartState.Off), new SystemPart("Alpaca", "in attesa", PartState.Off)),
(_, { Enabled: false }) => (new SystemPart("Prezzi da Alpaca", "spenti: mancano le chiavi del conto di prova, in Impostazioni", PartState.Off),
new SystemPart("Alpaca", "senza chiavi", PartState.Off)),
_ when Failing(alpaca) => (new SystemPart("Prezzi da Alpaca", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("Alpaca", "non risponde", PartState.Warn)),
_ => (new SystemPart("Prezzi da Alpaca", "collegato, " + Market(shell, market.UsCalendar), PartState.Ok), new SystemPart("Alpaca", "connesso", PartState.Ok)),
};
parts.Add(alpacaPart);
tiles.Add(okxTile);
tiles.Add(alpacaTile);
var newest = market?.Freshness.Snapshot().Select(s => s.LastDataAt).Max();
tiles.Add(newest is { } at
? new SystemPart("Prezzi di mercato", "aggiornati " + Ago(now - at), now - at > TimeSpan.FromMinutes(5) ? PartState.Warn : PartState.Ok)
: new SystemPart("Prezzi di mercato", "in attesa dei primi prezzi", PartState.Off));
// News arrive with phase 7 (SPEC 10).
parts.Add(new SystemPart("Lettura delle notizie", "non ancora attiva", PartState.Off));
tiles.Add(new SystemPart("Notizie", "non ancora attive", PartState.Off));
// The database: engine, size, last backup.
var engine = services.Db.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite";
var bytes = await SizeAsync(services.Db, host.Config.Db, cancellationToken).ConfigureAwait(false);
var backups = services.Backups.List();
var lastBackup = backups.Count == 0 ? null : (DateTimeOffset?)backups.Max(b => b.TakenAt);
var size = bytes is { } b ? Bytes(b) : null;
var saved = lastBackup is { } l ? "ultimo salvataggio " + When(l, now, zone) : "nessun salvataggio ancora";
parts.Add(new SystemPart("Database " + engine, (size is null ? "" : size + ", ") + saved, PartState.Ok));
tiles.Add(new SystemPart("Database", engine + (size is null ? "" : ", " + size), PartState.Ok));
// Telegram: the last message that really left (SPEC 14), never one only queued.
var telegram = services.Telegram;
var settings = telegram is null ? null : await telegram.ReadAsync(cancellationToken).ConfigureAwait(false);
if (telegram is null || settings is null)
{
parts.Add(new SystemPart("Telegram", "non configurato: si imposta in Impostazioni", PartState.Off));
tiles.Add(new SystemPart("Telegram", "non configurato", PartState.Off));
}
else
{
var summary = await telegram.Sender.SummaryAsync(cancellationToken).ConfigureAwait(false);
var last = summary.LastSentAt is { } sent ? "ultimo messaggio " + When(sent, now, zone) : "nessun messaggio inviato ancora";
var stuck = summary.Retrying + summary.GaveUp > 0;
parts.Add(new SystemPart("Telegram", stuck ? "alcuni messaggi non sono partiti: riprovo da solo; " + last : "collegato, " + last, stuck ? PartState.Warn : PartState.Ok));
tiles.Add(new SystemPart("Telegram", last, stuck ? PartState.Warn : PartState.Ok));
}
// Appointments only: the jobs that run every minute or every hour are background work.
var jobs = services.Scheduler.Upcoming(200).Where(u => !u.Periodic).Take(7)
.Select(u => new PlannedJob(JobTime(u.DueUtc, now, zone), u.Description)).ToList();
var since = host.Status.Since;
var platform = host.Config.Platform == PlatformKind.Docker ? "in Docker" : "come applicazione desktop";
var localSince = TimeZoneInfo.ConvertTime(since, zone);
var days = (int)Math.Floor((now - since).TotalDays);
var running = days >= 1
? $"Anubis {AnubisInfo.Version} {platform}, acceso dal {localSince.Day} {_months[localSince.Month - 1]}: {days} {(days == 1 ? "giorno" : "giorni")} senza interruzioni."
: $"Anubis {AnubisInfo.Version} {platform}, acceso oggi alle {localSince.ToString("HH:mm", _it)}.";
return new SystemView(parts, tiles, jobs, MeasureHost(host.Config.Data), running);
}
private static bool Failing(SourceState? state) =>
state is { LastError: not null } && (state.LastSuccessAt is null || state.LastRequestAt > state.LastSuccessAt);
private static string Market(ShellData shell, IMarketCalendar? calendar = null)
{
var (open, next) = AccountsView.MarketState(calendar, shell.Now);
var time = TimeZoneInfo.ConvertTime(next, shell.Zone).ToString("HH:mm", _it);
return open ? "mercato aperto fino alle " + time : "mercato chiuso fino alle " + time;
}
private static async Task<long?> SizeAsync(Database db, DbSettings? settings, CancellationToken cancellationToken)
{
try
{
if (db.Engine == DbEngine.Postgres)
{
return await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT pg_database_size(current_database()) AS n", r => (long?)r.Number("n")), cancellationToken)
.ConfigureAwait(false);
}
if (settings?.SqlitePath is { } path && File.Exists(path))
{
var wal = path + "-wal";
return new FileInfo(path).Length + (File.Exists(wal) ? new FileInfo(wal).Length : 0);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
{
// The size is a detail: without it the line still says engine and backups.
}
return null;
}
/// <summary>
/// Processor of this process (share of all cores since the last look, or since it started), its memory against
/// what the container or computer gives it, and the disk that holds the data folder.
/// </summary>
private static List<HostResource> MeasureHost(DataDirectory data)
{
var list = new List<HostResource>();
var cpu = CpuSampler.Share();
list.Add(new HostResource("Processore", Format.Number(cpu * 100m) + "%", null, cpu));
using var process = Process.GetCurrentProcess();
var used = process.WorkingSet64;
var total = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes;
if (total > 0)
{
list.Add(new HostResource("Memoria", Bytes(used), Bytes(total, unit: false), Math.Clamp((decimal)used / total, 0m, 1m)));
}
try
{
var drive = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(data.Root))!);
if (drive.IsReady && drive.TotalSize > 0)
{
var taken = drive.TotalSize - drive.AvailableFreeSpace;
list.Add(new HostResource("Spazio per i dati", Bytes(taken), Bytes(drive.TotalSize, unit: false), Math.Clamp((decimal)taken / drive.TotalSize, 0m, 1m)));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
// A disk that cannot be measured is left out rather than shown wrong.
}
return list;
}
/// <summary>A size as people read it: "780 MB", "1,8 GB"; without the unit for the "su 50" after the value.</summary>
public static string Bytes(long bytes, bool unit = true)
{
const decimal giga = 1024m * 1024m * 1024m;
var gb = bytes / giga;
if (!unit)
{
return Format.Number(gb, gb >= 10m ? 0 : 1);
}
return gb >= 1m ? Format.Number(gb, 1) + " GB" : Format.Number(Math.Max(1m, bytes / (1024m * 1024m))) + " MB";
}
private static string When(DateTimeOffset moment, DateTimeOffset now, TimeZoneInfo zone)
{
var text = Format.ShortDate(moment, now, zone);
return text.StartsWith("Oggi ", StringComparison.Ordinal) ? "alle " + text["Oggi ".Length..] : text.StartsWith("Ieri ", StringComparison.Ordinal) ? "ieri alle " + text["Ieri ".Length..] : "del " + text;
}
private static string Ago(TimeSpan elapsed) => elapsed.TotalSeconds < 60 ? $"{Math.Max(0, (int)elapsed.TotalSeconds)} s fa" : Format.Ago(elapsed);
/// <summary>The time alone within a day, otherwise the day too: "15:35", "Dom 03:00".</summary>
public static string JobTime(DateTimeOffset due, DateTimeOffset now, TimeZoneInfo zone)
{
var local = TimeZoneInfo.ConvertTime(due, zone);
var time = local.ToString("HH:mm", _it);
return due - now < TimeSpan.FromHours(24) ? time : _days[(int)local.DayOfWeek] + " " + time;
}
private static decimal Dec(JsonElement element, string name) => decimal.Parse(element.GetProperty(name).GetString()!, _it);
/// <summary>The processor used by this process between two looks, as a share of all cores.</summary>
private static class CpuSampler
{
private static readonly Lock _gate = new();
private static (long Ticks, TimeSpan Cpu)? _last;
public static decimal Share()
{
using var process = Process.GetCurrentProcess();
var cpu = process.TotalProcessorTime;
var ticks = Stopwatch.GetTimestamp();
lock (_gate)
{
TimeSpan wall;
TimeSpan used;
if (_last is { } last && Stopwatch.GetElapsedTime(last.Ticks, ticks) >= TimeSpan.FromSeconds(1))
{
wall = Stopwatch.GetElapsedTime(last.Ticks, ticks);
used = cpu - last.Cpu;
}
else
{
// First look, or two looks too close together: the average since the process started.
wall = Uptime(process);
used = cpu;
}
_last = (ticks, cpu);
var share = wall <= TimeSpan.Zero ? 0d : used.TotalMilliseconds / (wall.TotalMilliseconds * Environment.ProcessorCount);
return Math.Clamp((decimal)share, 0m, 1m);
}
}
// A measure of the process, not a business time: the system clock against the process's own start, since the
// injected clock may stand still (demo) or run in another world (tests).
private static TimeSpan Uptime(Process process) => DateTime.UtcNow - process.StartTime.ToUniversalTime();
}
}
+176
View File
@@ -0,0 +1,176 @@
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Notifications;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as
/// the Panoramica: one world, the simulated one until there is a real account.
/// </summary>
internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk
{
private const string By = "Telegram";
private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco.");
private TimeZoneInfo Zone => host.Config.TimeZone;
public async Task<string> StatusAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" })
.Append(" · solo denaro finto").AppendLine(".");
if (overview.HasData)
{
var today = overview.Cells[0];
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true))
.Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(").");
}
text.Append(Positions(overview.Positions, overview.PositionsWithoutStop));
if (overview.OpenOrders > 0)
{
text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso.");
}
text.AppendLine();
if (overview.Next.Count > 0 && overview.Next[0] is var next)
{
text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine(".");
}
return text.ToString().TrimEnd();
}
public async Task<string> PositionsAsync(CancellationToken cancellationToken)
{
var services = Services;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " +
"JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol",
r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"),
Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken)
.ConfigureAwait(false);
var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)];
if (rows.Count == 0)
{
return "Nessuna posizione aperta.";
}
var text = new StringBuilder();
foreach (var r in rows)
{
var last = r.Last ?? r.Average;
var gain = (last - r.Average) * r.Quantity;
text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency))
.Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ")
.Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP")
.Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine();
}
return text.ToString().TrimEnd();
}
public async Task<string> TodayAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var local = TimeZoneInfo.ConvertTime(now, Zone);
var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime();
var entries = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at",
r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false);
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
if (overview.HasData)
{
text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true))
.AppendLine(").");
}
if (entries.Count == 0)
{
text.Append("Nessun ordine oggi.");
return text.ToString();
}
const int Shown = 15;
foreach (var e in entries.TakeLast(Shown))
{
text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text);
}
if (entries.Count > Shown)
{
text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario.");
}
return text.ToString().TrimEnd();
}
public Task<string> PauseAsync(CancellationToken cancellationToken) =>
CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken);
public Task<string> ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken);
public Task<string> StopAllAsync(CancellationToken cancellationToken) =>
CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.",
cancellationToken);
/// <summary>The morning summary (SPEC 14): the night, the positions, what comes today.</summary>
public async Task<string> MorningAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder("Buongiorno.").AppendLine();
if (overview.HasData)
{
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true))
.AppendLine(".");
}
text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop));
var local = TimeZoneInfo.ConvertTime(now, Zone).Date;
var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(200)
.Where(u => u.IsMove && TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local)
.Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description)
.ToList();
if (today.Count > 0)
{
text.AppendLine("Oggi:");
foreach (var line in today)
{
text.AppendLine(line);
}
}
return text.ToString().TrimEnd();
}
private static string Positions(int count, int withoutStop) => count switch
{
0 => "Nessuna posizione aperta.",
1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.",
_ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.",
};
private async Task<string> CommandAsync(string command, string done, CancellationToken cancellationToken)
{
if (host.IsDemo)
{
return "Nella modalità dimostrativa il bot non si comanda.";
}
var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false);
return ok ? done : message;
}
}
+173
View File
@@ -0,0 +1,173 @@
using Anubis.Core;
using Anubis.Db;
using Anubis.Notifications;
namespace Anubis.Server;
/// <summary>
/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the
/// call to the checking service every minute, the morning summary and the optional periodic status.
/// </summary>
internal sealed partial class TelegramServices : IDisposable
{
/// <summary>The secret that keeps the address of the checking service when the configuration does not give one.</summary>
public const string HeartbeatSecret = "HEARTBEAT_URL";
public static readonly TimeOnly MorningAt = new(8, 0);
public static readonly TimeOnly EveningAt = new(20, 0);
private readonly HttpClient _http;
private readonly Database _db;
private readonly IClock _clock;
private readonly SettingsStore _settings;
private readonly SecretStore _secrets;
private readonly TimeZoneInfo _zone;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler,
Microsoft.Extensions.Logging.ILogger logger)
{
ArgumentNullException.ThrowIfNull(host);
_db = db;
_clock = clock;
_settings = settings;
_secrets = secrets;
_zone = host.Config.TimeZone;
_logger = logger;
_http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
// Longer than the wait of the commands' long polling.
_http.Timeout = TimeSpan.FromSeconds(60);
Desk = new TelegramDesk(host);
Sender = new NotificationSender(db, clock, ReadAsync, Client);
Bot = new TelegramBot(clock, ReadAsync, Client, new TelegramCommands(Desk, clock), logger);
ConfiguredHeartbeat = configuredHeartbeat;
Heartbeat = new Heartbeat(_http, clock, HeartbeatAddressAsync, logger);
}
public TelegramDesk Desk { get; }
public NotificationSender Sender { get; }
public TelegramBot Bot { get; }
public Heartbeat Heartbeat { get; }
/// <summary>The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.</summary>
public string? ConfiguredHeartbeat { get; }
/// <summary>How often the queue is looked at.</summary>
public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>The client of Telegram and of the checking service.</summary>
public HttpClient Http => _http;
public TelegramClient Client(string token) => new(_http, token);
public Task<TelegramSettings?> ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
public async Task<Uri?> HeartbeatAddressAsync(CancellationToken cancellationToken)
{
var text = ConfiguredHeartbeat ?? await _secrets.RevealAsync(HeartbeatSecret, cancellationToken).ConfigureAwait(false);
return string.IsNullOrWhiteSpace(text) || Heartbeat.Check(text) is not null ? null : new Uri(text.Trim());
}
public IReadOnlyList<ScheduledJob> Jobs() =>
[
new("segnale-di-vita", "Segnale di vita al servizio di controllo", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => await Heartbeat.BeatAsync(ct).ConfigureAwait(false))
{
MaxLateness = TimeSpan.FromMinutes(2),
},
// The summary is still useful a little late; after four hours the day has moved on (SPEC 5.6).
new("riepilogo-mattino", "Riepilogo del mattino su Telegram", Schedule.Daily(MorningAt, _zone), MorningAsync)
{
MaxLateness = TimeSpan.FromHours(4),
CatchUpWithin = TimeSpan.FromHours(4),
},
new("stato-ogni-ora", "Stato periodico su Telegram, se scelto ogni ora", Schedule.Every(TimeSpan.FromHours(1)), ct => PeriodicAsync("hourly", ct)),
new("stato-ogni-giorno", "Stato periodico su Telegram, se scelto ogni giorno", Schedule.Daily(EveningAt, _zone), ct => PeriodicAsync("daily", ct)),
];
/// <summary>Sends the queue and reads the commands until the services stop.</summary>
public async Task RunAsync(CancellationToken cancellationToken)
{
var commands = Bot.RunAsync(cancellationToken);
try
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// A busy or unreachable database, or anything else: the queue keeps its messages for the next pass.
LogSendFailed(_logger, ex);
}
await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false);
}
}
finally
{
try
{
await commands.ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
}
}
/// <summary>
/// The test of Impostazioni: a message to the chat, sent at once and not through the queue, so the answer says
/// whether Telegram took it. Null when it went; otherwise the reason, in the user's words.
/// </summary>
public async Task<string?> TestAsync(TelegramSettings telegram, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(telegram);
try
{
var client = Client(telegram.Token);
var name = await client.GetMeAsync(cancellationToken).ConfigureAwait(false);
await client.SendAsync(telegram.ChatId, $"Anubis: messaggio di prova. Da qui ti scrivo{(name.Length > 0 ? " come @" + name : "")}; scrivi /aiuto per i comandi.",
cancellationToken).ConfigureAwait(false);
return null;
}
catch (TelegramException ex)
{
return ex.Message;
}
}
public void Dispose() => _http.Dispose();
private async Task MorningAsync(CancellationToken cancellationToken)
{
if (await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.MorningAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "morning_summary", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
private async Task PeriodicAsync(string every, CancellationToken cancellationToken)
{
if ((await _settings.GetAsync(SettingsStore.TelegramStatus.Key, cancellationToken).ConfigureAwait(false)).Value != every
|| await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
[Microsoft.Extensions.Logging.LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Error, Message = "Sending the Telegram queue failed")]
private static partial void LogSendFailed(Microsoft.Extensions.Logging.ILogger logger, Exception exception);
}
+8 -2
View File
@@ -162,9 +162,12 @@ public static class BacktestEngine
/// <summary>
/// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs.
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs. The live engine
/// decides with this same call (SPEC 5.2): <paramref name="history"/> is the strategy's equity at each close up to
/// <paramref name="day"/>, which the risk stage walks as it does in a whole run.
/// </summary>
public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null)
public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null,
IReadOnlyList<EquityMark>? history = null)
{
ArgumentNullException.ThrowIfNull(strategy);
ArgumentNullException.ThrowIfNull(data);
@@ -172,6 +175,7 @@ public static class BacktestEngine
CheckSchedule(strategy);
var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state);
simulation.MarkThrough(day);
simulation.SeedHistory(history ?? []);
return simulation.Decide(day, data.SessionTimes(day).Closes);
}
@@ -263,6 +267,8 @@ public static class BacktestEngine
}
}
public void SeedHistory(IReadOnlyList<EquityMark> history) => _history.AddRange(history);
public void MarkThrough(DateOnly day)
{
foreach (var i in _data.Instruments)
+105 -6
View File
@@ -118,6 +118,15 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche
/// skipped and reported instead of executed blindly (trap 21, SPEC 5.6).
/// </summary>
public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job.</summary>
public bool IsMove { get; init; }
/// <summary>
/// A run missed while the bot was off is made once at the restart, queued, when the restart comes within this
/// time of the missed run; later it is skipped and reported (SPEC 5.6). Null: a missed run is simply not made.
/// </summary>
public TimeSpan? CatchUpWithin { get; init; }
}
public enum JobOutcome
@@ -128,10 +137,22 @@ public enum JobOutcome
}
/// <summary>Published on the bus after every run, skip or failure.</summary>
public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error);
public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error)
{
/// <summary>The run was missed while the bot was off and made, or skipped, at the restart (SPEC 5.6).</summary>
public bool Missed { get; init; }
public string? Description { get; init; }
}
/// <summary>A run coming up, for "Prossime mosse" and the jobs list.</summary>
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc);
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc)
{
public bool IsMove { get; init; }
/// <summary>A job that comes back at a fixed interval (every minute, every hour): background work, not an appointment.</summary>
public bool Periodic { get; init; }
}
/// <summary>
/// Runs jobs at fixed times, at intervals, or relative to market open and close (SPEC 5.5).
@@ -142,21 +163,60 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
private readonly ILogger _logger = logger ?? NullLogger<Scheduler>.Instance;
private readonly Lock _gate = new();
private readonly Dictionary<string, (ScheduledJob Job, DateTimeOffset? Due)> _jobs = new(StringComparer.Ordinal);
private readonly Dictionary<string, DateTimeOffset> _recovering = new(StringComparer.Ordinal);
private readonly List<JobRun> _missed = [];
private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Moment of the last loop iteration; the health check uses it to see the loop is alive.</summary>
public DateTimeOffset? LastBeatUtc { get; private set; }
public void Add(ScheduledJob job)
public void Add(ScheduledJob job) => Add(job, null);
/// <summary>
/// Adds a job whose last run, from an earlier life of the process, was due at <paramref name="lastDue"/>. A job with
/// <see cref="ScheduledJob.CatchUpWithin"/> that missed a run since then makes it once at the start, or reports it
/// skipped when the restart is too late (SPEC 5.6).
/// </summary>
public void Add(ScheduledJob job, DateTimeOffset? lastDue)
{
ArgumentNullException.ThrowIfNull(job);
var now = clock.UtcNow;
var missed = job.CatchUpWithin is not null && lastDue is { } last ? LastMissed(job.Schedule, last, now) : null;
lock (_gate)
{
_jobs[job.Name] = (job, job.Schedule.NextAfter(clock.UtcNow));
if (missed is { } due && now - due <= job.CatchUpWithin)
{
_jobs[job.Name] = (job, now);
_recovering[job.Name] = due;
}
else
{
_jobs[job.Name] = (job, job.Schedule.NextAfter(now));
if (missed is { } skipped)
{
_missed.Add(new JobRun(job.Name, skipped, now, now, JobOutcome.Skipped, "Saltato al riavvio: oltre l'orario utile.")
{ Missed = true, Description = job.Description });
}
}
_changed.TrySetResult();
}
}
/// <summary>The last due time after <paramref name="last"/> and not after <paramref name="now"/>: the run the absence took.</summary>
private static DateTimeOffset? LastMissed(Schedule schedule, DateTimeOffset last, DateTimeOffset now)
{
DateTimeOffset? missed = null;
var at = schedule.NextAfter(last);
for (var i = 0; i < 100_000 && at is { } due && due <= now; i++)
{
missed = due;
at = schedule.NextAfter(due);
}
return missed;
}
public IReadOnlyList<UpcomingRun> Upcoming(int count = 10)
{
lock (_gate)
@@ -164,7 +224,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
return _jobs.Values.Where(j => j.Due is not null)
.OrderBy(j => j.Due)
.Take(count)
.Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value))
.Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove, Periodic = j.Job.Schedule is IntervalSchedule })
.ToList();
}
}
@@ -218,8 +278,13 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
{
var now = clock.UtcNow;
List<(ScheduledJob Job, DateTimeOffset Due)> due;
List<JobRun> missed;
lock (_gate)
{
// The runs an absence took and the restart came too late for: reported once, at the first round.
missed = [.. _missed];
_missed.Clear();
due = _jobs.Values.Where(j => j.Due is { } d && d <= now).Select(j => (j.Job, j.Due!.Value)).OrderBy(j => j.Value).ToList();
foreach (var (job, _) in due)
{
@@ -227,9 +292,28 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
}
}
foreach (var (job, dueAt) in due)
foreach (var run in missed)
{
bus.Publish(run);
}
foreach (var (job, queuedAt) in due)
{
var started = clock.UtcNow;
bool recovering;
DateTimeOffset dueAt;
lock (_gate)
{
recovering = _recovering.Remove(job.Name, out var missedDue);
dueAt = recovering ? missedDue : queuedAt;
}
if (recovering)
{
await RecoverAsync(job, dueAt, started, cancellationToken).ConfigureAwait(false);
continue;
}
if (started - dueAt > job.MaxLateness)
{
LogSkipped(_logger, job.Name, dueAt);
@@ -250,6 +334,21 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
}
}
/// <summary>A run missed while the bot was off, made once now: never skipped for lateness, reported as recovered.</summary>
private async Task RecoverAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, CancellationToken cancellationToken)
{
try
{
await job.Run(cancellationToken).ConfigureAwait(false);
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null) { Missed = true, Description = job.Description });
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
LogFailed(_logger, ex, job.Name);
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message) { Missed = true, Description = job.Description });
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Job {Job} skipped: it was due at {Due} and is too late to run")]
private static partial void LogSkipped(ILogger logger, string job, DateTimeOffset due);
+4 -1
View File
@@ -41,8 +41,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE",
Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check);
/// <summary>The optional periodic status on Telegram (SPEC 14): never, every hour or every evening.</summary>
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
+95 -8
View File
@@ -54,7 +54,7 @@ public sealed partial class MarketDataService : IDisposable
private (string Key, string Secret, AlpacaClient Client)? _alpaca;
public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data,
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null)
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, OkxOptions? okx = null)
{
_db = db;
_clock = clock;
@@ -73,7 +73,7 @@ public sealed partial class MarketDataService : IDisposable
_http.Timeout = TimeSpan.FromSeconds(60);
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
Okx = new OkxClient(_http, clock, null, sockets);
Okx = new OkxClient(_http, clock, okx, sockets);
Freshness = new FreshnessMonitor(clock, bus);
References = new ReferenceSources(new ApiHttp(_http, clock, "reference"), db, clock, settings, secrets.RevealAsync, Okx);
UsCalendar = new StoredMarketCalendar(db, clock, "us_equity");
@@ -105,21 +105,22 @@ public sealed partial class MarketDataService : IDisposable
{ MaxLateness = TimeSpan.FromHours(6) },
new("dati-azioni-chiusura", "Barre giornaliere delle azioni dopo la chiusura", Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(30), UsCalendar),
_ => WakeWorker()) { MaxLateness = TimeSpan.FromHours(6) },
// SPEC 5.6: after an absence the last rate available is downloaded at once.
new("dati-cambi-mattina", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(8, 0), Zones.Rome), References.RefreshFxAsync)
{ MaxLateness = TimeSpan.FromHours(4) },
{ MaxLateness = TimeSpan.FromHours(4), CatchUpWithin = TimeSpan.FromDays(3650) },
new("dati-cambi-pomeriggio", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(16, 30), Zones.Rome), References.RefreshFxAsync)
{ MaxLateness = TimeSpan.FromHours(4) },
{ MaxLateness = TimeSpan.FromHours(4), CatchUpWithin = TimeSpan.FromDays(3650) },
new("dati-calendario", "Calendario economico, riunioni e trimestrali", Schedule.Every(TimeSpan.FromHours(1)), RefreshCalendarAsync)
{ MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-umore", "Umore del mercato", Schedule.Every(TimeSpan.FromHours(1)), References.RefreshMoodAsync) { MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-spread", "Campione orario degli spread delle crypto", Schedule.Every(TimeSpan.FromHours(1)), SampleSpreadsAsync)
{ MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-calendario-borsa", "Calendario di borsa di Alpaca", Schedule.Daily(new TimeOnly(4, 0), Zones.Rome), RefreshUsCalendarAsync)
{ MaxLateness = TimeSpan.FromHours(12) },
{ MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) },
new("dati-azioni-societarie", "Frazionamenti e dividendi prima dell'apertura", Schedule.Market(MarketAnchor.Open, TimeSpan.FromHours(-1), UsCalendar),
RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync)
{ MaxLateness = TimeSpan.FromHours(12) },
{ MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) },
];
/// <summary>
@@ -130,7 +131,8 @@ public sealed partial class MarketDataService : IDisposable
{
await UsCalendar.LoadAsync(cancellationToken).ConfigureAwait(false);
_work.Release();
await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), FreshnessAsync(cancellationToken)).ConfigureAwait(false);
await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), StockLiveAsync(cancellationToken), FreshnessAsync(cancellationToken))
.ConfigureAwait(false);
}
public Task WakeWorker()
@@ -419,7 +421,8 @@ public sealed partial class MarketDataService : IDisposable
await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false);
}
private async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken)
/// <summary>Splits and dividends of the stock universe from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10).</summary>
public async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken)
{
if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca)
{
@@ -491,6 +494,90 @@ public sealed partial class MarketDataService : IDisposable
}
}
/// <summary>
/// The stock feed (IEX, issue #47): during the US session only, the stocks held, those with an order planned and the
/// market index, at most <see cref="StockStreamLimit"/> symbols as the free feed allows. Outside the session the
/// quotes come by REST when asked, and no stock is followed for freshness.
/// </summary>
private async Task StockLiveAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var now = _clock.UtcNow;
var today = DateOnly.FromDateTime(now.UtcDateTime);
var session = UsCalendar.Sessions(today.AddDays(-1), today.AddDays(10)).FirstOrDefault(s => s.CloseUtc + StockStreamMargin > now);
if (session is null || session.OpenUtc - StockStreamMargin > now)
{
var next = session is null ? now.AddHours(1) : Min(session.OpenUtc - StockStreamMargin, now.AddHours(1));
await _clock.WaitUntilAsync(next, cancellationToken).ConfigureAwait(false);
continue;
}
var alpaca = await AlpacaAsync(cancellationToken).ConfigureAwait(false);
var instruments = alpaca is null ? [] : await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false);
if (alpaca is null || instruments.Count == 0)
{
await _clock.WaitUntilAsync(now.AddMinutes(5), cancellationToken).ConfigureAwait(false);
continue;
}
var end = session.CloseUtc + StockStreamMargin;
using var round = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var collector = new MarketCollector(alpaca, _db, _clock, _bus, Freshness, logger: _logger);
var run = collector.RunLiveAsync(instruments, round.Token);
var ids = instruments.Select(i => i.Id).ToHashSet();
while (!run.IsCompleted)
{
using var nap = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var wait = _clock.WaitUntilAsync(Min(_clock.UtcNow.AddMinutes(5), end), nap.Token);
await Task.WhenAny(run, wait).ConfigureAwait(false);
await nap.CancelAsync().ConfigureAwait(false);
if (!run.IsCompleted && (_clock.UtcNow >= end
|| !(await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false)).Select(i => i.Id).ToHashSet().SetEquals(ids)))
{
await round.CancelAsync().ConfigureAwait(false);
}
}
await run.ConfigureAwait(false);
foreach (var id in ids)
{
Freshness.Unfollow(id);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogStepFailed(_logger, ex, "live azioni");
await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>The free IEX feed follows at most 30 symbols.</summary>
public const int StockStreamLimit = 30;
private static readonly TimeSpan StockStreamMargin = TimeSpan.FromMinutes(5);
private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a <= b ? a : b;
private async Task<IReadOnlyList<Instrument>> StockLiveInstrumentsAsync(CancellationToken cancellationToken)
{
var symbols = await _db.ReadAsync(s => s.QueryAsync(
"SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (i.symbol = @m"
+ " OR i.id IN (SELECT instrument_id FROM positions WHERE quantity <> 0)"
+ " OR i.id IN (SELECT instrument_id FROM planned_orders WHERE status = @p)) ORDER BY i.symbol",
r => r.Text("symbol"), ("v", Venues.Alpaca), ("m", Trading.StrategyNames.MarketSymbol), ("p", "pending")), cancellationToken).ConfigureAwait(false);
var wanted = symbols.OrderBy(s => s == Trading.StrategyNames.MarketSymbol ? 0 : 1).ThenBy(s => s, StringComparer.Ordinal).Take(StockStreamLimit).ToHashSet(StringComparer.Ordinal);
var all = await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false);
return all.Where(i => wanted.Contains(i.Symbol) && i.IsLive).ToList();
}
private async Task<IReadOnlyList<Instrument>> LiveInstrumentsAsync(CancellationToken cancellationToken)
{
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
+27
View File
@@ -117,8 +117,16 @@ public sealed class Database : IAsyncDisposable
return builder.ToString();
}
/// <summary>Fault tests only (issue #47): while true every new connection fails as if the server could not be reached.</summary>
internal bool Unreachable { get; set; }
public async Task<DbConnection> OpenConnectionAsync(CancellationToken cancellationToken)
{
if (Unreachable)
{
throw new DatabaseUnreachableException();
}
if (_postgres is not null)
{
return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
@@ -239,6 +247,25 @@ public sealed class Database : IAsyncDisposable
}
/// <summary>One open transaction. Parameters are named <c>@name</c> on both engines.</summary>
/// <summary>The database could not be reached (fault tests).</summary>
public sealed class DatabaseUnreachableException : DbException
{
public DatabaseUnreachableException()
: base("Database non raggiungibile.")
{
}
public DatabaseUnreachableException(string message)
: base(message)
{
}
public DatabaseUnreachableException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public sealed class DbSession(DbEngine engine, DbConnection connection, DbTransaction transaction)
{
public DbEngine Engine => engine;
+65
View File
@@ -0,0 +1,65 @@
-- Phase 6 schema (SPEC 5.5, 5.6, 9.3, 9.4, 14, ADR 0012): the live engine, recovery after an absence, Telegram.
-- One row for each decision the live engine makes: run_key names the strategy and the close it decides on, so a
-- decision is made once even across restarts. The row is written in the same transaction as its planned orders,
-- its decision rows and its diary lines: either all of it exists or none. state is the book the strategy decided
-- from, for the one-step comparison of SPEC 12.3 the next day.
CREATE TABLE engine_runs (
id {uuid} PRIMARY KEY,
strategy TEXT NOT NULL,
run_key TEXT NOT NULL UNIQUE,
decision_day TEXT NOT NULL,
decision_id {uuid} NOT NULL,
mode TEXT NOT NULL,
state {json},
proposed {json},
created_at {timestamp} NOT NULL
){strict};
CREATE INDEX engine_runs_strategy ON engine_runs (strategy, decision_day);
-- Orders decided and not yet handed to the order manager (SPEC 5.5: the stock orders decided after the close go at
-- the next open; SPEC 5.6: an entry has a deadline and a reference price it must not drift from). The planned
-- order's id is the decision id of the trade intent: the order key derives from it, so a restart that finds the
-- execution already there never sends it twice.
CREATE TABLE planned_orders (
id {uuid} PRIMARY KEY,
decision_id {uuid} NOT NULL,
strategy TEXT NOT NULL,
account_id {uuid} NOT NULL REFERENCES accounts (id),
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
side TEXT NOT NULL,
purpose TEXT NOT NULL,
quantity {money} NOT NULL,
exit_all {bool} NOT NULL,
stop_level {money},
stop_offset {money},
reference_price {money} NOT NULL,
reason TEXT NOT NULL,
due_at {timestamp} NOT NULL,
valid_until {timestamp},
status TEXT NOT NULL,
outcome TEXT,
execution_id {uuid},
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
CREATE INDEX planned_orders_due ON planned_orders (status, due_at);
-- Absences (SPEC 5.6): measured at the restart from the last heartbeat. One longer than 24 hours is declared on the
-- Panoramica until the user acknowledges it.
CREATE TABLE absences (
id {uuid} PRIMARY KEY,
started_at {timestamp} NOT NULL,
ended_at {timestamp} NOT NULL,
acknowledged_at {timestamp},
created_at {timestamp} NOT NULL
){strict};
-- Every notification has its state (SPEC 14): pending, sent or failed, with the attempts and the last error.
ALTER TABLE notifications ADD COLUMN attempts INTEGER;
ALTER TABLE notifications ADD COLUMN next_attempt_at {timestamp};
ALTER TABLE notifications ADD COLUMN last_error TEXT;
CREATE INDEX notifications_status ON notifications (status, created_at);
+38 -3
View File
@@ -50,10 +50,45 @@
{ "nome": "equity_meanrev", "etichetta": "Mean reversion azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 15, "capitale": "1500", "risultato": "11.36", "risultato_pct": "0.76", "calo_peggiore_pct": "-1.1", "chiuse": 21, "in_guadagno": 10 }
],
"operazioni": { "chiuse": 41, "in_guadagno": 22, "guadagno_medio": "28.42", "perdita_media": "-20.31", "rapporto": "1.62", "incassati": "239.28", "commissioni": "14.82" },
"notizie": { "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50" },
"apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56 },
"notizie": {
"lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50",
"panoramica": [
{ "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: per 24 ore non aumento SOL", "in_corso": true },
{ "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: niente mean reversion su JPM fino a martedì", "in_corso": true },
{ "quando": "07:52", "riguarda": "sul mercato in generale", "titolo": "I verbali della banca centrale USA non cambiano le attese sui tassi", "effetto": "Nessun effetto: non cambio nulla", "in_corso": false }
]
},
"panoramica": {
"prossima_decisione": "Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.",
"mosse": [
{ "ora": "15:35", "testo": "Rimetto gli stop del giorno sulle frazioni di 6 azioni", "dove": "Alpaca", "calendario": false },
{ "ora": "16:00", "testo": "Esce la fiducia dei consumatori USA: impatto medio, non blocco gli ingressi", "calendario": true },
{ "ora": "21:55", "testo": "Controllo AAPL: vendo se è sopra la media a 5 giorni", "calendario": false },
{ "ora": "22:20", "testo": "Wall Street ha chiuso: calcolo i segnali sulle azioni", "calendario": false },
{ "ora": "02:05", "testo": "Chiusura giornaliera crypto: ricalcolo i trend di 10 monete", "calendario": false }
],
"ultime_azioni": [
{ "quando": "02:06", "testo": "Alzato lo stop di BTC a 66.180 € (era 65.400 €)" },
{ "quando": "Ieri 21:58", "testo": "Venduto MSFT: +9,84 $ in 3 giorni" },
{ "quando": "Ieri 15:36", "testo": "Comprate 2 AAPL a 259,80 $" }
]
},
"apprendimento": {
"stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56,
"ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00"
},
"sistema": {
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
"cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50
"cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50,
"notizie_ultima": "08:20",
"lavori": [
{ "ora": "15:35", "testo": "Stop del giorno sulle azioni" },
{ "ora": "21:55", "testo": "Uscite della mean reversion" },
{ "ora": "22:20", "testo": "Segnali sulle azioni" },
{ "ora": "02:05", "testo": "Segnali sulle crypto" },
{ "ora": "03:00", "testo": "Controllo del modello" },
{ "ora": "03:30", "testo": "Salvataggio del database" },
{ "ora": "Dom 03:00", "testo": "Verifica settimanale del modello" }
]
}
}
+133
View File
@@ -0,0 +1,133 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Notifications;
/// <summary>The state of a notification (SPEC 14): never "sent" before Telegram said ok.</summary>
public static class NotificationStates
{
/// <summary>In the queue: not tried yet, or Telegram is not configured.</summary>
public const string Pending = "pending";
public const string Sent = "sent";
/// <summary>Tried and refused; tried again at <c>next_attempt_at</c>, or never again when that is empty.</summary>
public const string Failed = "failed";
}
/// <summary>The bot's Telegram: the token and the one chat it writes to and takes commands from.</summary>
public sealed record TelegramSettings(string Token, string ChatId)
{
public const string TokenSecret = "TELEGRAM_BOT_TOKEN";
public const string ChatSecret = "TELEGRAM_CHAT_ID";
/// <summary>Both secrets, or null while either is missing.</summary>
public static async Task<TelegramSettings?> ReadAsync(SecretStore secrets, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(secrets);
var token = await secrets.RevealAsync(TokenSecret, cancellationToken).ConfigureAwait(false);
var chat = await secrets.RevealAsync(ChatSecret, cancellationToken).ConfigureAwait(false);
return string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chat) ? null : new TelegramSettings(token.Trim(), chat.Trim());
}
}
/// <summary>What Impostazioni shows of the queue: the last message that left, what waits, what failed and why.</summary>
public sealed record NotificationSummary(DateTimeOffset? LastSentAt, int Pending, int Retrying, int GaveUp, string? LastError);
/// <summary>
/// The Telegram queue (SPEC 14). Every message is written first, then sent: a refusal or a network failure is
/// recorded and tried again with growing pauses; a message that could not leave within a day is given up, with the
/// reason, rather than arriving late as if it were news.
/// </summary>
public sealed class NotificationSender(Database db, IClock clock, Func<CancellationToken, Task<TelegramSettings?>> settings, Func<string, TelegramClient> client)
{
/// <summary>Older than this, a message is no longer worth sending.</summary>
public static readonly TimeSpan MaxAge = TimeSpan.FromHours(24);
public const int MaxAttempts = 8;
/// <summary>At most this many messages per pass: Telegram limits the messages to one chat.</summary>
public const int Batch = 20;
/// <summary>Writes a message in the queue, in the same transaction as what it tells.</summary>
public static Task EnqueueAsync(DbSession s, IClock clock, string kind, string message, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync(
"INSERT INTO notifications (id, channel, kind, message, status, attempts, created_at) VALUES (@id, 'telegram', @k, @m, @st, 0, @at)", cancellationToken,
("id", Ids.NewId(clock)), ("k", kind), ("m", message), ("st", NotificationStates.Pending), ("at", clock.UtcNow));
}
/// <summary>The pause before attempt <paramref name="attempts"/> + 1: 1, 2, 4, 8, 16, 32, then 60 minutes.</summary>
public static TimeSpan Pause(int attempts) => TimeSpan.FromMinutes(Math.Min(60, 1 << Math.Clamp(attempts - 1, 0, 6)));
/// <summary>Sends what is due; the answer is how many left. Without Telegram configured everything stays in the queue.</summary>
public async Task<int> SendDueAsync(CancellationToken cancellationToken)
{
if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
{
return 0;
}
var now = clock.UtcNow;
var due = await db.ReadAsync(s => s.QueryAsync(
"SELECT id, message, attempts, created_at FROM notifications WHERE channel = 'telegram' AND (status = @p OR (status = @f AND next_attempt_at IS NOT NULL AND next_attempt_at <= @now)) " +
"ORDER BY created_at, id LIMIT " + Batch.ToString(System.Globalization.CultureInfo.InvariantCulture),
r => (Id: r.Id("id"), Message: r.Text("message"), Attempts: r.IsNull("attempts") ? 0 : (int)r.Number("attempts"), Created: r.Moment("created_at")),
("p", NotificationStates.Pending), ("f", NotificationStates.Failed), ("now", now)), cancellationToken).ConfigureAwait(false);
var bot = client(telegram.Token);
var sent = 0;
foreach (var item in due)
{
if (now - item.Created > MaxAge)
{
await MarkAsync(item.Id, NotificationStates.Failed, item.Attempts, null, "Non partito entro un giorno: non lo mando più.", cancellationToken).ConfigureAwait(false);
continue;
}
try
{
await bot.SendAsync(telegram.ChatId, item.Message, cancellationToken).ConfigureAwait(false);
await MarkAsync(item.Id, NotificationStates.Sent, item.Attempts + 1, null, null, cancellationToken).ConfigureAwait(false);
sent++;
}
catch (TelegramException ex)
{
var attempts = item.Attempts + 1;
DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
: null;
await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false);
if (ex.Retryable)
{
// Telegram unreachable or asking to slow down: the others wait for the next pass.
break;
}
}
}
return sent;
}
public Task<NotificationSummary> SummaryAsync(CancellationToken cancellationToken) =>
db.ReadAsync(async s =>
{
var last = await s.FirstOrDefaultAsync("SELECT MAX(sent_at) AS at FROM notifications WHERE channel = 'telegram' AND status = @s",
r => r.MomentOrNull("at"), ("s", NotificationStates.Sent)).ConfigureAwait(false);
var pending = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @p", ("p", NotificationStates.Pending)).ConfigureAwait(false);
var retrying = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NOT NULL",
("f", NotificationStates.Failed)).ConfigureAwait(false);
var gaveUp = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NULL",
("f", NotificationStates.Failed)).ConfigureAwait(false);
var error = await s.FirstOrDefaultAsync(
"SELECT last_error FROM notifications WHERE channel = 'telegram' AND status = @f ORDER BY created_at DESC, id DESC LIMIT 1",
r => r.TextOrNull("last_error"), ("f", NotificationStates.Failed)).ConfigureAwait(false);
return new NotificationSummary(last, (int)pending, (int)retrying, (int)gaveUp, error);
}, cancellationToken);
private Task<int> MarkAsync(Guid id, string status, int attempts, DateTimeOffset? next, string? error, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync(
"UPDATE notifications SET status = @s, attempts = @a, next_attempt_at = @n, last_error = @e, sent_at = @sent WHERE id = @id", cancellationToken,
("s", status), ("a", attempts), ("n", next), ("e", error), ("sent", status == NotificationStates.Sent ? clock.UtcNow : (DateTimeOffset?)null), ("id", id)), cancellationToken);
}
+289
View File
@@ -0,0 +1,289 @@
using Anubis.Core;
using Microsoft.Extensions.Logging;
namespace Anubis.Notifications;
/// <summary>
/// What the Telegram commands read and do (SPEC 14), answered in plain Italian. Nothing here turns on real money,
/// changes a limit or shows a secret: the interface does those, never the phone.
/// </summary>
public interface ITelegramDesk
{
Task<string> StatusAsync(CancellationToken cancellationToken);
Task<string> PositionsAsync(CancellationToken cancellationToken);
Task<string> TodayAsync(CancellationToken cancellationToken);
Task<string> PauseAsync(CancellationToken cancellationToken);
/// <summary>Only from a pause, never after "Ferma tutto" (SPEC 9.3, 14).</summary>
Task<string> ResumeAsync(CancellationToken cancellationToken);
/// <summary>"Ferma tutto", already confirmed.</summary>
Task<string> StopAllAsync(CancellationToken cancellationToken);
}
/// <summary>The commands of SPEC 14 and the confirmation of /ferma: two minutes to send /conferma.</summary>
public sealed class TelegramCommands(ITelegramDesk desk, IClock clock)
{
public static readonly TimeSpan ConfirmWithin = TimeSpan.FromMinutes(2);
public const string Help =
"Comandi:\n" +
"/stato – come sta il bot\n" +
"/posizioni – cosa ho in mano, con gli stop\n" +
"/oggi – cosa ho fatto oggi\n" +
"/pausa – niente nuovi acquisti, stop e uscite proseguono\n" +
"/riprendi – riparto dalla pausa\n" +
"/ferma – «Ferma tutto», con conferma\n" +
"/aiuto – questo elenco\n" +
"Soldi veri, limiti e chiavi si cambiano solo dall'interfaccia.";
private DateTimeOffset? _stopAskedAt;
/// <summary>The answer to one message; null for a message that is not a command.</summary>
public async Task<string?> AnswerAsync(string text, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(text);
var word = text.Trim().Split((char[])[' ', '\n', '\t'], 2)[0];
if (!word.StartsWith('/'))
{
return null;
}
// In a group Telegram adds the bot's name: "/stato@AnubisBot".
var command = word[1..].Split('@')[0].ToLowerInvariant();
if (command != "conferma")
{
_stopAskedAt = null;
}
switch (command)
{
case "start" or "aiuto" or "help":
return Help;
case "stato":
return await desk.StatusAsync(cancellationToken).ConfigureAwait(false);
case "posizioni":
return await desk.PositionsAsync(cancellationToken).ConfigureAwait(false);
case "oggi":
return await desk.TodayAsync(cancellationToken).ConfigureAwait(false);
case "pausa":
return await desk.PauseAsync(cancellationToken).ConfigureAwait(false);
case "riprendi":
return await desk.ResumeAsync(cancellationToken).ConfigureAwait(false);
case "ferma":
_stopAskedAt = clock.UtcNow;
return "Vuoi davvero «Ferma tutto»? Annullo gli ordini in attesa e non apro nuove posizioni; gli stop restano. " +
"Da qui non si riparte: si riparte solo dall'interfaccia, pagina Rischio.\nPer confermare scrivi /conferma entro 2 minuti.";
case "conferma":
if (_stopAskedAt is { } asked && clock.UtcNow - asked <= ConfirmWithin)
{
_stopAskedAt = null;
return await desk.StopAllAsync(cancellationToken).ConfigureAwait(false);
}
_stopAskedAt = null;
return "Non c'è niente da confermare: scrivi prima /ferma.";
default:
return "Non conosco questo comando.\n" + Help;
}
}
}
/// <summary>
/// Reads the messages sent to the bot and answers the commands (SPEC 14). Only the chat of the settings is obeyed;
/// the others get no answer at all. A message older than five minutes, found after a stop of the bot, is not
/// obeyed: a /pausa of yesterday must not pause today.
/// </summary>
public sealed partial class TelegramBot(IClock clock, Func<CancellationToken, Task<TelegramSettings?>> settings, Func<string, TelegramClient> client,
TelegramCommands commands, ILogger logger)
{
public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5);
/// <summary>How long one call waits for a message on Telegram's side.</summary>
public int WaitSeconds { get; init; } = 25;
/// <summary>The pause after a failure, or while Telegram is not configured.</summary>
public TimeSpan Retry { get; init; } = TimeSpan.FromSeconds(30);
private long _offset;
/// <summary>One read of the messages; the answer is how many commands were obeyed.</summary>
public async Task<int> PollOnceAsync(CancellationToken cancellationToken)
{
if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram)
{
return -1;
}
var bot = client(telegram.Token);
var updates = await bot.GetUpdatesAsync(_offset, WaitSeconds, cancellationToken).ConfigureAwait(false);
var obeyed = 0;
foreach (var update in updates)
{
_offset = Math.Max(_offset, update.UpdateId + 1);
if (update.ChatId != telegram.ChatId)
{
LogStranger(logger, update.ChatId ?? "?");
continue;
}
if (update.Text is not { } text || update.Date is not { } date || clock.UtcNow - date > StaleAfter)
{
continue;
}
string? answer;
try
{
answer = await commands.AnswerAsync(text, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogCommandFailed(logger, ex);
answer = "Non ci sono riuscito: " + Redactor.Redact(ex.Message);
}
if (answer is not null)
{
obeyed++;
await bot.SendAsync(telegram.ChatId, answer, cancellationToken).ConfigureAwait(false);
}
}
return obeyed;
}
/// <summary>The loop: reads, answers, and after a failure waits and tries again.</summary>
public async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
TimeSpan? pause = null;
try
{
if (await PollOnceAsync(cancellationToken).ConfigureAwait(false) < 0)
{
pause = Retry;
}
}
catch (TelegramException ex)
{
LogPollFailed(logger, ex.Message);
pause = ex.RetryAfter is { } after && after > Retry ? after : Retry;
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// The database or the network failed in a way Telegram did not report: the loop goes on after a pause.
LogLoopFailed(logger, ex);
pause = Retry;
}
if (pause is { } wait)
{
await Task.Delay(wait, cancellationToken).ConfigureAwait(false);
}
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Telegram message from another chat ignored: {Chat}")]
private static partial void LogStranger(ILogger logger, string chat);
[LoggerMessage(Level = LogLevel.Warning, Message = "Telegram read failed: {Error}")]
private static partial void LogPollFailed(ILogger logger, string error);
[LoggerMessage(Level = LogLevel.Error, Message = "Reading the Telegram commands failed")]
private static partial void LogLoopFailed(ILogger logger, Exception ex);
[LoggerMessage(Level = LogLevel.Error, Message = "Telegram command failed")]
private static partial void LogCommandFailed(ILogger logger, Exception ex);
}
/// <summary>
/// The sign of life (SPEC 14): a call to an outside checking service every minute. When the calls stop, that
/// service warns the user: the only way to know the bot is off while it is off.
/// </summary>
public sealed partial class Heartbeat(HttpClient http, IClock clock, Func<CancellationToken, Task<Uri?>> address, ILogger logger)
{
public DateTimeOffset? LastOk { get; private set; }
public string? LastError { get; private set; }
/// <summary>True when the call went through; false when there is no address or it failed.</summary>
public async Task<bool> BeatAsync(CancellationToken cancellationToken)
{
if (await address(cancellationToken).ConfigureAwait(false) is not { } url)
{
return false;
}
try
{
using var response = await http.GetAsync(url, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
LastOk = clock.UtcNow;
LastError = null;
return true;
}
LastError = $"Il servizio ha risposto {(int)response.StatusCode}.";
}
catch (HttpRequestException ex)
{
LastError = "Il servizio non risponde: " + Redactor.Redact(ex.Message);
}
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
{
LastError = "Il servizio non ha risposto in tempo.";
}
LogFailed(logger, LastError);
return false;
}
/// <summary>An address the interface accepts: https, or http only on this computer or the local network.</summary>
public static string? Check(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http"))
{
return "Serve un indirizzo che inizi con https://.";
}
return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || IsPrivate(uri.Host))
? "Fuori dalla rete di casa serve https://."
: null;
}
/// <summary>An address of a home network: 10.x, 172.16-31.x, 192.168.x, link-local, or their IPv6 equivalents.</summary>
private static bool IsPrivate(string host)
{
if (!System.Net.IPAddress.TryParse(host.Trim('[', ']'), out var ip))
{
return false;
}
if (ip.IsIPv4MappedToIPv6)
{
ip = ip.MapToIPv4();
}
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
return System.Net.IPAddress.IsLoopback(ip) || ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal;
}
var b = ip.GetAddressBytes();
return b[0] == 10 || b[0] == 127 || (b[0] == 172 && b[1] is >= 16 and <= 31) || (b[0] == 192 && b[1] == 168) || (b[0] == 169 && b[1] == 254);
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")]
private static partial void LogFailed(ILogger logger, string error);
}
+156
View File
@@ -0,0 +1,156 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Anubis.Core;
namespace Anubis.Notifications;
/// <summary>A refusal or failure of the Telegram Bot API. <see cref="Retryable"/>: the network, a 429 or a 5xx.</summary>
public sealed class TelegramException : Exception
{
public TelegramException()
{
}
public TelegramException(string message)
: base(message)
{
}
public TelegramException(string message, Exception innerException)
: base(message, innerException)
{
}
public TelegramException(string message, bool retryable, TimeSpan? retryAfter = null)
: base(message)
{
Retryable = retryable;
RetryAfter = retryAfter;
}
public bool Retryable { get; }
/// <summary>The wait Telegram asks for after a 429.</summary>
public TimeSpan? RetryAfter { get; }
}
/// <summary>A message to the bot: who wrote it (the chat), what and when.</summary>
public sealed record TelegramUpdate(long UpdateId, string? ChatId, string? Text, DateTimeOffset? Date);
/// <summary>
/// The Telegram Bot API (SPEC 14): plain text messages to the user's chat. The token is part of the address, so the
/// address is never logged; errors carry only Telegram's own description.
/// </summary>
public sealed class TelegramClient
{
public static readonly Uri DefaultBase = new("https://api.telegram.org/");
private static readonly string[] MessagesOnly = ["message"];
private readonly HttpClient _http;
private readonly string _token;
private readonly Uri _base;
public TelegramClient(HttpClient http, string token, Uri? baseUrl = null)
{
_http = http ?? throw new ArgumentNullException(nameof(http));
_token = token ?? throw new ArgumentNullException(nameof(token));
_base = baseUrl ?? DefaultBase;
Redactor.Register(token);
}
/// <summary>Telegram's limit for one message; longer texts are cut with an ellipsis.</summary>
public const int MaxLength = 4096;
public async Task SendAsync(string chatId, string text, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(text);
if (text.Length > MaxLength)
{
text = text[..(MaxLength - 1)] + "…";
}
using var answer = await CallAsync("sendMessage", new Dictionary<string, object> { ["chat_id"] = chatId, ["text"] = text, ["disable_web_page_preview"] = true },
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The messages sent to the bot after <paramref name="offset"/>, waiting up to <paramref name="waitSeconds"/> for
/// one (long polling). The next call passes the last update's id plus one, which tells Telegram they were read.
/// </summary>
public async Task<IReadOnlyList<TelegramUpdate>> GetUpdatesAsync(long offset, int waitSeconds, CancellationToken cancellationToken)
{
using var answer = await CallAsync("getUpdates", new Dictionary<string, object> { ["offset"] = offset, ["timeout"] = waitSeconds, ["allowed_updates"] = MessagesOnly },
cancellationToken).ConfigureAwait(false);
var updates = new List<TelegramUpdate>();
foreach (var item in answer.RootElement.GetProperty("result").EnumerateArray())
{
string? chat = null;
string? text = null;
DateTimeOffset? date = null;
if (item.TryGetProperty("message", out var message))
{
chat = message.TryGetProperty("chat", out var c) && c.TryGetProperty("id", out var id) ? id.GetRawText().Trim('"') : null;
text = message.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
date = message.TryGetProperty("date", out var d) && d.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null;
}
updates.Add(new TelegramUpdate(item.GetProperty("update_id").GetInt64(), chat, text, date));
}
return updates;
}
/// <summary>The bot's own name: the test of Impostazioni, which proves the token works without writing to anyone.</summary>
public async Task<string> GetMeAsync(CancellationToken cancellationToken)
{
using var answer = await CallAsync("getMe", new Dictionary<string, object>(), cancellationToken).ConfigureAwait(false);
return answer.RootElement.GetProperty("result").TryGetProperty("username", out var name) ? name.GetString() ?? "" : "";
}
/// <summary>One call of the Bot API; the answer's <c>result</c> when Telegram says ok.</summary>
public async Task<JsonDocument> CallAsync(string method, object body, CancellationToken cancellationToken)
{
HttpResponseMessage response;
try
{
response = await _http.PostAsJsonAsync(new Uri(_base, $"bot{_token}/{method}"), body, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException ex)
{
throw new TelegramException("Telegram non risponde: " + Redactor.Redact(ex.Message), retryable: true);
}
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TelegramException("Telegram non ha risposto in tempo.", retryable: true);
}
using (response)
{
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
JsonDocument? json = null;
try
{
json = JsonDocument.Parse(text);
}
catch (JsonException)
{
}
if (response.IsSuccessStatusCode && json is not null && json.RootElement.TryGetProperty("ok", out var ok) && ok.GetBoolean())
{
return json;
}
var description = json is not null && json.RootElement.TryGetProperty("description", out var d) ? d.GetString() : null;
TimeSpan? after = json is not null && json.RootElement.TryGetProperty("parameters", out var p) && p.TryGetProperty("retry_after", out var r)
? TimeSpan.FromSeconds(r.GetInt32())
: null;
json?.Dispose();
var status = (int)response.StatusCode;
throw new TelegramException($"Telegram ha risposto {status}: {Redactor.Redact(description ?? response.ReasonPhrase ?? "")}",
retryable: response.StatusCode == HttpStatusCode.TooManyRequests || status >= 500, after);
}
}
}
+158
View File
@@ -0,0 +1,158 @@
using System.Diagnostics;
using System.IO.Pipes;
using System.Security.Cryptography;
using System.Text;
namespace Anubis.Supervision;
/// <summary>
/// The engine as a child process of the guard, with its channel: a named pipe open to this user only, created
/// before the process starts. The child's output goes where the guard's goes (the container log).
/// </summary>
public sealed class ChildEngine : IEngineProcess
{
private readonly Process _process;
private readonly NamedPipeServerStream _pipe;
private readonly CancellationTokenSource _stop = new();
private readonly SemaphoreSlim _write = new(1, 1);
private readonly Task _reading;
private readonly TaskCompletionSource _connected = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _disposed;
private ChildEngine(Process process, NamedPipeServerStream pipe, Action<GuardMessage> onMessage)
{
_process = process;
_pipe = pipe;
Exited = WaitAsync(process);
_reading = Task.Run(() => ReadAsync(onMessage, _stop.Token));
}
public Task<int> Exited { get; }
/// <summary>
/// Starts <paramref name="file"/> with <paramref name="arguments"/> and the guard's environment, plus the pipe's
/// name; the drill's fault only when <see cref="EngineStart.Fault"/> asks for it.
/// </summary>
public static ChildEngine Start(string file, IEnumerable<string> arguments, IReadOnlyDictionary<string, string?> environment, EngineStart start)
{
ArgumentNullException.ThrowIfNull(arguments);
ArgumentNullException.ThrowIfNull(environment);
ArgumentNullException.ThrowIfNull(start);
var name = "anubis-" + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(8));
var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
var info = new ProcessStartInfo(file) { UseShellExecute = false };
foreach (var argument in arguments)
{
info.ArgumentList.Add(argument);
}
info.Environment.Clear();
foreach (var (key, value) in environment)
{
if (value is not null && key != GuardChannel.FaultVariable && key != GuardChannel.PipeVariable)
{
info.Environment[key] = value;
}
}
info.Environment[GuardChannel.PipeVariable] = name;
if (start.Fault && environment.GetValueOrDefault(GuardChannel.FaultVariable) is { Length: > 0 } fault)
{
info.Environment[GuardChannel.FaultVariable] = fault;
}
try
{
var process = Process.Start(info) ?? throw new InvalidOperationException("Il motore non è partito.");
return new ChildEngine(process, pipe, start.OnMessage);
}
catch
{
pipe.Dispose();
throw;
}
}
public async Task RequestStopAsync(CancellationToken cancellationToken)
{
await _connected.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
await _write.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var bytes = Encoding.UTF8.GetBytes(GuardChannel.Write(new GuardMessage(GuardMessageTypes.Stop)) + "\n");
await _pipe.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
await _pipe.FlushAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_write.Release();
}
}
public void Kill()
{
try
{
if (!_process.HasExited)
{
_process.Kill(entireProcessTree: true);
}
}
catch (InvalidOperationException)
{
// Already gone.
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_stop.Cancel();
try
{
_reading.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException)
{
}
_pipe.Dispose();
_process.Dispose();
_stop.Dispose();
_write.Dispose();
}
private static async Task<int> WaitAsync(Process process)
{
await process.WaitForExitAsync().ConfigureAwait(false);
return process.ExitCode;
}
private async Task ReadAsync(Action<GuardMessage> onMessage, CancellationToken cancellationToken)
{
try
{
await _pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
_connected.TrySetResult();
using var reader = new StreamReader(_pipe, Encoding.UTF8, leaveOpen: true);
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
if (GuardChannel.Read(line) is { } message)
{
onMessage(message);
}
}
}
catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException)
{
}
finally
{
_connected.TrySetCanceled(CancellationToken.None);
}
}
}
+53
View File
@@ -0,0 +1,53 @@
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Notifications;
using Anubis.Trading;
using Microsoft.Extensions.Logging;
namespace Anubis.Supervision;
/// <summary>The broker adapters and the warnings of the guard, from the keys the engine handed it in memory.</summary>
public static class GuardBrokers
{
/// <summary>
/// The adapter of a demo account. Real accounts get none until the real-money phase gives the guard the startup
/// consent of its own (ADR 0012); the simulator needs none, the engine is its broker.
/// </summary>
public static IBrokerAccount? Create(HttpClient http, IClock clock, GuardAccount account, IReadOnlyList<GuardKeys> keys)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(keys);
if (account.Environment != TradingEnvironments.Demo || keys.FirstOrDefault(k => k.Service == account.Broker && k.Environment == account.Environment) is not { } key)
{
return null;
}
return account.Broker switch
{
Venues.Alpaca when key.Values.Count >= 2 => new AlpacaTrading(http, clock, new AlpacaCredentials(key.Values[0], key.Values[1]),
new AlpacaTradingOptions { Environment = account.Environment }, TradingConsent.None),
Venues.Okx when key.Values.Count >= 3 => new OkxTrading(http, clock, new OkxCredentials(key.Values[0], key.Values[1], key.Values[2]),
new OkxTradingOptions { Environment = account.Environment }, TradingConsent.None),
_ => null,
};
}
/// <summary>The guard's warning: always in its log, and on Telegram when the engine handed it the bot's token and chat.</summary>
public static async Task AlertAsync(HttpClient http, ILogger logger, IReadOnlyList<GuardKeys> keys, string text, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
GuardLog.Alert(logger, text.ReplaceLineEndings(" "));
if (keys.FirstOrDefault(k => k.Service == GuardKeys.Telegram) is { Values.Count: >= 2 } telegram)
{
await new TelegramClient(http, telegram.Values[0]).SendAsync(telegram.Values[1], "Anubis, guardia" + Environment.NewLine + text, cancellationToken)
.ConfigureAwait(false);
}
}
}
internal static partial class GuardLog
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard alert: {Text}")]
public static partial void Alert(ILogger logger, string text);
}
+450
View File
@@ -0,0 +1,450 @@
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
using Anubis.Trading;
using Microsoft.Extensions.Logging;
namespace Anubis.Supervision;
/// <summary>The outcome of the guard drill, line by line in Italian.</summary>
public sealed record DrillResult(bool Passed, IReadOnlyList<string> Lines);
/// <summary>
/// The guard drill (issue #48, ADR 0012): the real guard and the real engine, as child process, in a folder of their
/// own with a SQLite database. A position of 0.01 BTC with its stop on the internal simulator and a sale already
/// decided; the engine starts with the fault that blocks its main loop right after the sale leaves, with the stop
/// removed. The drill passes when the guard intervened, the engine restarted, the sale left open was canceled, the
/// stop came back for the whole quantity and the guard's note reached the diary. Prices come from a small local
/// server that answers like OKX: nothing leaves the computer. Same drill in the tests and in the Docker image.
/// </summary>
public static class GuardDrill
{
public const decimal Quantity = 0.01m;
public const decimal StopLevel = 45000m;
/// <summary>Times short enough for a drill of about two minutes.</summary>
public static GuardOptions Options { get; } = new()
{
Silence = TimeSpan.FromSeconds(20),
StalledStart = TimeSpan.FromMinutes(3),
GracefulStop = TimeSpan.FromSeconds(30),
};
/// <summary>The drill in a new temporary folder, removed at the end. Exit code 0 when it passes.</summary>
public static async Task<int> RunAsync(string serverDll, TextWriter output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(output);
var folder = Path.Combine(Path.GetTempPath(), "anubis-drill-" + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(6)));
try
{
var result = await RunInAsync(folder, serverDll, Options, line => output.WriteLine(line), cancellationToken).ConfigureAwait(false);
await output.WriteLineAsync(result.Passed ? "Esercitazione della guardia superata." : "Esercitazione della guardia NON superata.").ConfigureAwait(false);
return result.Passed ? 0 : 1;
}
finally
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A leftover temporary folder is harmless.
}
}
}
public static async Task<DrillResult> RunInAsync(string folder, string serverDll, GuardOptions options, Action<string> say, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(say);
var lines = new List<string>();
void Say(string line)
{
lines.Add(line);
say(line);
}
var data = new DataDirectory(folder);
data.Ensure();
using var okx = FakeOkx.Start();
var held = await SeedAsync(data, cancellationToken).ConfigureAwait(false);
Say($"Preparato: {Format.Quantity(held)} BTC con lo stop a {Format.Price(StopLevel)} e una vendita già decisa.");
var environment = ChildEnvironment(okx.Address);
var clock = SystemClock.Instance;
var logger = new LineLogger(Say);
var guardian = new Guardian(new GuardPaths(folder), clock, options,
start => ChildEngine.Start(GuardLaunch.Dotnet(), [serverDll, "--platform", "docker", "--data-dir", folder], environment, start),
(_, _) => null, (text, _, _) =>
{
Say("Avviso della guardia: " + text.ReplaceLineEndings(" "));
return Task.CompletedTask;
}, logger);
guardian.Start(fault: true);
using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var guarding = guardian.RunAsync(stop.Token);
var intervened = await WaitAsync(() => guardian.Interventions > 0, options.Silence + TimeSpan.FromMinutes(3), cancellationToken).ConfigureAwait(false);
var restarted = intervened && await WaitAsync(() => guardian.EngineAlive && guardian.Stage == GuardStages.Running, TimeSpan.FromMinutes(3), cancellationToken)
.ConfigureAwait(false);
// "Running" comes as soon as the scheduler starts: the restart's own work (adopting the stop, cancelling the sale
// left halfway, planning it again) may take a few more seconds on a busy machine.
if (restarted)
{
var noted = guardian.Notes;
await WaitForRepairAsync(data, noted.Count > 0 ? noted[0].At : DateTimeOffset.MinValue, TimeSpan.FromMinutes(2), cancellationToken).ConfigureAwait(false);
}
await stop.CancelAsync().ConfigureAwait(false);
var code = await guarding.ConfigureAwait(false);
Say($"Motore fermato in ordine alla fine dell'esercitazione (codice {code}).");
var passed = Check(intervened, "La guardia è intervenuta dopo il silenzio del ciclo principale.", "La guardia non è intervenuta.", Say);
passed &= Check(restarted, "Il motore è ripartito e il suo ciclo batte di nuovo.", "Il motore non è ripartito.", Say);
var notes = guardian.Notes;
var at = notes.Count > 0 ? notes[0].At : DateTimeOffset.MaxValue;
await using (var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: false))
{
var hung = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM orders WHERE side = 'sell' AND purpose = 'exit' AND created_at < @t", ("t", at)), cancellationToken)
.ConfigureAwait(false);
var canceled = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE side = 'sell' AND purpose = 'exit' AND status = 'canceled' AND reason = @r",
("r", LiveReasons.Restart)), cancellationToken).ConfigureAwait(false);
var stops = await db.ReadAsync(s => s.QueryAsync("SELECT quantity FROM orders WHERE purpose = 'stop' AND created_at > @t", r => r.Money("quantity"), ("t", at)),
cancellationToken).ConfigureAwait(false);
var noted = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention'"), cancellationToken).ConfigureAwait(false);
var again = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM planned_orders WHERE side = 'sell' AND created_at > @t", ("t", at)), cancellationToken)
.ConfigureAwait(false);
passed &= Check(hung > 0, "Prima dell'intervento la vendita era partita, senza più lo stop.", "La vendita non era partita prima dell'intervento.", Say);
passed &= Check(canceled > 0, "Alla ripartenza la vendita rimasta a metà è stata annullata.", "La vendita rimasta a metà non è stata annullata.", Say);
passed &= Check(stops.Any(q => q == held), $"Lo stop è tornato per tutti i {Format.Quantity(held)} BTC.", "Lo stop non è tornato per l'intera quantità.", Say);
passed &= Check(again > 0, "La vendita già decisa è ripartita con un ordine nuovo.", "La vendita già decisa non è ripartita.", Say);
passed &= Check(noted > 0, "La nota della guardia è nel diario.", "La nota della guardia non è nel diario.", Say);
}
return new DrillResult(passed, lines);
}
private static async Task WaitForRepairAsync(DataDirectory data, DateTimeOffset intervention, TimeSpan timeout, CancellationToken cancellationToken)
{
var until = SystemClock.Instance.UtcNow + timeout;
await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: false);
while (SystemClock.Instance.UtcNow < until)
{
var done = await db.ReadAsync(async s =>
await s.CountAsync("SELECT COUNT(*) FROM executions WHERE side = 'sell' AND purpose = 'exit' AND status = 'canceled' AND reason = @r",
("r", LiveReasons.Restart)).ConfigureAwait(false) > 0
&& await s.CountAsync("SELECT COUNT(*) FROM planned_orders WHERE side = 'sell'").ConfigureAwait(false) > 1
&& await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention'").ConfigureAwait(false) > 0
&& await s.CountAsync("SELECT COUNT(*) FROM orders WHERE purpose = 'stop' AND created_at > @t", ("t", intervention)).ConfigureAwait(false) > 0,
cancellationToken).ConfigureAwait(false);
if (done)
{
return;
}
await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false);
}
}
private static bool Check(bool ok, string yes, string no, Action<string> say)
{
say((ok ? "OK " : "NO ") + (ok ? yes : no));
return ok;
}
private static async Task<bool> WaitAsync(Func<bool> condition, TimeSpan timeout, CancellationToken cancellationToken)
{
var until = SystemClock.Instance.UtcNow + timeout;
while (!condition())
{
if (SystemClock.Instance.UtcNow > until)
{
return false;
}
await Task.Delay(250, cancellationToken).ConfigureAwait(false);
}
return true;
}
private static Dictionary<string, string?> ChildEnvironment(Uri okx)
{
var environment = new Dictionary<string, string?>(StringComparer.Ordinal);
foreach (System.Collections.DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
var key = (string)entry.Key;
if (!key.StartsWith("ANUBIS_", StringComparison.Ordinal) && !key.StartsWith("ALPACA_", StringComparison.Ordinal) &&
!key.StartsWith("OKX_", StringComparison.Ordinal) && !key.StartsWith("TELEGRAM_", StringComparison.Ordinal))
{
environment[key] = entry.Value as string;
}
}
environment["ANUBIS_PLATFORM"] = "docker";
environment["ANUBIS_DB_ENGINE"] = "sqlite";
environment["ANUBIS_SECRET_KEY"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(24));
environment["ANUBIS_ADMIN_PASSWORD"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(12));
environment["PORT"] = FreePort().ToString(CultureInfo.InvariantCulture);
environment["TZ"] = "Europe/Rome";
environment[DrillOkxVariable] = okx.ToString();
environment[GuardChannel.FaultVariable] = GuardChannel.HangMidSale;
return environment;
}
/// <summary>
/// The address of the local server that answers like OKX in the drill. Honored only on this computer's own
/// addresses (loopback): it can never point the bot at a price source elsewhere.
/// </summary>
public const string DrillOkxVariable = "ANUBIS_DRILL_OKX_URL";
/// <summary>The OKX addresses of the drill, or null when the variable is missing or not a loopback address.</summary>
public static Brokers.OkxOptions? DrillOkx(IReadOnlyDictionary<string, string?> environment)
{
ArgumentNullException.ThrowIfNull(environment);
if (environment.GetValueOrDefault(DrillOkxVariable) is not { Length: > 0 } text || !Uri.TryCreate(text, UriKind.Absolute, out var url) || !url.IsLoopback)
{
return null;
}
var socket = new UriBuilder(url) { Scheme = "ws" };
return new Brokers.OkxOptions
{
RestUrl = url,
PublicStreamUrl = new Uri(socket.Uri, "/ws/v5/public"),
BusinessStreamUrl = new Uri(socket.Uri, "/ws/v5/business"),
};
}
// The database the engine will find: installation, accounts, BTC, the capital, a filled purchase with its stop on
// the simulator, and the sale decided for now. Built with the same order manager the engine uses.
private static async Task<decimal> SeedAsync(DataDirectory data, CancellationToken cancellationToken)
{
var clock = SystemClock.Instance;
await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: true);
await Migrations.MigrateAsync(db, clock, null, cancellationToken).ConfigureAwait(false);
var identity = await Installation.CheckAsync(db, data, clock, cancellationToken).ConfigureAwait(false);
var accounts = await AccountSetup.EnsureAsync(db, clock, alpacaDemo: false, okxDemo: false, cancellationToken).ConfigureAwait(false);
var account = accounts.First(a => a.Broker == Venues.Okx && a.Environment == TradingEnvironments.Simulation);
var btc = await new InstrumentCatalog(db, clock).EnsureAsync(new InstrumentSpec(Venues.Okx, "BTC-EUR", "BTC-EUR", AssetClasses.Crypto, "EUR")
{
BaseCurrency = "BTC",
TickSize = 0.1m,
LotSize = 0.00000001m,
MinSize = 0.00001m,
Status = "live",
}, cancellationToken).ConfigureAwait(false);
var ledger = new Ledger(db, clock);
await new Capital(db, clock, ledger, new FxStore(db, clock)).SetAsync(Venues.Okx, 1000m, "esercitazione", cancellationToken).ConfigureAwait(false);
Task<Quote?> QuoteAsync(string symbol, CancellationToken _) => Task.FromResult<Quote?>(new Quote(symbol, FakeOkx.Bid, FakeOkx.Ask, clock.UtcNow));
using var paper = new PaperBroker(PaperOptions.Okx() with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, clock, QuoteAsync,
symbol => symbol == btc.Symbol ? btc.Spec : null, new PaperBookStore(db, clock, account.AccountId));
await paper.DepositAsync(1000m, "EUR", cancellationToken).ConfigureAwait(false);
using var manager = new OrderManager(db, clock, ledger, paper, account, ClientOrderIds.InstallationCode(identity.File!.InstallationId),
(id, _) => Task.FromResult<Instrument?>(id == btc.Id ? btc : null), QuoteAsync)
{
PassiveSteps = 0,
ConfirmPrice = QuoteAsync,
MarketOpen = (_, _) => Task.FromResult(true),
};
var (_, refusal) = await manager.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, Quantity, OrderPurpose.Entry, Ids.NewId(clock))
{
StopLevel = StopLevel,
}, cancellationToken).ConfigureAwait(false);
if (refusal is not null)
{
throw new InvalidOperationException("Esercitazione: acquisto rifiutato (" + refusal + ").");
}
for (var i = 0; ; i++)
{
await paper.PumpAsync(cancellationToken).ConfigureAwait(false);
await manager.TickAsync(cancellationToken).ConfigureAwait(false);
var stops = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM orders WHERE purpose = 'stop' AND status = 'submitted'"), cancellationToken).ConfigureAwait(false);
if (stops > 0)
{
break;
}
if (i > 100)
{
throw new InvalidOperationException("Esercitazione: la posizione non ha avuto il suo stop.");
}
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
var held = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).Single().Quantity;
var now = clock.UtcNow;
await db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, " +
"due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, 'sell', 'exit', @q, @x, NULL, NULL, @r, 'esercitazione', " +
"@now, NULL, 'pending', NULL, NULL, @now, @now)", cancellationToken,
("id", Ids.NewId(clock)), ("d", Ids.NewId(clock)), ("s", StrategyNames.CryptoTrend), ("a", account.AccountId), ("i", btc.Id), ("q", held), ("x", true),
("r", FakeOkx.Bid), ("now", now)), cancellationToken).ConfigureAwait(false);
return held;
}
private static int FreePort()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
/// <summary>
/// A local server that answers like OKX's REST interface with a fixed price for every ticker and nothing for the
/// rest; anything else (the streams) gets 404. Plain HTTP/1.1 on the loopback address, one request per connection.
/// </summary>
private sealed class FakeOkx : IDisposable
{
public const decimal Bid = 50000m;
public const decimal Ask = 50010m;
private readonly TcpListener _listener;
private readonly CancellationTokenSource _stop = new();
private readonly Task _loop;
private FakeOkx()
{
_listener = new TcpListener(IPAddress.Loopback, 0);
_listener.Start();
Address = new Uri($"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/");
_loop = Task.Run(() => AcceptAsync(_stop.Token));
}
public Uri Address { get; }
public static FakeOkx Start() => new();
public void Dispose()
{
_stop.Cancel();
_listener.Stop();
try
{
_loop.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException)
{
}
_stop.Dispose();
}
private async Task AcceptAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
{
return;
}
_ = Task.Run(() => AnswerAsync(client, cancellationToken), CancellationToken.None);
}
}
private static async Task AnswerAsync(TcpClient client, CancellationToken cancellationToken)
{
using (client)
{
try
{
var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.ASCII, leaveOpen: true);
var request = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) ?? "";
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { Length: > 0 })
{
}
var target = request.Split(' ') is [_, var path, ..] ? path : "/";
var (status, body) = Route(target);
var bytes = Encoding.UTF8.GetBytes(body);
var head = $"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n";
await stream.WriteAsync(Encoding.ASCII.GetBytes(head), cancellationToken).ConfigureAwait(false);
await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or OperationCanceledException or SocketException)
{
}
}
}
private static (string Status, string Body) Route(string target)
{
if (target.StartsWith("/ws", StringComparison.Ordinal))
{
return ("404 Not Found", "{}");
}
if (target.StartsWith("/api/v5/market/ticker?instId=", StringComparison.Ordinal))
{
var symbol = Uri.UnescapeDataString(target["/api/v5/market/ticker?instId=".Length..]);
var ts = SystemClock.Instance.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
return ("200 OK", $"{{\"code\":\"0\",\"msg\":\"\",\"data\":[{{\"instId\":\"{symbol}\",\"bidPx\":\"{Bid.ToString(CultureInfo.InvariantCulture)}\"," +
$"\"askPx\":\"{Ask.ToString(CultureInfo.InvariantCulture)}\",\"bidSz\":\"1\",\"askSz\":\"1\",\"ts\":\"{ts}\"}}]}}");
}
// The list of instruments has the drill's one: an instrument missing from it is taken as delisted.
if (target.StartsWith("/api/v5/public/instruments", StringComparison.Ordinal))
{
return ("200 OK", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"instId\":\"BTC-EUR\",\"baseCcy\":\"BTC\",\"quoteCcy\":\"EUR\",\"tickSz\":\"0.1\",\"lotSz\":\"0.00000001\",\"minSz\":\"0.00001\",\"state\":\"live\"}]}");
}
return ("200 OK", "{\"code\":\"0\",\"msg\":\"\",\"data\":[]}");
}
}
}
/// <summary>How the guard finds the .NET host and the engine next to itself.</summary>
public static class GuardLaunch
{
/// <summary>The <c>dotnet</c> host that runs the engine: the one running now when it is dotnet itself, otherwise the one the SDK names.</summary>
public static string Dotnet()
{
if (Environment.ProcessPath is { } current && Path.GetFileNameWithoutExtension(current).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
{
return current;
}
return Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") is { Length: > 0 } host ? host : "dotnet";
}
/// <summary>The engine's program next to the guard's.</summary>
public static string Server() => Path.Combine(AppContext.BaseDirectory, "Anubis.Server.dll");
}
/// <summary>A logger that writes one line per message: the guard's log goes where the container's goes.</summary>
public sealed class LineLogger(Action<string> write) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
ArgumentNullException.ThrowIfNull(formatter);
if (!IsEnabled(logLevel))
{
return;
}
var text = Redactor.Redact(formatter(state, exception) + (exception is null ? "" : " — " + exception.Message));
write($"{SystemClock.Instance.UtcNow:yyyy-MM-dd HH:mm:ss} guardia {logLevel}: {text}");
}
}
+170
View File
@@ -0,0 +1,170 @@
using System.IO.Pipes;
using System.Text;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Supervision;
/// <summary>
/// The engine's end of the channel to the guard (SPEC 9.3): the beat of the main loop, the startup steps, the keys
/// and the stops it decides. Messages wait in a short queue and the oldest beats give way: a slow guard never slows
/// the engine. When the guard is gone the engine goes on by itself.
/// </summary>
public sealed partial class GuardLink : IAsyncDisposable
{
private readonly Lock _gate = new();
private readonly NamedPipeClientStream _pipe;
private readonly Channel<GuardMessage> _outgoing = Channel.CreateBounded<GuardMessage>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
private readonly CancellationTokenSource _stop = new();
private readonly ILogger _logger;
private readonly Task _loop;
private string _stage = GuardStages.Starting;
private string? _step;
private GuardLink(string pipeName, ILogger logger)
{
_logger = logger;
_pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
_loop = Task.Run(() => RunAsync(_stop.Token));
}
/// <summary>The link when a guard started this engine (<see cref="GuardChannel.PipeVariable"/>); null otherwise.</summary>
public static GuardLink? FromEnvironment(IReadOnlyDictionary<string, string?> environment, ILogger? logger = null)
{
ArgumentNullException.ThrowIfNull(environment);
return environment.GetValueOrDefault(GuardChannel.PipeVariable) is { Length: > 0 } name ? new GuardLink(name, logger ?? NullLogger.Instance) : null;
}
/// <summary>The guard asked for an orderly stop.</summary>
public Action? StopRequested { get; set; }
public string Stage
{
get
{
lock (_gate)
{
return _stage;
}
}
}
/// <summary>A new stage or startup step: told to the guard at once.</summary>
public void Set(string stage, string? step = null)
{
lock (_gate)
{
if (_stage == stage && _step == step)
{
return;
}
_stage = stage;
_step = step;
}
Beat();
}
/// <summary>A step of the startup of SPEC 9.4.</summary>
public void Step(string step) => Set(GuardStages.Starting, step);
/// <summary>Alive, at the current stage.</summary>
public void Beat()
{
GuardMessage message;
lock (_gate)
{
message = GuardMessage.Beat(_stage, _step);
}
_outgoing.Writer.TryWrite(message);
}
public void SendKeys(IReadOnlyList<GuardKeys> keys) => _outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Keys) { Keys = keys });
/// <summary>A stop decided by the engine: the guard will not restart it. Waits a moment for the message to leave.</summary>
public async Task AnnounceAsync(string reason)
{
_outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Stopping) { Reason = reason });
for (var i = 0; i < 20 && _outgoing.Reader.Count > 0; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync().ConfigureAwait(false);
try
{
await _loop.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
await _pipe.DisposeAsync().ConfigureAwait(false);
_stop.Dispose();
}
private async Task RunAsync(CancellationToken cancellationToken)
{
try
{
await _pipe.ConnectAsync(TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException)
{
LogNoGuard(_logger, ex.Message);
return;
}
var reading = ReadAsync(cancellationToken);
var writer = new StreamWriter(_pipe, new UTF8Encoding(false), leaveOpen: true) { AutoFlush = true, NewLine = "\n" };
await using (writer.ConfigureAwait(false))
{
try
{
await foreach (var message in _outgoing.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
await writer.WriteLineAsync(GuardChannel.Write(message).AsMemory(), cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (IOException ex)
{
LogGuardLost(_logger, ex.Message);
}
}
await reading.ConfigureAwait(false);
}
private async Task ReadAsync(CancellationToken cancellationToken)
{
using var reader = new StreamReader(_pipe, Encoding.UTF8, leaveOpen: true);
try
{
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
if (GuardChannel.Read(line) is { Type: GuardMessageTypes.Stop })
{
StopRequested?.Invoke();
}
}
}
catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException)
{
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel not reached: {Reason}. The engine runs without its guard.")]
private static partial void LogNoGuard(ILogger logger, string reason);
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel lost: {Reason}")]
private static partial void LogGuardLost(ILogger logger, string reason);
}
+120
View File
@@ -0,0 +1,120 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Anubis.Supervision;
/// <summary>
/// The channel between the guard and the engine (SPEC 9.3, ADR 0012): a local named pipe whose name the guard puts
/// in <see cref="PipeVariable"/>, one JSON message per line. The engine sends its beat, the startup steps, the broker
/// keys (in memory only) and the stops it decides; the guard sends only "stop".
/// </summary>
public static class GuardChannel
{
/// <summary>The pipe the engine connects to. Without it the engine runs on its own (development, tests).</summary>
public const string PipeVariable = "ANUBIS_GUARD_PIPE";
/// <summary>
/// Fault injection for the guard drill (ADR 0012): <see cref="HangMidSale"/> blocks the main loop right after a sale
/// leaves. The guard never passes it to an engine it restarts.
/// </summary>
public const string FaultVariable = "ANUBIS_FAULT";
public const string HangMidSale = "hang-mid-sale";
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() },
};
public static string Write(GuardMessage message) => JsonSerializer.Serialize(message, Json);
/// <summary>A line of the channel; null when it is not a message (a broken line is ignored, never fatal).</summary>
public static GuardMessage? Read(string? line)
{
if (string.IsNullOrWhiteSpace(line))
{
return null;
}
try
{
return JsonSerializer.Deserialize<GuardMessage>(line, Json) is { Type.Length: > 0 } message ? message : null;
}
catch (JsonException)
{
return null;
}
}
}
public static class GuardMessageTypes
{
/// <summary>Engine to guard: alive, with its stage and the startup step it is on.</summary>
public const string Beat = "beat";
/// <summary>Engine to guard: the keys of the broker accounts and of Telegram, kept in memory only.</summary>
public const string Keys = "keys";
/// <summary>Engine to guard: a stop decided by the engine (exit, restore, import): not restarted.</summary>
public const string Stopping = "stopping";
/// <summary>Guard to engine: stop in an orderly way (the container is stopping).</summary>
public const string Stop = "stop";
}
/// <summary>Stages of the engine as the guard sees them.</summary>
public static class GuardStages
{
/// <summary>The startup steps of SPEC 9.4: watched for 10 minutes without progress.</summary>
public const string Starting = "starting";
/// <summary>The main loop runs: watched for 2 minutes of silence.</summary>
public const string Running = "running";
/// <summary>Error page or first run: waiting for the user, never a reason to intervene.</summary>
public const string Waiting = "waiting";
}
/// <summary>One message of the channel.</summary>
public sealed record GuardMessage(string Type)
{
public string? Stage { get; init; }
public string? Step { get; init; }
public string? Reason { get; init; }
public IReadOnlyList<GuardKeys>? Keys { get; init; }
public static GuardMessage Beat(string stage, string? step) => new(GuardMessageTypes.Beat) { Stage = stage, Step = step };
// Never prints the keys.
public override string ToString() => $"GuardMessage({Type}, {Stage}, {Step})";
}
/// <summary>
/// The keys of one account, as the engine has them: Alpaca key and secret, OKX key, secret and passphrase, Telegram
/// token and chat. Held only in the guard's memory, never written (SPEC 9.3).
/// </summary>
public sealed record GuardKeys(string Service, string Environment, IReadOnlyList<string> Values)
{
public const string Telegram = "telegram";
public override string ToString() => $"GuardKeys({Service}, {Environment}, ***)";
}
/// <summary>Where the guard and the engine meet in the data folder.</summary>
public sealed record GuardPaths(string DataRoot)
{
public string Folder => Path.Combine(DataRoot, "guard");
/// <summary>Positions, stop levels and open orders, kept current by the engine for the guard.</summary>
public string StateFile => Path.Combine(Folder, "state.json");
/// <summary>The guard does not write in the database: it leaves notes here, which the engine puts in the diary.</summary>
public string NotesFolder => Path.Combine(Folder, "notes");
/// <summary>The "Ferma tutto" file (SPEC 9.3).</summary>
public string StopFile => Path.Combine(DataRoot, "STOP");
}
+130
View File
@@ -0,0 +1,130 @@
using Anubis.Core;
using Anubis.Trading;
namespace Anubis.Supervision;
/// <summary>What the guard did on one account.</summary>
public sealed record RepairOutcome(IReadOnlyList<string> Lines, IReadOnlyList<PlacedStop> Placed, bool Complete);
/// <summary>
/// The guard's work on a broker account while the engine is stopped (SPEC 9.3): reads positions and the outcome of the
/// orders in the state file, cancels the purchases and sales left open, and puts back only the stops that are
/// missing and were not executed, for the quantity still held. Protective sales and stops are never touched.
/// </summary>
public static class GuardRepair
{
/// <summary>
/// The guard's stops take sequences this far above the engine's next one: if a note were lost, the engine's next
/// stops would still not reuse their ids.
/// </summary>
public const int SequenceGap = 500;
public static async Task<RepairOutcome> RunAsync(GuardState state, GuardAccount account, IBrokerAccount broker, IClock clock, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(broker);
ArgumentNullException.ThrowIfNull(clock);
var lines = new List<string>();
var placed = new List<PlacedStop>();
var complete = true;
// 1. Purchases and sales still waiting: the open ones the broker shows, and those the state lists.
var open = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false))
.Where(o => ClientOrderIds.IsOurs(o.ClientOrderId, state.Installation)).ToList();
var waiting = open.Where(o => ClientOrderIds.Parse(o.ClientOrderId)?.Purpose is OrderPurpose.Entry or OrderPurpose.Exit)
.Select(o => (o.ClientOrderId, o.Symbol, o.Side)).ToList();
foreach (var listed in account.Orders.Where(o => o.Purpose is OrderPurpose.Entry or OrderPurpose.Exit && waiting.All(w => w.ClientOrderId != o.ClientOrderId)))
{
if (await broker.GetOrderAsync(listed.ClientOrderId, listed.Symbol, cancellationToken).ConfigureAwait(false) is { IsOpen: true } remote)
{
waiting.Add((remote.ClientOrderId, remote.Symbol, remote.Side));
}
}
foreach (var (clientId, symbol, side) in waiting)
{
await broker.CancelOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false);
lines.Add($"Ho annullato {(side == OrderSide.Buy ? "l'acquisto" : "la vendita")} di {Shown(symbol)} rimast{(side == OrderSide.Buy ? "o" : "a")} in attesa.");
}
// 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 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)
.ToList();
foreach (var bySymbol in account.Positions.Where(p => p.StopLevel is not null).GroupBy(p => p.Symbol, StringComparer.Ordinal))
{
var available = positions.Where(p => p.Symbol == bySymbol.Key).Sum(p => p.Quantity);
foreach (var position in bySymbol.OrderBy(p => p.Strategy, StringComparer.Ordinal))
{
var code = ClientOrderIds.StrategyCodes.GetValueOrDefault(position.Strategy);
var moved = fills.Where(f => f.Symbol == position.Symbol && ClientOrderIds.Parse(f.ClientOrderId)?.Strategy == position.Strategy)
.Sum(f => f.Side == OrderSide.Buy ? f.Quantity : -f.Quantity);
var held = Math.Min(Math.Max(0m, position.Quantity + moved), available);
available -= held;
var covered = stops.Where(o => o.Symbol == position.Symbol && code is not null && ClientOrderIds.Parse(o.ClientOrderId)?.Strategy == position.Strategy)
.Sum(o => o.Remaining);
var missing = OrderRules.RoundDown(held - covered, position.Lot);
if (missing <= 0m || code is null)
{
continue;
}
var sequence = Math.Min(position.NextStopSequence + SequenceGap, ClientOrderIds.MaxSequence - 2);
foreach (var (quantity, timeInForce) in Shapes(position, missing, account.FractionalStopsAreDayOnly))
{
var clientId = ClientOrderIds.Build(state.Installation, account.Environment, position.Strategy, OrderPurpose.Stop, position.StopKey, sequence++);
var request = new OrderRequest(clientId, position.Symbol, OrderSide.Sell, OrderKind.Stop, quantity, timeInForce) { StopPrice = position.StopLevel };
try
{
var remote = await broker.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false);
placed.Add(new PlacedStop(account.AccountId, position.InstrumentId, position.Symbol, position.Strategy, clientId, remote.BrokerOrderId, quantity,
position.StopLevel!.Value, timeInForce));
lines.Add($"Ho rimesso lo stop di {Shown(position.Symbol)} a {Format.Price(position.StopLevel.Value)} per {Format.Quantity(quantity)}.");
}
catch (OrderRejectedException ex)
{
complete = false;
lines.Add($"{account.Name} ha rifiutato lo stop di {Shown(position.Symbol)} ({ex.Code}): la posizione resta senza stop finché il motore non riparte.");
}
}
}
}
if (lines.Count == 0)
{
lines.Add($"Su {account.Name} non c'era nulla da annullare e ogni posizione aveva il suo stop.");
}
return new RepairOutcome(lines, placed, complete);
}
/// <summary>The stops a quantity needs on the venue, as the engine places them (SPEC 7.2): fractions of shares only as day orders.</summary>
public static IReadOnlyList<(decimal Quantity, TimeInForce TimeInForce)> Shapes(GuardPosition position, decimal quantity, bool fractionalDayOnly)
{
ArgumentNullException.ThrowIfNull(position);
if (!fractionalDayOnly || position.IsCrypto)
{
return [(quantity, TimeInForce.Gtc)];
}
var (whole, fraction) = OrderRules.SplitWhole(quantity);
var shapes = new List<(decimal, TimeInForce)>();
if (whole > 0m)
{
shapes.Add((whole, TimeInForce.Gtc));
}
if (fraction > 0m)
{
shapes.Add((fraction, TimeInForce.Day));
}
return shapes;
}
private static string Shown(string symbol) => DiaryText.Shown(symbol);
}
+116
View File
@@ -0,0 +1,116 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Trading;
namespace Anubis.Supervision;
/// <summary>
/// What the guard needs to protect the positions while the engine is stopped (SPEC 9.3): written by the engine every
/// few seconds, read by the guard only after it stopped the engine.
/// </summary>
public sealed record GuardState(DateTimeOffset WrittenAt, string Installation, IReadOnlyList<GuardAccount> Accounts);
public sealed record GuardAccount(Guid AccountId, string Name, string Broker, string Environment, bool FractionalStopsAreDayOnly,
IReadOnlyList<GuardPosition> Positions, IReadOnlyList<GuardOrder> Orders);
/// <summary>
/// A position of a strategy: quantity, stop level already on the tick, lot, and what the guard needs to name a stop
/// the engine will recognize as its own (the key of the position's stops and the next free sequence).
/// </summary>
public sealed record GuardPosition(Guid InstrumentId, string Symbol, string Strategy, decimal Quantity, decimal? StopLevel, decimal Lot, bool IsCrypto,
string StopKey, int NextStopSequence);
/// <summary>An order the engine believes open.</summary>
public sealed record GuardOrder(string ClientOrderId, Guid InstrumentId, string Symbol, string Strategy, OrderSide Side, OrderPurpose Purpose, decimal Quantity,
decimal? StopPrice);
/// <summary>A stop the guard placed while the engine was stopped: the engine adopts it at the restart.</summary>
public sealed record PlacedStop(Guid AccountId, Guid InstrumentId, string Symbol, string Strategy, string ClientOrderId, string? BrokerOrderId, decimal Quantity,
decimal StopPrice, TimeInForce TimeInForce);
/// <summary>
/// The note of one intervention: when, why, what the guard did, in the words of the diary. The engine writes it in the
/// diary at the restart and adopts the stops it lists.
/// </summary>
public sealed record GuardNote(DateTimeOffset At, string Reason, IReadOnlyList<string> Lines, IReadOnlyList<PlacedStop> Placed)
{
/// <summary>The engine was silent for the 2 minutes of SPEC 9.3.</summary>
public const string Silence = "silence";
/// <summary>The startup steps did not move for 10 minutes.</summary>
public const string Stalled = "stalled";
/// <summary>The engine ended without announcing it.</summary>
public const string Crash = "crash";
/// <summary>The intervention made the bot restart in "Ferma tutto" (third forced restart within an hour).</summary>
public bool StopFileCreated { get; init; }
}
/// <summary>Reading and writing the guard's files: each write goes to a temporary file first, so a reader never sees half of it.</summary>
public static class GuardFiles
{
public static void WriteState(GuardPaths paths, GuardState state)
{
ArgumentNullException.ThrowIfNull(paths);
Write(paths.StateFile, JsonSerializer.Serialize(state, GuardChannel.Json));
}
/// <summary>The last state the engine wrote; null when there is none or it cannot be read.</summary>
public static GuardState? ReadState(GuardPaths paths)
{
ArgumentNullException.ThrowIfNull(paths);
return Read<GuardState>(paths.StateFile);
}
public static string WriteNote(GuardPaths paths, GuardNote note)
{
ArgumentNullException.ThrowIfNull(paths);
ArgumentNullException.ThrowIfNull(note);
var path = Path.Combine(paths.NotesFolder, note.At.UtcDateTime.ToString("yyyyMMdd'T'HHmmssfff'Z'", CultureInfo.InvariantCulture) + ".json");
Write(path, JsonSerializer.Serialize(note, GuardChannel.Json));
return path;
}
/// <summary>The notes not yet taken by the engine, oldest first, with their files.</summary>
public static IReadOnlyList<(string Path, GuardNote Note)> ReadNotes(GuardPaths paths)
{
ArgumentNullException.ThrowIfNull(paths);
if (!Directory.Exists(paths.NotesFolder))
{
return [];
}
var notes = new List<(string, GuardNote)>();
foreach (var file in Directory.GetFiles(paths.NotesFolder, "*.json").Order(StringComparer.Ordinal))
{
if (Read<GuardNote>(file) is { } note)
{
notes.Add((file, note));
}
}
return notes;
}
private static T? Read<T>(string path)
where T : class
{
try
{
return File.Exists(path) ? JsonSerializer.Deserialize<T>(File.ReadAllText(path), GuardChannel.Json) : null;
}
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
{
return null;
}
}
private static void Write(string path, string text)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var temporary = path + ".tmp";
File.WriteAllText(temporary, text);
File.Move(temporary, path, overwrite: true);
}
}
+524
View File
@@ -0,0 +1,524 @@
using Anubis.Core;
using Anubis.Trading;
using Microsoft.Extensions.Logging;
namespace Anubis.Supervision;
/// <summary>The times of the guard (SPEC 9.3). The drill shortens them; the bot uses these.</summary>
public sealed record GuardOptions
{
/// <summary>Silence of the main loop, after a successful start, that makes the guard intervene.</summary>
public TimeSpan Silence { get; init; } = TimeSpan.FromMinutes(2);
/// <summary>Startup steps that do not move for this long make the guard intervene.</summary>
public TimeSpan StalledStart { get; init; } = TimeSpan.FromMinutes(10);
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(1);
/// <summary>A round of the guard this late means its own clock jumped (the computer slept): the silence counts from now.</summary>
public TimeSpan ClockJump { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>How long an orderly stop may take before the engine is ended (the container waits 60 seconds).</summary>
public TimeSpan GracefulStop { get; init; } = TimeSpan.FromSeconds(55);
public TimeSpan ForcedWindow { get; init; } = TimeSpan.FromHours(1);
/// <summary>The forced restart, within <see cref="ForcedWindow"/>, that restarts the engine in "Ferma tutto".</summary>
public int ForcedLimit { get; init; } = 3;
public TimeSpan DownAlertEvery { get; init; } = TimeSpan.FromHours(1);
/// <summary>Pauses before restarting an engine that keeps closing by itself: the first restart is immediate.</summary>
public IReadOnlyList<TimeSpan> CrashPauses { get; init; } =
[TimeSpan.Zero, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15)];
}
/// <summary>How to start the engine: with the drill's fault or without, and where its messages go.</summary>
public sealed record EngineStart(bool Fault, Action<GuardMessage> OnMessage);
/// <summary>The engine as a child process of the guard.</summary>
public interface IEngineProcess : IDisposable
{
/// <summary>Completes with the exit code when the process ends.</summary>
Task<int> Exited { get; }
/// <summary>Asks for an orderly stop through the channel.</summary>
Task RequestStopAsync(CancellationToken cancellationToken);
/// <summary>Ends the process at once, with everything it started.</summary>
void Kill();
}
/// <summary>
/// The guard (SPEC 9.3): parent of the engine, it listens to its beat and intervenes when the main loop is silent for
/// 2 minutes after a successful start, or the startup steps of 9.4 do not move for 10 minutes. Then, in this order:
/// ends the engine, reads positions and orders from the brokers, cancels the purchases and sales left open, puts back
/// the missing stops, leaves a note, warns, restarts the engine. Orderly stops are not reactions: they are passed on
/// and waited for, and the engine is not restarted. At the third forced restart within an hour the engine restarts in
/// "Ferma tutto". The guard never writes in the database.
/// </summary>
public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOptions options, Func<EngineStart, IEngineProcess> start,
Func<GuardAccount, IReadOnlyList<GuardKeys>, IBrokerAccount?> brokers, Func<string, IReadOnlyList<GuardKeys>, CancellationToken, Task> alert, ILogger logger)
{
private readonly Lock _gate = new();
private readonly List<DateTimeOffset> _forced = [];
private IEngineProcess? _engine;
private string _stage = GuardStages.Starting;
private string? _step;
private DateTimeOffset _lastBeat;
private DateTimeOffset _stepSince;
private bool _announced;
/// <summary>Which engine is the current one: a late message from an engine already replaced is ignored.</summary>
private int _generation;
private IReadOnlyList<GuardKeys> _keys = [];
private DateTimeOffset _lastRound;
private DateTimeOffset? _downSince;
private DateTimeOffset? _nextDownAlert;
private DateTimeOffset? _restartAt;
private int _crashes;
/// <summary>The stage the engine last declared.</summary>
public string Stage
{
get
{
lock (_gate)
{
return _stage;
}
}
}
public int Interventions { get; private set; }
/// <summary>The engine has a process now (not waiting for the pause after a crash).</summary>
public bool EngineAlive => _engine is { Exited.IsCompleted: false };
/// <summary>The notes written so far, for the drill and the tests.</summary>
public IReadOnlyList<GuardNote> Notes => [.. _notes];
private readonly List<GuardNote> _notes = [];
/// <summary>Starts the engine; <paramref name="fault"/> only for the drill.</summary>
public void Start(bool fault = false) => StartEngine(fault);
/// <summary>A message from the current engine.</summary>
public void Receive(GuardMessage message)
{
int current;
lock (_gate)
{
current = _generation;
}
Receive(current, message);
}
/// <summary>
/// A message from engine number <paramref name="generation"/>. The pipe of a stopped engine can still deliver what it
/// had sent: a "running" beat would make the new engine look ready, a "stopping" would make its crash look planned.
/// </summary>
private void Receive(int generation, GuardMessage message)
{
ArgumentNullException.ThrowIfNull(message);
var now = clock.UtcNow;
lock (_gate)
{
if (generation != _generation)
{
return;
}
switch (message.Type)
{
case GuardMessageTypes.Beat:
var stage = message.Stage ?? _stage;
if (stage != _stage || message.Step != _step)
{
_stepSince = now;
}
_stage = stage;
_step = message.Step;
_lastBeat = now;
if (stage is GuardStages.Running or GuardStages.Waiting)
{
// The engine is back: no more "it does not restart" alerts.
_downSince = null;
_nextDownAlert = null;
_crashes = 0;
}
break;
case GuardMessageTypes.Keys:
_keys = message.Keys ?? [];
foreach (var value in _keys.SelectMany(k => k.Values))
{
Redactor.Register(value);
}
break;
case GuardMessageTypes.Stopping:
_announced = true;
LogAnnounced(logger, message.Reason ?? "-");
break;
}
}
}
/// <summary>Watches until the engine stops on purpose, or until <paramref name="shutdown"/> asks the guard to stop it.</summary>
public async Task<int> RunAsync(CancellationToken shutdown)
{
if (_engine is null && _restartAt is null)
{
StartEngine(fault: false);
}
while (true)
{
var exited = _engine?.Exited ?? Task.FromResult(0);
try
{
await Task.WhenAny(Task.Delay(options.Poll, shutdown), _engine is null ? Task.Delay(Timeout.Infinite, shutdown) : exited).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
if (shutdown.IsCancellationRequested)
{
return await StopAsync().ConfigureAwait(false);
}
if (await RoundAsync(shutdown).ConfigureAwait(false) is { } code)
{
return code;
}
}
}
/// <summary>One round of watching; the exit code when the engine stopped on purpose and the guard's work is over.</summary>
public async Task<int?> RoundAsync(CancellationToken cancellationToken)
{
var now = clock.UtcNow;
if (_lastRound != default && now - _lastRound > options.ClockJump)
{
// The guard's own clock jumped too (the computer slept): the engine's silence starts now, not then.
lock (_gate)
{
_lastBeat = now;
_stepSince = now;
}
}
_lastRound = now;
if (_engine is null)
{
if (_restartAt is { } at && now >= at)
{
_restartAt = null;
StartEngine(fault: false);
}
await DownAlertAsync(now, cancellationToken).ConfigureAwait(false);
return null;
}
if (_engine.Exited.IsCompleted)
{
var code = await _engine.Exited.ConfigureAwait(false);
bool announced;
lock (_gate)
{
announced = _announced;
}
if (announced)
{
LogEnded(logger, code);
return code;
}
await InterveneAsync(GuardNote.Crash, cancellationToken).ConfigureAwait(false);
return null;
}
string stage;
string? step;
DateTimeOffset beat;
DateTimeOffset since;
lock (_gate)
{
(stage, step, beat, since) = (_stage, _step, _lastBeat, _stepSince);
}
if (stage == GuardStages.Running && now - beat > options.Silence)
{
await InterveneAsync(GuardNote.Silence, cancellationToken).ConfigureAwait(false);
}
else if (stage == GuardStages.Starting && now - since > options.StalledStart)
{
await InterveneAsync(GuardNote.Stalled, cancellationToken, step).ConfigureAwait(false);
}
await DownAlertAsync(now, cancellationToken).ConfigureAwait(false);
return null;
}
/// <summary>
/// The container is stopping: the engine gets "stop" and up to <see cref="GuardOptions.GracefulStop"/> to close in
/// order, then it is ended. It is not restarted.
/// </summary>
public async Task<int> StopAsync()
{
lock (_gate)
{
_announced = true;
}
var engine = _engine;
if (engine is null)
{
return 0;
}
try
{
using var asking = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await engine.RequestStopAsync(asking.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException or InvalidOperationException)
{
// The channel is gone: the wait below ends the engine anyway.
}
if (await Task.WhenAny(engine.Exited, Task.Delay(options.GracefulStop)).ConfigureAwait(false) != engine.Exited)
{
LogKilledAtStop(logger);
engine.Kill();
}
return await engine.Exited.ConfigureAwait(false);
}
private void StartEngine(bool fault)
{
_engine?.Dispose();
var now = clock.UtcNow;
int generation;
lock (_gate)
{
generation = ++_generation;
_stage = GuardStages.Starting;
_step = null;
_lastBeat = now;
_stepSince = now;
_announced = false;
}
_lastRound = now;
_engine = start(new EngineStart(fault, message => Receive(generation, message)));
LogStarted(logger, fault);
}
private async Task InterveneAsync(string reason, CancellationToken cancellationToken, string? step = null)
{
var engine = _engine!;
var now = clock.UtcNow;
Interventions++;
LogIntervention(logger, reason);
// 1. The engine stops first: the guard touches orders only while it is stopped.
engine.Kill();
try
{
await engine.Exited.WaitAsync(TimeSpan.FromSeconds(30), CancellationToken.None).ConfigureAwait(false);
}
catch (TimeoutException)
{
LogStillAlive(logger);
}
engine.Dispose();
_engine = null;
// 2-4. Each broker account: orders left waiting canceled, missing stops put back.
var lines = new List<string> { Opening(reason, step) };
var placed = new List<PlacedStop>();
IReadOnlyList<GuardKeys> keys;
lock (_gate)
{
keys = _keys;
}
var state = GuardFiles.ReadState(paths);
if (state is null)
{
lines.Add("Non ho trovato il file di stato del motore: posizioni e stop li rimette in ordine il motore alla ripartenza.");
}
else
{
foreach (var account in state.Accounts.Where(a => a.Positions.Count > 0 || a.Orders.Count > 0))
{
lines.AddRange(await RepairAsync(state, account, keys, placed, cancellationToken).ConfigureAwait(false));
}
}
// The third forced restart within an hour: the engine restarts in "Ferma tutto" (SPEC 9.3).
_forced.RemoveAll(t => now - t >= options.ForcedWindow);
_forced.Add(now);
var stopAll = _forced.Count >= options.ForcedLimit;
if (stopAll)
{
WriteStopFile(now);
lines.Add("È il terzo riavvio forzato in un'ora: il motore riparte in \"Ferma tutto\". Per ripartire togli il file STOP e conferma dall'interfaccia.");
}
// 5. The note for the diary, then the warning.
var note = new GuardNote(now, reason, lines, placed) { StopFileCreated = stopAll };
try
{
GuardFiles.WriteNote(paths, note);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
LogNoteFailed(logger, ex);
}
_notes.Add(note);
await AlertAsync(string.Join(Environment.NewLine, lines), cancellationToken).ConfigureAwait(false);
// 6. The restart, never with the drill's fault. An engine that keeps closing by itself waits a little longer each time.
_downSince ??= now;
_nextDownAlert ??= now + options.DownAlertEvery;
var pause = TimeSpan.Zero;
if (reason == GuardNote.Crash)
{
_crashes++;
pause = options.CrashPauses[Math.Min(_crashes, options.CrashPauses.Count) - 1];
}
if (pause <= TimeSpan.Zero)
{
StartEngine(fault: false);
}
else
{
_restartAt = now + pause;
}
}
private async Task<List<string>> RepairAsync(GuardState state, GuardAccount account, IReadOnlyList<GuardKeys> keys, List<PlacedStop> placed, CancellationToken cancellationToken)
{
if (account.Environment == TradingEnvironments.Simulation)
{
return [$"{account.Name} è il simulatore interno: posizioni e stop li rimette in ordine il motore alla ripartenza."];
}
IBrokerAccount? broker;
try
{
broker = brokers(account, keys);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return [$"{account.Name}: non riesco a collegarmi al conto ({Redactor.Redact(ex.Message)}): ci pensa il motore alla ripartenza."];
}
if (broker is null)
{
return [$"{account.Name}: non ho le chiavi del conto, quindi non posso intervenire: ci pensa il motore alla ripartenza."];
}
try
{
var outcome = await GuardRepair.RunAsync(state, account, broker, clock, cancellationToken).ConfigureAwait(false);
placed.AddRange(outcome.Placed);
return [.. outcome.Lines];
}
catch (BrokerException ex)
{
return [$"{account.Name}: non raggiungo il conto ({Redactor.Redact(ex.Message)}): ci pensa il motore alla ripartenza."];
}
finally
{
(broker as IDisposable)?.Dispose();
}
}
private async Task DownAlertAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
if (_downSince is not { } since || _nextDownAlert is not { } next || now < next)
{
return;
}
_nextDownAlert = next + options.DownAlertEvery;
await AlertAsync($"Il motore non riparte da {DiaryText.Duration(now - since)}. Le posizioni hanno gli stop che ho rimesso io; " +
"quelli giornalieri sulle frazioni di azione scadono a fine seduta e senza il motore nessuno li rimette domani.", cancellationToken).ConfigureAwait(false);
}
private async Task AlertAsync(string text, CancellationToken cancellationToken)
{
IReadOnlyList<GuardKeys> keys;
lock (_gate)
{
keys = _keys;
}
try
{
await alert(text, keys, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogAlertFailed(logger, ex);
}
}
private void WriteStopFile(DateTimeOffset now)
{
try
{
Directory.CreateDirectory(paths.DataRoot);
File.WriteAllText(paths.StopFile, $"Creato dalla guardia il {now:yyyy-MM-dd HH:mm} UTC: terzo riavvio forzato in un'ora.{Environment.NewLine}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
LogNoteFailed(logger, ex);
}
}
private string Opening(string reason, string? step) => reason switch
{
GuardNote.Silence => $"La guardia è intervenuta: il motore non dava segni di vita da {DiaryText.Duration(options.Silence)}. L'ho fermato, ho controllato i conti e l'ho riavviato.",
GuardNote.Stalled => $"La guardia è intervenuta: l'avvio del motore era fermo da {DiaryText.Duration(options.StalledStart)}" +
(step is null ? "" : $" al passo \"{step}\"") + ". L'ho fermato, ho controllato i conti e l'ho riavviato.",
_ => "La guardia è intervenuta: il motore si è chiuso senza avvisare. Ho controllato i conti e l'ho riavviato.",
};
[LoggerMessage(Level = LogLevel.Information, Message = "Engine started (drill fault: {Fault})")]
private static partial void LogStarted(ILogger logger, bool fault);
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard intervention: {Reason}")]
private static partial void LogIntervention(ILogger logger, string reason);
[LoggerMessage(Level = LogLevel.Information, Message = "Engine announced its stop: {Reason}")]
private static partial void LogAnnounced(ILogger logger, string reason);
[LoggerMessage(Level = LogLevel.Information, Message = "Engine ended with code {Code}")]
private static partial void LogEnded(ILogger logger, int code);
[LoggerMessage(Level = LogLevel.Warning, Message = "Engine did not stop in time: ended")]
private static partial void LogKilledAtStop(ILogger logger);
[LoggerMessage(Level = LogLevel.Error, Message = "Engine still alive after being ended")]
private static partial void LogStillAlive(ILogger logger);
[LoggerMessage(Level = LogLevel.Error, Message = "Guard note or STOP file not written")]
private static partial void LogNoteFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "Guard alert not sent")]
private static partial void LogAlertFailed(ILogger logger, Exception exception);
}
+227
View File
@@ -0,0 +1,227 @@
using System.Globalization;
using System.Text;
using Anubis.Core;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Supervision;
/// <summary>One check of the endurance run: what was looked at and whether it is in order.</summary>
public sealed record SoakCheck(string Text, bool Ok);
/// <summary>
/// The report of an endurance run in real time (SPEC 17, phase 6): over a window of the bot's own records, whether it
/// kept working without losing control. It reads only what the bot wrote; it changes nothing.
/// </summary>
public sealed record SoakReport(DateTimeOffset From, DateTimeOffset To, IReadOnlyList<SoakCheck> Checks, IReadOnlyList<string> Facts)
{
public bool Passed => Checks.All(c => c.Ok);
public string Markdown(TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(zone);
var text = new StringBuilder();
text.AppendLine("# Prova di durata")
.AppendLine()
.AppendLine(CultureInfo.InvariantCulture, $"Dal {Moment(From, zone)} al {Moment(To, zone)} ({Hours(To - From)}).")
.AppendLine()
.AppendLine(Passed ? "**Esito: regolare.**" : "**Esito: da guardare.** Le righe segnate con ✗ dicono cosa.")
.AppendLine()
.AppendLine("## Controlli")
.AppendLine();
foreach (var check in Checks)
{
text.AppendLine(CultureInfo.InvariantCulture, $"- {(check.Ok ? "✓" : "✗")} {check.Text}");
}
text.AppendLine().AppendLine("## Che cosa è successo").AppendLine();
foreach (var fact in Facts)
{
text.AppendLine("- " + fact);
}
return text.ToString();
}
internal static string Moment(DateTimeOffset moment, TimeZoneInfo zone) =>
TimeZoneInfo.ConvertTime(moment, zone).ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
internal static string Hours(TimeSpan span) =>
Format.Number((decimal)Math.Round(span.TotalHours, 1), span.TotalHours % 1 == 0 ? 0 : 1) + " ore";
}
/// <summary>Builds the <see cref="SoakReport"/> from the database.</summary>
public static class SoakReporter
{
/// <summary>
/// The reconciliation and the other frequent jobs run every 5 minutes: a job last finished longer ago than this, or an
/// account last reconciled longer ago, means the bot stopped working.
/// </summary>
public static readonly TimeSpan MaxSilence = TimeSpan.FromMinutes(15);
public static async Task<SoakReport> BuildAsync(Database db, DateTimeOffset from, DateTimeOffset to, TimeSpan minimum, TimeZoneInfo zone,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(zone);
if (to <= from)
{
throw new ArgumentException("La fine della prova deve venire dopo l'inizio.", nameof(to));
}
return await db.ReadAsync(async s =>
{
var checks = new List<SoakCheck>();
var facts = new List<string>();
(string Name, object? Value)[] window = [("from", from), ("to", to)];
// Continuity. A clean reconciliation writes no row, so the bot's life is read elsewhere: its scheduled jobs
// say when it first ran and when it last finished something; every stop of 5 minutes or more is written as an
// absence at the restart (SPEC 5.6); a loop stuck while the process lives is a guard intervention (below).
var jobs = await s.FirstOrDefaultAsync("SELECT MIN(created_at) AS first, MAX(last_finished_at) AS last FROM jobs",
r => (First: r.IsNull("first") ? (DateTimeOffset?)null : r.Moment("first"), Last: r.IsNull("last") ? (DateTimeOffset?)null : r.Moment("last")))
.ConfigureAwait(false);
var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at",
r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false);
// A gap shorter than the longest silence allowed at either end (the first jobs come a minute after the start,
// the last one up to 5 minutes before the end) is no more a hole than one in the middle.
var start = jobs.First is { } first && first > from + MaxSilence ? first : from;
var end = jobs.Last is { } lastJob && lastJob < to - MaxSilence ? lastJob : to;
var covered = jobs.First is null || jobs.Last is null || end <= start ? TimeSpan.Zero
: end - start - absences.Aggregate(TimeSpan.Zero, (sum, a) => sum + (Min(a.End, end) - Max(a.Start, start) is { } span && span > TimeSpan.Zero ? span : TimeSpan.Zero));
checks.Add(new SoakCheck($"Durata coperta dal lavoro del bot: {SoakReport.Hours(covered)} (servono almeno {SoakReport.Hours(minimum)}).", covered >= minimum));
var startedInTime = jobs.First is { } began && began <= from + MaxSilence;
var workingAtEnd = jobs.Last is { } finished && finished >= to - MaxSilence;
checks.Add(new SoakCheck((jobs.First, jobs.Last) switch
{
(null, _) or (_, null) => "Nessun lavoro in programma è mai finito.",
_ when !startedInTime => $"Il bot ha cominciato a lavorare solo il {SoakReport.Moment(jobs.First!.Value, zone)}.",
_ when !workingAtEnd => $"L'ultimo lavoro in programma è finito il {SoakReport.Moment(jobs.Last!.Value, zone)}: da allora il bot tace.",
_ => "Al lavoro dall'inizio alla fine della finestra.",
}, startedInTime && workingAtEnd));
// No order twice: one order per client id, one execution per order key, one decision per run key.
var doubled = await s.CountAsync("SELECT COUNT(*) FROM (SELECT client_order_id FROM orders GROUP BY client_order_id HAVING COUNT(*) > 1) d").ConfigureAwait(false)
+ await s.CountAsync("SELECT COUNT(*) FROM (SELECT order_key FROM executions GROUP BY order_key HAVING COUNT(*) > 1) d").ConfigureAwait(false)
+ await s.CountAsync("SELECT COUNT(*) FROM (SELECT run_key FROM engine_runs GROUP BY run_key HAVING COUNT(*) > 1) d").ConfigureAwait(false);
checks.Add(new SoakCheck(doubled == 0 ? "Nessun ordine né decisione doppia." : $"Ordini o decisioni doppie: {doubled}.", doubled == 0));
// Reconciliations: never an unexplained difference, and every account ends in agreement.
var outcomes = await s.QueryAsync(
"SELECT a.name AS account, r.outcome AS outcome, COUNT(*) AS n FROM reconciliations r JOIN accounts a ON a.id = r.account_id " +
"WHERE r.occurred_at >= @from AND r.occurred_at <= @to GROUP BY a.name, r.outcome ORDER BY a.name, r.outcome",
r => (Account: r.Text("account"), Outcome: r.Text("outcome"), Count: r.Number("n")), window).ConfigureAwait(false);
var different = outcomes.Where(o => o.Outcome == ReconcileOutcomes.Different).Sum(o => o.Count);
checks.Add(new SoakCheck(different == 0 ? "Nessuna differenza inspiegata tra registro e conti." : $"Riconciliazioni con differenze inspiegate: {different}.", different == 0));
var accounts = await s.QueryAsync(
"SELECT a.name AS account, st.mode AS mode, st.last_reconciled_at AS at FROM account_status st JOIN accounts a ON a.id = st.account_id ORDER BY a.name",
r => (Account: r.Text("account"), Mode: r.Text("mode"), At: r.IsNull("at") ? (DateTimeOffset?)null : r.Moment("at"))).ConfigureAwait(false);
var behind = accounts.Where(a => a.At is not { } at || at < to - MaxSilence || a.Mode != AccountModes.Normal).ToList();
checks.Add(new SoakCheck(accounts.Count == 0
? "Nessun conto riconciliato."
: behind.Count == 0
? "Ogni conto riconciliato fino alla fine e in regola: " + string.Join(", ", accounts.Select(a => a.Account)) + "."
: "Conti non riconciliati fino alla fine o non in regola: " + string.Join(", ", behind.Select(a =>
a.Mode != AccountModes.Normal ? $"{a.Account} in modalità {(a.Mode == AccountModes.Prudent ? "prudente" : a.Mode)}" : $"{a.Account} (ultima riconciliazione {(a.At is { } at ? SoakReport.Moment(at, zone) : "mai")})")) + ".",
accounts.Count > 0 && behind.Count == 0));
foreach (var group in outcomes.GroupBy(o => o.Account, StringComparer.Ordinal))
{
facts.Add($"Riconciliazioni di {group.Key}: " + string.Join(", ", group.Select(o => $"{o.Count} {Outcome(o.Outcome)}")) + ".");
}
// The bot was never away and the guard never had to step in.
checks.Add(new SoakCheck(absences.Count == 0
? "Il bot non si è mai spento."
: "Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Minutes(a.End - a.Start)}")) + ".", absences.Count == 0));
var interventions = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention' AND occurred_at >= @from AND occurred_at <= @to", window)
.ConfigureAwait(false);
checks.Add(new SoakCheck(interventions == 0 ? "La guardia non è mai dovuta intervenire." : $"Interventi della guardia: {interventions}.", interventions == 0));
// A crypto decision at every daily close in the window (00:05 UTC), whatever the stage of the strategy.
var closes = DailyCloses(from, to);
var runs = await s.QueryAsync("SELECT strategy, mode, COUNT(*) AS n FROM engine_runs WHERE created_at >= @from AND created_at <= @to GROUP BY strategy, mode ORDER BY strategy, mode",
r => (Strategy: r.Text("strategy"), Mode: r.Text("mode"), Count: r.Number("n")), window).ConfigureAwait(false);
var crypto = runs.Where(r => r.Strategy == StrategyNames.CryptoTrend).Sum(r => r.Count);
checks.Add(new SoakCheck($"Decisioni di {StrategyNames.CryptoTrend}: {crypto} su {closes} chiusure giornaliere.", crypto >= closes));
facts.Add(runs.Count == 0
? "Nessuna decisione del motore."
: "Decisioni del motore: " + string.Join(", ", runs.Select(r => $"{r.Strategy} {r.Count} ({Mode(r.Mode)})")) + ".");
// What the bot did and wrote, for the record.
facts.Add(Counted("Ordini", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window)
.ConfigureAwait(false)));
facts.Add(Counted("Esecuzioni", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM executions WHERE created_at >= @from AND created_at <= @to GROUP BY status", window)
.ConfigureAwait(false)));
facts.Add(Counted("Ordini pianificati", await GroupAsync(s,
"SELECT status AS k, COUNT(*) AS n FROM planned_orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false)));
facts.Add(Counted("Righe del diario", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM journal WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window)
.ConfigureAwait(false)));
facts.Add(Counted("Messaggi Telegram", await GroupAsync(s,
"SELECT status AS k, COUNT(*) AS n FROM notifications WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false)));
facts.Add(Counted("Eventi di rischio", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM risk_events WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window)
.ConfigureAwait(false)));
facts.Add(Counted("Problemi nei dati", await GroupAsync(s,
"SELECT kind || ' ' || status AS k, COUNT(*) AS n FROM data_issues WHERE created_at >= @from AND created_at <= @to GROUP BY kind, status", window).ConfigureAwait(false)));
var failing = await s.QueryAsync("SELECT name, last_error FROM jobs WHERE last_error IS NOT NULL AND last_finished_at >= @from ORDER BY name",
r => r.Text("name") + " (" + Redactor.Redact(r.Text("last_error")) + ")", ("from", from)).ConfigureAwait(false);
facts.Add(failing.Count == 0 ? "Nessun lavoro in programma è finito con un errore all'ultima esecuzione." : "Lavori con un errore all'ultima esecuzione: " + string.Join("; ", failing) + ".");
return new SoakReport(from, to, checks, facts);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>The time a daily decision is given to run and be written before the report expects it.</summary>
public static readonly TimeSpan DecisionTime = TimeSpan.FromMinutes(30);
/// <summary>
/// How many crypto daily decisions (00:05 UTC) fall in the window. A close too near the end of the window is not
/// counted: its decision may still be running when the report is made.
/// </summary>
public static int DailyCloses(DateTimeOffset from, DateTimeOffset to)
{
to -= DecisionTime;
var count = 0;
for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1))
{
var close = new DateTimeOffset(day.ToDateTime(new TimeOnly(0, 5)), TimeSpan.Zero);
if (close > to)
{
return count;
}
if (close >= from)
{
count++;
}
}
}
private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a < b ? a : b;
private static DateTimeOffset Max(DateTimeOffset a, DateTimeOffset b) => a > b ? a : b;
private static Task<List<(string Key, long Count)>> GroupAsync(DbSession s, string sql, (string Name, object? Value)[] window) =>
s.QueryAsync(sql, r => (Key: r.TextOrNull("k") ?? "?", Count: r.Number("n")), window);
private static string Counted(string what, List<(string Key, long Count)> groups) =>
groups.Count == 0 ? what + ": nessuno." : $"{what}: {groups.Sum(g => g.Count)} (" + string.Join(", ", groups.Select(g => $"{g.Key} {g.Count}")) + ").";
private static string Minutes(TimeSpan span) =>
span.TotalMinutes < 120 ? Format.Number((decimal)Math.Round(span.TotalMinutes)) + " minuti" : SoakReport.Hours(span);
private static string Outcome(string outcome) => outcome switch
{
ReconcileOutcomes.Clean => "in regola",
ReconcileOutcomes.Healed => "sistemate da sole",
ReconcileOutcomes.Different => "con differenze",
ReconcileOutcomes.Unreachable => "conto non raggiungibile",
_ => outcome,
};
private static string Mode(string mode) => mode switch
{
DecisionModes.Observation => "in osservazione",
DecisionModes.ExitsOnly => "solo uscite",
DecisionModes.Full => "complete",
_ => mode,
};
}
+92
View File
@@ -0,0 +1,92 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Trading;
/// <summary>A time the bot was off: from its last sign of life to the restart (SPEC 5.6).</summary>
public sealed record Absence(Guid Id, DateTimeOffset StartedAt, DateTimeOffset EndedAt, DateTimeOffset? AcknowledgedAt)
{
public TimeSpan Length => EndedAt - StartedAt;
}
/// <summary>
/// The absences of the bot (SPEC 5.6): measured at the restart from the last job that ran, written in the diary, and
/// declared at the top of the Panoramica when longer than a day, until the user has seen it.
/// </summary>
public sealed class AbsenceBook(Database db, IClock clock)
{
/// <summary>Shorter than this is a restart, not an absence: the minute pulse runs every minute.</summary>
public static readonly TimeSpan Threshold = TimeSpan.FromMinutes(5);
/// <summary>An absence longer than this is declared on the Panoramica.</summary>
public static readonly TimeSpan Declared = TimeSpan.FromHours(24);
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
/// <summary>
/// At the start, before the scheduler: the time since the last job finished. An absence is recorded and written in
/// the diary; null when the bot was not away (or never ran before).
/// </summary>
public async Task<Absence?> RecordAsync(CancellationToken cancellationToken)
{
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
var last = await s.FirstOrDefaultAsync("SELECT MAX(last_finished_at) AS last FROM jobs", r => r.IsNull("last") ? (DateTimeOffset?)null : r.Moment("last"))
.ConfigureAwait(false);
if (last is not { } since || now - since < Threshold)
{
return null;
}
var absence = new Absence(Ids.NewId(clock), since, now, null);
await s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @now)", cancellationToken,
("id", absence.Id), ("s", since), ("e", now), ("now", now)).ConfigureAwait(false);
await Diary.WriteAsync(s, clock, DiaryKinds.System, "absence", DiaryText.Absence(absence.Length), new { started = since, ended = now }, cancellationToken)
.ConfigureAwait(false);
return absence;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>The absence the Panoramica declares: the last one longer than a day the user has not acknowledged.</summary>
public async Task<Absence?> DeclaredAsync(CancellationToken cancellationToken)
{
var rows = await db.ReadAsync(s => s.QueryAsync(
"SELECT id, started_at, ended_at, acknowledged_at FROM absences WHERE acknowledged_at IS NULL ORDER BY ended_at DESC",
r => new Absence(r.Id("id"), r.Moment("started_at"), r.Moment("ended_at"), r.MomentOrNull("acknowledged_at"))), cancellationToken).ConfigureAwait(false);
return rows.FirstOrDefault(a => a.Length > Declared);
}
/// <summary>The user has seen the notice: every absence up to this one stops being declared.</summary>
public Task AcknowledgeAsync(Guid id, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
var ended = await s.FirstOrDefaultAsync("SELECT ended_at FROM absences WHERE id = @id", r => (DateTimeOffset?)r.Moment("ended_at"), ("id", id)).ConfigureAwait(false);
if (ended is { } until)
{
await s.ExecuteAsync("UPDATE absences SET acknowledged_at = @now WHERE acknowledged_at IS NULL AND ended_at <= @e", cancellationToken, ("now", clock.UtcNow), ("e", until))
.ConfigureAwait(false);
}
}, cancellationToken);
/// <summary>The diary line of a run missed while the bot was off: made at the restart, or skipped with its reason.</summary>
public static string? MissedLine(JobRun run, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(run);
if (!run.Missed)
{
return null;
}
var what = Lower(run.Description ?? run.Name);
return run.Outcome switch
{
JobOutcome.Completed => DiaryText.Recovered(what, run.DueUtc, zone),
JobOutcome.Skipped => DiaryText.Skipped($"{what} (previsto alle {TimeZoneInfo.ConvertTime(run.DueUtc, zone):HH:mm})", "Il riavvio è arrivato oltre l'orario utile."),
_ => null,
};
}
private static string Lower(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
}
+3
View File
@@ -11,6 +11,9 @@ public static class StrategyNames
public const string EquityMomentum = "equity_momentum";
public const string EquityMeanrev = "equity_meanrev";
/// <summary>The market filter of the stock strategies (SPEC 8.2): read, never traded unless it is in the universe.</summary>
public const string MarketSymbol = "SPY";
public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base =
[
(CryptoTrend, Venues.Okx, 1m),
+7 -3
View File
@@ -8,12 +8,17 @@ namespace Anubis.Trading;
public static class DiaryKinds
{
public const string Orders = "Ordini";
public const string Decisions = "Decisioni";
public const string System = "Sistema";
public const string News = "Notizie";
public const string Learning = "Apprendimento";
public static readonly IReadOnlyList<string> All = [Orders, Decisions, System, News, Learning];
}
/// <summary>
/// The bot's diary and its notices (SPEC 13.6): short sentences in Italian, in the first person. A notice is also
/// queued for Telegram; the sender arrives with Phase 6, the queue is kept from now.
/// queued for Telegram (SPEC 14), in the same transaction.
/// </summary>
public static class Diary
{
@@ -31,7 +36,6 @@ public static class Diary
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
await WriteAsync(s, clock, DiaryKinds.System, code, message, null, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO notifications (id, channel, kind, message, status, created_at) VALUES (@id, 'telegram', @k, @m, 'pending', @at)", cancellationToken,
("id", Ids.NewId(clock)), ("k", code), ("m", message), ("at", clock.UtcNow)).ConfigureAwait(false);
await Notifications.NotificationSender.EnqueueAsync(s, clock, code, message, cancellationToken).ConfigureAwait(false);
}
}
+245
View File
@@ -0,0 +1,245 @@
using Anubis.Core;
using Anubis.Data;
namespace Anubis.Trading;
/// <summary>
/// The fixed templates of the diary (SPEC 5.2, 13.3, appendix B): one main sentence and, when it helps, a second
/// one with the reason. Short form without a subject for what was done ("Alzato lo stop di BTC/EUR"), first person
/// for what the bot does or did ("Sono stato fermo"). Never free text written at decision time.
/// </summary>
public static class DiaryText
{
/// <summary>A symbol as the user reads it: <c>BTC/EUR</c> for the pair <c>BTC-EUR</c>, <c>AAPL</c> as it is.</summary>
public static string Shown(string symbol)
{
ArgumentNullException.ThrowIfNull(symbol);
return symbol.Replace('-', '/');
}
/// <summary>The coin of a pair: <c>BTC</c> for <c>BTC-EUR</c>.</summary>
public static string Coin(string symbol)
{
ArgumentNullException.ThrowIfNull(symbol);
var dash = symbol.IndexOf('-', StringComparison.Ordinal);
return dash > 0 ? symbol[..dash] : symbol;
}
/// <summary>"BTC, ETH e SOL".</summary>
public static string List(IEnumerable<string> items)
{
ArgumentNullException.ThrowIfNull(items);
var list = items.ToList();
return list.Count switch
{
0 => "",
1 => list[0],
_ => string.Join(", ", list.Take(list.Count - 1)) + " e " + list[^1],
};
}
/// <summary>A stop or a price level in a sentence: no decimals from 1,000 up (65.400 €), the price's own below.</summary>
public static string Level(decimal value, string currency) =>
Math.Abs(value) >= 1000m ? Format.Money(value, currency, decimals: 0) : Format.Number(value, Math.Abs(value) >= 1m ? 2 : 4) + " " + Format.CurrencySymbol(currency);
/// <summary>
/// A fill: "Comprate 2 AAPL a 259,80 $." and, for a sale that closes the trade, its result: "Venduta 1 MSFT a
/// 522,14 $: +9,84 $ in 3 giorni." <paramref name="reason"/> is the second sentence, from a reason code.
/// </summary>
public static string Fill(OrderSide side, decimal quantity, string symbol, bool crypto, decimal price, string currency, string? reason = null, ClosedTrade? closed = null)
{
var buy = side == OrderSide.Buy;
var one = quantity == 1m;
var verb = (buy, crypto, one) switch
{
(true, true, true) => "Comprato",
(true, true, false) => "Comprati",
(true, false, true) => "Comprata",
(true, false, false) => "Comprate",
(false, true, true) => "Venduto",
(false, true, false) => "Venduti",
(false, false, true) => "Venduta",
(false, false, false) => "Vendute",
};
var text = $"{verb} {Format.Quantity(quantity)} {Shown(symbol)} a {Format.Price(price)} {Format.CurrencySymbol(currency)}";
if (closed is not null)
{
text += $": {Format.Money(closed.Result, currency, withSign: true)} {Days(closed.Days)}";
}
return text + "." + (string.IsNullOrWhiteSpace(reason) ? "" : " " + reason.Trim());
}
/// <summary>"in 3 giorni", "in 1 giorno", "in giornata".</summary>
public static string Days(int days) => days switch
{
<= 0 => "in giornata",
1 => "in 1 giorno",
_ => $"in {days} giorni",
};
public static string StopRaised(string symbol, decimal from, decimal to, string currency) =>
$"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale.";
public static string StopLowered(string symbol, decimal from, decimal to, string currency) =>
$"Spostato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}.";
public static string StopsReplaced(int count) => count == 1
? "Rimesso 1 stop giornaliero sulle frazioni di azione."
: $"Rimessi {count} stop giornalieri sulle frazioni di azione.";
/// <summary>
/// The daily crypto close (SPEC 5.5): what changes, what stays in trend, what stays out. "Chiusura giornaliera
/// crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato
/// nuovi massimi."
/// </summary>
public static string CryptoClose(DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var head = "Chiusura giornaliera crypto: " + Changes(summary, Coin) + ".";
var staying = summary.Held.Select(Coin).ToList();
if (staying.Count > 0)
{
head += staying.Count == 1 ? $" {staying[0]} resta in tendenza." : $" {List(staying)} restano in tendenza.";
}
if (summary.Outside > 0)
{
head += summary.Outside == 1
? " L'altra moneta resta fuori: non ha segnato nuovi massimi."
: $" {(staying.Count + summary.Bought.Count > 0 ? "Le altre" : "Le")} {summary.Outside} monete restano fuori: nessuna ha segnato nuovi massimi.";
}
return head;
}
/// <summary>
/// The stock signals after the close: "Azioni: nessun nuovo acquisto. AAPL resta aperta." or "Azioni: domani
/// compro AAPL e MSFT, vendo JPM."
/// </summary>
public static string StockSignals(DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var head = summary.HasChanges ? "Azioni: domani " + Changes(summary, s => s) + "." : "Azioni: nessun nuovo acquisto.";
if (summary.Held.Count > 0)
{
head += summary.Held.Count == 1 ? $" {summary.Held[0]} resta aperta." : $" {List(summary.Held)} restano aperte.";
}
return head;
}
/// <summary>A strategy in observation: the signal is recorded, no order leaves (SPEC 12.3).</summary>
public static string Observed(string strategy, DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var label = StrategyNames.Label(strategy, withMarket: true);
return summary.HasChanges
? $"{label}, in osservazione: avrei {Conditional(summary)}. Nessun ordine: registro solo il segnale."
: $"{label}, in osservazione: nessun cambio. Registro solo il segnale.";
}
/// <summary>A strategy whose decision could not be made: the data was missing, nothing was bought.</summary>
public static string NoData(string strategy, string what) =>
$"{StrategyNames.Label(strategy, withMarket: true)}: nessuna decisione oggi. Mancano {what}: non apro nuove posizioni.";
/// <summary>A missed job done at the restart (SPEC 5.6).</summary>
public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) =>
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
/// <summary>A missed job left out at the restart, with its reason (SPEC 5.6).</summary>
public static string Skipped(string what, string reason) => $"Saltato: {what}. {reason}";
/// <summary>A purchase or sale left open at a start (SPEC 9.4): canceled, and proposed again.</summary>
public static string RestartedOrder(bool sale, string symbol) => sale
? $"Alla ripartenza ho annullato la vendita di {Shown(symbol)} rimasta aperta: la vendita già decisa riparte subito con un ordine nuovo."
: $"Alla ripartenza ho annullato l'acquisto di {Shown(symbol)} rimasto aperto: lo ripropongo con le regole del recupero.";
/// <summary>An entry left out because the price moved too far from the planned one (SPEC 5.6).</summary>
public static string EntryDropped(string symbol, decimal movedPercent, decimal limitPercent) =>
$"Scartato l'acquisto di {Shown(symbol)}: il prezzo si è mosso del {Format.Percent(movedPercent, 1)} dall'orario previsto, oltre il limite del {Format.Percent(limitPercent, 0)}.";
/// <summary>The restart after an absence (SPEC 5.6, 9.4).</summary>
public static string Absence(TimeSpan absence) => $"Sono stato fermo per {Duration(absence)}. Ho ripreso i lavori saltati con le regole del recupero.";
/// <summary>"3 ore e 5 minuti", "2 giorni e 4 ore", "12 minuti".</summary>
public static string Duration(TimeSpan span)
{
static string Unit(int n, string one, string many) => n == 1 ? $"1 {one}" : $"{n} {many}";
if (span.TotalDays >= 1)
{
var days = (int)span.TotalDays;
return span.Hours > 0 ? $"{Unit(days, "giorno", "giorni")} e {Unit(span.Hours, "ora", "ore")}" : Unit(days, "giorno", "giorni");
}
if (span.TotalHours >= 1)
{
var hours = (int)span.TotalHours;
return span.Minutes > 0 ? $"{Unit(hours, "ora", "ore")} e {Unit(span.Minutes, "minuto", "minuti")}" : Unit(hours, "ora", "ore");
}
return Unit(Math.Max(1, (int)Math.Round(span.TotalMinutes)), "minuto", "minuti");
}
private static string Changes(DecisionSummary s, Func<string, string> name)
{
var parts = new List<string>();
if (s.Bought.Count > 0)
{
parts.Add("compro " + List(s.Bought.Select(name)));
}
if (s.Increased.Count > 0)
{
parts.Add("aumento " + List(s.Increased.Select(name)));
}
if (s.Reduced.Count > 0)
{
parts.Add("riduco " + List(s.Reduced.Select(name)));
}
if (s.Sold.Count > 0)
{
parts.Add("vendo " + List(s.Sold.Select(name)));
}
return parts.Count == 0 ? "nessun cambio" : string.Join(", ", parts);
}
private static string Conditional(DecisionSummary s)
{
var parts = new List<string>();
if (s.Bought.Count > 0)
{
parts.Add("comprato " + List(s.Bought.Select(Shown)));
}
if (s.Increased.Count > 0)
{
parts.Add("aumentato " + List(s.Increased.Select(Shown)));
}
if (s.Reduced.Count > 0)
{
parts.Add("ridotto " + List(s.Reduced.Select(Shown)));
}
if (s.Sold.Count > 0)
{
parts.Add("venduto " + List(s.Sold.Select(Shown)));
}
return string.Join(", ", parts);
}
}
/// <summary>The result of a trade a sale has just closed: for the diary line of the fill.</summary>
public sealed record ClosedTrade(decimal Result, int Days);
/// <summary>What one decision changes, by symbol: the material of the diary's decision lines.</summary>
public sealed record DecisionSummary(IReadOnlyList<string> Bought, IReadOnlyList<string> Increased, IReadOnlyList<string> Reduced, IReadOnlyList<string> Sold,
IReadOnlyList<string> Held, int Outside)
{
public bool HasChanges => Bought.Count + Increased.Count + Reduced.Count + Sold.Count > 0;
}
+36 -8
View File
@@ -55,7 +55,10 @@ public static class Returns
public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore fx)
{
private sealed record Shot(string Scope, string World, Guid? AccountId, string? Strategy, string Currency, decimal Equity, decimal Cash, decimal Invested, decimal Flows,
decimal? FxEffect);
decimal? FxEffect)
{
public decimal? Benchmark { get; init; }
}
public async Task<int> TakeAsync(CancellationToken cancellationToken)
{
@@ -84,10 +87,13 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
}
var rate = await UsdRateAsync(DateOnly.FromDateTime(now.UtcDateTime), cancellationToken).ConfigureAwait(false);
var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL",
r => (Account: r.Id("account_id"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken)
var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL",
r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken)
.ConfigureAwait(false);
foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World))
Func<DateOnly, (decimal Bitcoin, decimal Stock)?>? prices = null;
var pricesLoaded = false;
var today = DateOnly.FromDateTime(now.UtcDateTime);
foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World).ToList())
{
var usd = world.Where(s => s.Currency == "USD").ToList();
if (usd.Count > 0 && rate is null)
@@ -102,11 +108,33 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
usdFlows.Add((row.Amount, await UsdRateAsync(DateOnly.FromDateTime(row.At.UtcDateTime), cancellationToken).ConfigureAwait(false) ?? rate!.Value));
}
// The "senza bot" comparison gets the same flows, each on its day and in euro at that day's rate (SPEC 7.5).
var included = shots.Where(s => s.Scope == "strategy" && s.World == world.Key && !twins.Contains((s.Strategy!, s.AccountId!.Value)))
.Select(s => (s.AccountId!.Value, s.Strategy!)).ToHashSet();
var dated = new List<(DateOnly Day, decimal AmountEur)>();
foreach (var row in flowRows.Where(f => LedgerKinds.IsFlow(f.Kind) && included.Contains((f.Account, f.Strategy))))
{
var day = DateOnly.FromDateTime(row.At.UtcDateTime);
var amount = row.Currency == "USD"
? row.Amount / (await UsdRateAsync(day, cancellationToken).ConfigureAwait(false) ?? rate!.Value)
: row.Amount;
dated.Add((day, amount));
}
if (!pricesLoaded && dated.Count > 0)
{
pricesLoaded = true;
prices = await NoBot.PricesAsync(db, clock, dated.Min(d => d.Day), today, cancellationToken).ConfigureAwait(false);
}
var benchmark = prices is null ? null : NoBot.Value(dated, prices, today);
decimal ToEur(Shot s, decimal value) => s.Currency == "USD" ? value / rate!.Value : value;
var eurFlows = world.Where(s => s.Currency != "USD").Sum(s => s.Flows) + usdFlows.Sum(f => f.AmountUsd / f.Rate);
shots.Add(new Shot("total", world.Key, null, null, "EUR",
DbValues.Money(world.Sum(s => ToEur(s, s.Equity))), DbValues.Money(world.Sum(s => ToEur(s, s.Cash))), DbValues.Money(world.Sum(s => ToEur(s, s.Invested))),
DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null));
DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null)
{ Benchmark = benchmark });
}
await db.WriteAsync(async s =>
@@ -119,10 +147,10 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
var peak = Math.Max(previous?.Peak ?? index, index);
var drawdown = peak <= 0m ? 0m : Math.Round((index / peak - 1m) * 100m, 4, MidpointRounding.AwayFromZero);
await s.ExecuteAsync(
"INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect) " +
"VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx)", cancellationToken,
"INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect, benchmark) " +
"VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx, @b)", cancellationToken,
("id", Ids.NewId(clock)), ("now", now), ("sc", shot.Scope), ("a", shot.AccountId), ("st", shot.Strategy), ("e", shot.Equity), ("c", shot.Cash), ("i", shot.Invested),
("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect)).ConfigureAwait(false);
("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect), ("b", shot.Benchmark)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
return shots.Count;
File diff suppressed because it is too large. Load diff
+113
View File
@@ -0,0 +1,113 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Trading;
/// <summary>
/// The "senza bot" comparison (SPEC 7.5): the same capital, with the same flows, put 40% in Bitcoin (BTC/EUR) and
/// 60% in the S&amp;P 500 (SPY adjusted for dividends and splits, in euro at the ECB rate) and never touched. Every
/// deposit buys the two in that proportion on its day; a withdrawal sells both in the proportion they have reached.
/// Prices are the daily closes of the days before: a deposit on Tuesday buys at Monday's close, and the value on
/// Wednesday uses Tuesday's. A close is final only when its day is over, so the comparison moves once a day.
/// </summary>
public static class NoBot
{
public const decimal BitcoinShare = 0.40m;
public const decimal StockShare = 0.60m;
public const string BitcoinSymbol = "BTC-EUR";
public const string StockSymbol = "SPY";
/// <summary>
/// The value in euro on <paramref name="today"/> of the untouched portfolio. Null when there are no flows or a
/// price is missing on a day that needs it: a comparison with a hole would not be honest.
/// </summary>
public static decimal? Value(IEnumerable<(DateOnly Day, decimal AmountEur)> flows, Func<DateOnly, (decimal Bitcoin, decimal Stock)?> prices, DateOnly today)
{
ArgumentNullException.ThrowIfNull(flows);
ArgumentNullException.ThrowIfNull(prices);
decimal bitcoin = 0m, stock = 0m;
var any = false;
foreach (var (day, amount) in flows.Where(f => f.AmountEur != 0m).OrderBy(f => f.Day))
{
if (prices(day) is not { Bitcoin: > 0m, Stock: > 0m } p)
{
return null;
}
any = true;
if (amount > 0m)
{
bitcoin += BitcoinShare * amount / p.Bitcoin;
stock += StockShare * amount / p.Stock;
continue;
}
var value = bitcoin * p.Bitcoin + stock * p.Stock;
var keep = value <= 0m ? 0m : Math.Max(0m, 1m + amount / value);
bitcoin *= keep;
stock *= keep;
}
return any && prices(today) is { Bitcoin: > 0m, Stock: > 0m } now ? DbValues.Money(bitcoin * now.Bitcoin + stock * now.Stock) : null;
}
/// <summary>
/// The daily closes the comparison needs, from the database: BTC-EUR on OKX, SPY on Alpaca with its corporate
/// actions, the ECB rate. Null when one of the series is missing (no Alpaca keys means no SPY history).
/// </summary>
public static async Task<Func<DateOnly, (decimal Bitcoin, decimal Stock)?>?> PricesAsync(Database db, IClock clock, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var catalog = new InstrumentCatalog(db, clock);
var bars = new BarStore(db, clock);
var btc = await catalog.FindAsync(Venues.Okx, BitcoinSymbol, cancellationToken).ConfigureAwait(false);
var spy = await catalog.FindAsync(Venues.Alpaca, StockSymbol, cancellationToken).ConfigureAwait(false);
if (btc is null || spy is null)
{
return null;
}
// A week before the first flow: a deposit on a Monday uses Friday's close.
var start = from.AddDays(-10);
var bitcoin = (await bars.DailyAsync(btc.Id, start, to, cancellationToken).ConfigureAwait(false)).Select(b => (b.Day, Close: (decimal)b.Close)).ToList();
var rawStock = await bars.DailyAsync(spy.Id, start, to, cancellationToken).ConfigureAwait(false);
var actions = await new CorporateActionStore(db, clock).ForSymbolAsync(StockSymbol, cancellationToken).ConfigureAwait(false);
var stock = rawStock.Count == 0 ? [] : Adjustments.Anchored(rawStock, actions, rawStock[^1].Day).Select(b => (b.Day, Close: (decimal)(b.Adjusted?.Close ?? b.Close))).ToList();
var rates = await db.ReadAsync(s => s.QueryAsync("SELECT rate_date, rate FROM fx_rates WHERE base = 'EUR' AND quote = 'USD' AND rate_date >= @f AND rate_date <= @t ORDER BY rate_date",
r => (Day: BarStore.ParseDay(r.Text("rate_date")), Rate: r.Money("rate")), ("f", BarStore.DayText(start.AddDays(-10))), ("t", BarStore.DayText(to))), cancellationToken).ConfigureAwait(false);
if (bitcoin.Count == 0 || stock.Count == 0 || rates.Count == 0)
{
return null;
}
var rateSeries = rates.Select(x => (x.Day, x.Rate)).ToList();
return day =>
{
var known = day.AddDays(-1);
var b = OnOrBefore(bitcoin, known);
var s = OnOrBefore(stock, known);
var r = OnOrBefore(rateSeries, known);
return b is null || s is null || r is not > 0m ? null : (b.Value, s.Value / r.Value);
};
}
private static decimal? OnOrBefore(List<(DateOnly Day, decimal Value)> series, DateOnly day)
{
decimal? found = null;
foreach (var (d, v) in series)
{
if (d > day)
{
break;
}
found = v;
}
return found;
}
}
+84
View File
@@ -0,0 +1,84 @@
using Anubis.Core;
using Anubis.Supervision;
namespace Anubis.Trading;
/// <summary>What the order manager gives to the guard and takes back from it (SPEC 9.3).</summary>
public sealed partial class OrderManager
{
/// <summary>
/// Called right after a sale leaves, before the turn ends. Only the guard drill sets it, to block the main loop
/// with a sale halfway (ADR 0012).
/// </summary>
public Func<CancellationToken, Task>? AfterSale { get; init; }
/// <summary>
/// The account as the guard needs it: every position with its stop level on the tick and the names its stops
/// take, and the orders believed open.
/// </summary>
public async Task<GuardAccount> GuardAccountAsync(CancellationToken cancellationToken)
{
var positions = new List<GuardPosition>();
foreach (var position in await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false))
{
if (position.Quantity <= 0m || await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument)
{
continue;
}
var level = position.StopPrice is { } stop ? OrderRules.StopPrice(stop, OrderRules.TickOf(instrument.Spec, stop)) : (decimal?)null;
var key = ClientOrderIds.Key(StopKey(position.InstrumentId, position.Strategy));
var next = await NextStopSequenceAsync(position.InstrumentId, position.Strategy, key, cancellationToken).ConfigureAwait(false);
positions.Add(new GuardPosition(position.InstrumentId, instrument.Symbol, position.Strategy, position.Quantity, level, OrderRules.LotOf(instrument.Spec),
instrument.IsCrypto, key, next));
}
var orders = new List<GuardOrder>();
var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('created', 'submitted', 'partially_filled')", ReadOrder,
("a", _account.AccountId)), cancellationToken).ConfigureAwait(false);
foreach (var row in open)
{
var symbol = (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "";
orders.Add(new GuardOrder(row.ClientOrderId, row.InstrumentId, symbol, row.Strategy, row.Side, row.Purpose, row.Quantity, row.Stop));
}
return new GuardAccount(_account.AccountId, _account.Name, _account.Broker, _account.Environment, _broker.Capabilities.FractionalStopsAreDayOnly, positions, orders);
}
/// <summary>
/// A stop the guard placed while the engine was stopped becomes one of the engine's stops: recorded, then read
/// again from the broker (it may have triggered meanwhile). False when it was already known.
/// </summary>
public async Task<bool> AdoptStopAsync(PlacedStop placed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(placed);
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await OrderByClientIdAsync(placed.ClientOrderId, cancellationToken).ConfigureAwait(false) is not null)
{
return false;
}
var row = new OrderRow(Ids.NewId(_clock), null, placed.InstrumentId, placed.Strategy, placed.ClientOrderId, OrderSide.Sell, OrderKind.Stop, OrderPurpose.Stop,
placed.Quantity, null, placed.StopPrice, OrderStatus.Created, 0m, null, placed.StopPrice, null, placed.TimeInForce, false, _clock.UtcNow);
await _db.WriteAsync(async s =>
{
await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @now, reason = 'placed by the guard' WHERE id = @id", cancellationToken,
("b", placed.BrokerOrderId), ("now", _clock.UtcNow), ("id", row.Id)).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (await _broker.GetOrderAsync(placed.ClientOrderId, placed.Symbol, cancellationToken).ConfigureAwait(false) is { } remote)
{
await ApplyRemoteAsync(row, remote, "placed by the guard", cancellationToken).ConfigureAwait(false);
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
}
return true;
}
finally
{
_gate.Release();
}
}
}
+32 -9
View File
@@ -375,14 +375,15 @@ public sealed partial class OrderManager : IDisposable
/// <summary>
/// Cancels the executions under way, except protective sales (SPEC 9.3, "Ferma tutto"): the open order of each is
/// canceled with the broker, and the stops it had removed come back at once for the quantity held.
/// canceled with the broker, and the stops it had removed come back at once for the quantity held. The answer is
/// the executions canceled.
/// </summary>
public async Task<int> CancelWorkingAsync(string reason, Func<string, bool>? strategy = null, CancellationToken cancellationToken = default)
public async Task<IReadOnlyList<Guid>> CancelWorkingAsync(string reason, Func<string, bool>? strategy = null, CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var count = 0;
var canceled = new List<Guid>();
foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false))
{
if (exec.Purpose == OrderPurpose.Protective || (strategy is not null && !strategy(exec.Strategy)))
@@ -400,10 +401,10 @@ public sealed partial class OrderManager : IDisposable
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false);
count++;
canceled.Add(exec.Id);
}
return count;
return canceled;
}
finally
{
@@ -626,6 +627,10 @@ public sealed partial class OrderManager : IDisposable
}
}, cancellationToken).ConfigureAwait(false);
await SendAsync(exec, row, instrument, cancellationToken).ConfigureAwait(false);
if (exec.Side == OrderSide.Sell && exec.Purpose == OrderPurpose.Exit && AfterSale is { } afterSale)
{
await afterSale(cancellationToken).ConfigureAwait(false);
}
}
private async Task SendAsync(ExecRow exec, OrderRow row, Instrument instrument, CancellationToken cancellationToken)
@@ -766,10 +771,28 @@ public sealed partial class OrderManager : IDisposable
recorded++;
var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill",
string.Create(CultureInfo.InvariantCulture,
$"{(fill.Side == OrderSide.Buy ? "Comprati" : "Venduti")} {Format.Quantity(fill.Quantity)} {instrument?.Symbol} a {Format.Price(fill.Price)} su {_account.Name}."),
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp }, cancellationToken), cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(async s =>
{
// A sale that closes the trade says its result (appendix F.10: "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni").
ClosedTrade? closed = null;
if (outcome.TradeClosed && outcome.TradeId is { } tradeId)
{
var trade = await s.FirstOrDefaultAsync("SELECT realized, opened_at, closed_at FROM trades WHERE id = @id",
r => (Realized: r.Money("realized"), Opened: r.Moment("opened_at"), Closed: r.MomentOrNull("closed_at")), ("id", tradeId)).ConfigureAwait(false);
if (trade.Closed is { } closedAt)
{
closed = new ClosedTrade(trade.Realized, (DateOnly.FromDateTime(closedAt.UtcDateTime).DayNumber - DateOnly.FromDateTime(trade.Opened.UtcDateTime).DayNumber));
}
}
var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null;
var text = DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed);
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(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 (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).
+93
View File
@@ -0,0 +1,93 @@
namespace Anubis.Trading;
/// <summary>
/// The fixed sentences of the reason codes of the decisions table (SPEC 5.2): the "why" card of a trade and the
/// diary use these, never free text written at decision time. An unknown code is shown as it is, so nothing is ever
/// hidden.
/// </summary>
public static class ReasonCatalog
{
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
["unknown_symbol"] = "Strumento sconosciuto.",
// Orders.
["zero_quantity"] = "Quantità troppo piccola: nessun ordine.",
["below_min_size"] = "Sotto la quantità minima del broker: nessun ordine.",
["below_min_notional"] = "Sotto l'importo minimo del broker: nessun ordine.",
["no_price"] = "Nessun prezzo recente: nessun ordine.",
["instrument_not_live"] = "Lo strumento non si può negoziare in questo momento.",
["account_prudent"] = "Conto in modalità prudente: niente nuovi ingressi.",
["not_ours"] = "L'ordine non è del bot: non lo tocca.",
["no_cash"] = "Liquidità insufficiente per l'acquisto.",
["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.",
["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["dividend"] = "Dividendo accreditato.",
// Live engine.
["late_exits_only"] = "Decisione in ritardo: solo uscite e stop, gli ingressi aspettano la prossima chiusura.",
["entry_expired"] = "Ingresso scaduto: oltre l'orario in cui era valido.",
["price_moved"] = "Il prezzo si è mosso troppo dall'orario previsto: ingresso scartato.",
["missing_bars"] = "Mancano le barre di chiusura: niente nuove posizioni.",
["superseded"] = "Sostituito da una decisione più recente.",
["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.",
["nothing_held"] = "Niente da vendere: la posizione era già chiusa.",
["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.",
["recovered"] = "Recuperato dopo un'assenza.",
};
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
public static bool Has(string code) => Texts.ContainsKey(code);
}
+291 -20
View File
@@ -4,6 +4,7 @@ using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Risk;
using Anubis.Supervision;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -183,8 +184,22 @@ public sealed partial class TradingService : IDisposable
Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false)));
Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile };
_settings = settings;
Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger)
{
WantData = market is null ? null : _ => market.WakeWorker(),
Ready = () => _started,
AccountReady = AccountReady,
};
}
private volatile bool _started;
/// <summary>The startup steps of SPEC 9.4 are done and the loop runs.</summary>
public bool IsStarted => _started;
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
public LiveEngine Engine { get; }
private readonly SettingsStore? _settings;
public StageBook Stages { get; }
@@ -206,6 +221,23 @@ public sealed partial class TradingService : IDisposable
public TimeSpan TickInterval { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>The channel to the guard (SPEC 9.3): startup steps and the beat of the loop. Null without a guard.</summary>
public GuardLink? Guard { get; init; }
/// <summary>Where the state file for the guard is written and its notes are read. Null without a guard.</summary>
public GuardPaths? GuardFiles { get; init; }
/// <summary>The guard drill's fault (ADR 0012): <see cref="GuardChannel.HangMidSale"/> or nothing.</summary>
public string? Fault { get; init; }
/// <summary>How often the loop writes the state file for the guard.</summary>
public TimeSpan GuardStateEvery { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>A broker clock further than this from the computer's is reported at the start (SPEC 9.4).</summary>
public TimeSpan ClockTolerance { get; init; } = TimeSpan.FromSeconds(5);
private DateTimeOffset _guardStateAt;
public IReadOnlyCollection<OrderManager> Managers => [.. _managers.Values];
public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId);
@@ -223,14 +255,21 @@ public sealed partial class TradingService : IDisposable
return accounts;
}
/// <summary>Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled.</summary>
/// <summary>
/// The startup of SPEC 9.4 after the migrations: brokers, clock, corporate actions, then for every account the
/// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again)
/// and every position checked for its stop. Each step is told to the guard.
/// </summary>
public async Task StartAsync(CancellationToken cancellationToken)
{
Guard?.Step("conti e strategie");
var accounts = await PrepareAsync(cancellationToken).ConfigureAwait(false);
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false);
Guard?.Step("connessione ai broker");
var hang = Fault == GuardChannel.HangMidSale;
foreach (var account in accounts)
{
var broker = Build(account, alpaca, okx);
@@ -249,28 +288,195 @@ public sealed partial class TradingService : IDisposable
Gate = Risk is null ? null : Risk.GateAsync,
LivePermit = Stages.LiveRefusalAsync,
PurchasePriceCheck = (limit, quote) => RiskRules.TechnicalRefusal(_clock.UtcNow, quote.At, quote.Mid, limit, null, _limits),
// The guard drill only: the main loop stops here for good, with a sale halfway.
AfterSale = hang ? _ => Task.Delay(Timeout.Infinite, CancellationToken.None) : null,
};
}
await GuardAsync("simulatore", () => FundSimulatorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values)
{
await GuardAsync("avvio " + manager.Account.Name, async () =>
{
if (manager.Broker is PaperBroker paper)
{
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
}
else
{
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
}
Guard?.Step("orologio");
await GuardAsync("orologio", () => CheckClocksAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
Guard?.Step("azioni societarie");
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
// SPEC 5.6: corporate actions come first, so the stops the reconciliation puts back already know about a split.
if (_market is not null)
{
await GuardAsync("azioni societarie", () => _market.RefreshCorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
}
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values)
{
await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false);
}
_accountsRetryAt = _clock.UtcNow + AccountRetry;
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false);
_started = true;
Guard?.Set(GuardStages.Running);
}
/// <summary>
/// What the guard needs if the engine stops answering (SPEC 9.3): positions, stop levels and open orders of every
/// account. Written to a temporary file first, so the guard never reads half of it.
/// </summary>
public async Task WriteGuardStateAsync(CancellationToken cancellationToken)
{
if (GuardFiles is null)
{
return;
}
var accounts = new List<GuardAccount>();
foreach (var manager in _managers.Values)
{
accounts.Add(await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false));
}
Supervision.GuardFiles.WriteState(GuardFiles, new GuardState(_clock.UtcNow, InstallationCode, accounts));
_guardStateAt = _clock.UtcNow;
}
/// <summary>The accounts whose startup of SPEC 9.4 is done: only these are ticked, decided on and sent orders.</summary>
public bool AccountReady(Guid accountId) => _ready.ContainsKey(accountId);
private readonly ConcurrentDictionary<Guid, bool> _ready = new();
/// <summary>An account whose startup failed (broker unreachable) is tried again this often.</summary>
public TimeSpan AccountRetry { get; init; } = TimeSpan.FromMinutes(1);
private DateTimeOffset _accountsRetryAt;
/// <summary>
/// The startup of one account (SPEC 9.4): the guard's stops adopted first, whatever else fails; then the key, the
/// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again)
/// and every position checked for its stop. Until all of it is done the account is not ready.
/// </summary>
private async Task StartAccountAsync(OrderManager manager, CancellationToken cancellationToken)
{
var name = manager.Account.Name;
await GuardAsync("stop della guardia " + name, () => AdoptGuardStopsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
var started = await TryAsync("avvio " + name, async () =>
{
if (manager.Broker is PaperBroker paper)
{
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
}
else
{
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
}
Guard?.Step("riconciliazione " + name);
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("ordini rimasti aperti " + name);
await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("stop " + name);
await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (started)
{
_ready[manager.Account.AccountId] = true;
}
}
/// <summary>
/// The stops the guard put back while the engine was stopped become the engine's own, before anything compares
/// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a
/// stop left unknown would be put back a second time.
/// </summary>
private async Task AdoptGuardStopsAsync(OrderManager manager, CancellationToken cancellationToken)
{
if (GuardFiles is null)
{
return;
}
foreach (var (path, note) in Supervision.GuardFiles.ReadNotes(GuardFiles))
{
foreach (var placed in note.Placed.Where(p => p.AccountId == manager.Account.AccountId))
{
await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false);
}
var adopted = true;
foreach (var placed in note.Placed)
{
adopted &= await _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM orders WHERE client_order_id = @c", ("c", placed.ClientOrderId))
.ConfigureAwait(false) > 0, cancellationToken).ConfigureAwait(false);
}
if (adopted)
{
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines),
new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false);
File.Delete(path);
}
}
}
/// <summary>The accounts whose startup failed are tried again, once a minute.</summary>
private async Task RetryAccountsAsync(CancellationToken cancellationToken)
{
if (_clock.UtcNow < _accountsRetryAt)
{
return;
}
_accountsRetryAt = _clock.UtcNow + AccountRetry;
foreach (var manager in _managers.Values.Where(m => !AccountReady(m.Account.AccountId)))
{
await LimitedAsync("nuovo avvio " + manager.Account.Name, RetryLimit, ct => StartAccountAsync(manager, ct), cancellationToken).ConfigureAwait(false);
BeatIfAlive();
}
}
// The keys reach the guard in memory only: it needs them to protect the positions while the engine is stopped.
private async Task SendGuardKeysAsync(AlpacaCredentials? alpaca, OkxCredentials? okx, CancellationToken cancellationToken)
{
if (Guard is null)
{
return;
}
var keys = new List<GuardKeys>();
if (alpaca is not null)
{
keys.Add(new GuardKeys(Venues.Alpaca, TradingEnvironments.Demo, [alpaca.KeyId, alpaca.Secret]));
}
if (okx is not null)
{
keys.Add(new GuardKeys(Venues.Okx, TradingEnvironments.Demo, [okx.Key, okx.Secret, okx.Passphrase]));
}
var token = await _secrets.RevealAsync("TELEGRAM_BOT_TOKEN", cancellationToken).ConfigureAwait(false);
var chat = await _secrets.RevealAsync("TELEGRAM_CHAT_ID", cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(token) && !string.IsNullOrWhiteSpace(chat))
{
keys.Add(new GuardKeys(GuardKeys.Telegram, "", [token, chat]));
}
Guard.SendKeys(keys);
}
// SPEC 9.4: the clock of each broker against the computer's. A large gap is said, not corrected: the computer's clock is the system's.
private async Task CheckClocksAsync(CancellationToken cancellationToken)
{
foreach (var manager in _managers.Values.Where(m => m.Broker is not PaperBroker))
{
var remote = await manager.Broker.ServerTimeAsync(cancellationToken).ConfigureAwait(false);
var gap = (remote - _clock.UtcNow).Duration();
if (gap > ClockTolerance)
{
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "clock_gap",
$"L'orologio di questo computer differisce di {Math.Round(gap.TotalSeconds)} secondi da quello di {manager.Account.Name}: controlla la sincronizzazione dell'ora.",
cancellationToken), cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>
@@ -295,8 +501,29 @@ public sealed partial class TradingService : IDisposable
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
.. Engine.Jobs(),
.. _market is null ? Array.Empty<ScheduledJob>() :
[
new ScheduledJob("fine-seduta", "Scadenza degli ordini giornalieri del simulatore azioni",
Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(1), _market.UsCalendar), ExpireDayOrdersAsync) { MaxLateness = TimeSpan.FromHours(12) },
],
];
/// <summary>
/// The day orders of the stock simulator end at the close, as on the broker: the daily stops on fractions go back
/// at the next open (SPEC 5.5, 7.2).
/// </summary>
public async Task ExpireDayOrdersAsync(CancellationToken cancellationToken)
{
foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca))
{
if (manager.Broker is PaperBroker paper)
{
await paper.ExpireDayOrdersAsync(cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file.</summary>
public async Task CheckRiskAsync(CancellationToken cancellationToken)
{
@@ -337,6 +564,12 @@ public sealed partial class TradingService : IDisposable
}
await TickAllAsync(cancellationToken).ConfigureAwait(false);
BeatIfAlive();
if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery)
{
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
}
await Task.Delay(TickInterval, cancellationToken).ConfigureAwait(false);
}
}
@@ -377,20 +610,52 @@ public sealed partial class TradingService : IDisposable
public async Task TickAllAsync(CancellationToken cancellationToken)
{
foreach (var manager in _managers.Values)
await RetryAccountsAsync(cancellationToken).ConfigureAwait(false);
// An account not started yet keeps what it left open untouched: its startup cancels or resumes it first.
foreach (var manager in _managers.Values.Where(m => AccountReady(m.Account.AccountId)))
{
await GuardAsync("ordini " + manager.Account.Name, async () =>
await LimitedAsync("ordini " + manager.Account.Name, TickLimit, async ct =>
{
if (manager.Broker is PaperBroker paper)
{
await paper.PumpAsync(cancellationToken).ConfigureAwait(false);
await paper.PumpAsync(ct).ConfigureAwait(false);
}
await manager.TickAsync(cancellationToken).ConfigureAwait(false);
await manager.TickAsync(ct).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
BeatIfAlive();
}
}
/// <summary>
/// The longest one account's turn of the loop may take. A broker that stops answering (timeouts, retries) must
/// not keep the loop from beating for the two minutes after which the guard steps in: the turn is cut, written in
/// the log, and tried again at the next round. A loop that is truly stuck still falls silent.
/// </summary>
public TimeSpan TickLimit { get; init; } = TimeSpan.FromSeconds(45);
/// <summary>The longest an account's startup may take when it is tried again from the loop.</summary>
public TimeSpan RetryLimit { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>Whether the other loops of the engine are alive (the scheduler): without them the beat is withheld.</summary>
public Func<bool>? OthersAlive { get; init; }
private void BeatIfAlive()
{
if (OthersAlive is null || OthersAlive())
{
Guard?.Beat();
}
}
private async Task LimitedAsync(string what, TimeSpan limit, Func<CancellationToken, Task> work, CancellationToken cancellationToken)
{
using var limited = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
limited.CancelAfter(limit);
await GuardAsync(what, () => work(limited.Token), cancellationToken).ConfigureAwait(false);
}
public async Task ReconcileAllAsync(CancellationToken cancellationToken)
{
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
@@ -643,11 +908,15 @@ public sealed partial class TradingService : IDisposable
}
}
private async Task GuardAsync(string what, Func<Task> work, CancellationToken cancellationToken)
private Task<bool> GuardAsync(string what, Func<Task> work, CancellationToken cancellationToken) => TryAsync(what, work, cancellationToken);
/// <summary>Runs a step; a failure is logged and the answer is false. Only the stop of the service passes through.</summary>
private async Task<bool> TryAsync(string what, Func<Task> work, CancellationToken cancellationToken)
{
try
{
await work().ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -656,6 +925,7 @@ public sealed partial class TradingService : IDisposable
catch (Exception ex)
{
LogWorkFailed(_logger, ex, what);
return false;
}
}
@@ -707,6 +977,7 @@ public sealed partial class TradingService : IDisposable
public void Dispose()
{
Engine.Dispose();
foreach (var manager in _managers.Values)
{
manager.Dispose();
+204
View File
@@ -0,0 +1,204 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// Recovery after an absence (issue #49, SPEC 5.6): the bot is switched off for 3 hours, 20 hours and 3 days with a
/// simulated clock, and the rows of 5.6 whose jobs exist in this phase are checked at the restart.
/// </summary>
[TestClass]
public sealed class AbsenceTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateOnly LiveFrom = new(2026, 9, 1);
// The bot is switched off the evening before the first live day, at 23:00 UTC.
private static readonly DateTimeOffset Off = new(2026, 8, 31, 23, 0, 0, TimeSpan.Zero);
/// <summary>
/// Off from 23:00 to 02:00 UTC: the crypto decision of 00:05 is made at the restart and its purchases go if the
/// price is within 2% of the one at 00:05; one that moved more is dropped. Both end in the diary with the reason.
/// The missed backup is taken once; the morning summary is not due yet; no notice on the Panoramica.
/// </summary>
[TestMethod]
public async Task ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar()
{
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false);
var jobs = await RestartAsync(live.Rig, Off.AddHours(3)).ConfigureAwait(false);
Assert.AreEqual("Sono stato fermo per 3 ore. Ho ripreso i lavori saltati con le regole del recupero.", await LastDiaryAsync(live.Rig, "absence").ConfigureAwait(false));
Assert.IsNull(await new AbsenceBook(live.Rig.Db, live.Rig.Clock).DeclaredAsync(_none).ConfigureAwait(false));
Assert.AreEqual(1, jobs.Backups);
Assert.AreEqual(0, jobs.Summaries);
Assert.AreEqual(0, jobs.Plain, "A job without recovery rules is not run for the time it missed.");
// The data step brings yesterday's bar; SOL has moved 3% from the price of 00:05, ETH has not.
await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false);
live.Quotes(LiveFrom, b => b.Open);
var sol = (decimal)live.Bar("SOL-EUR", LiveFrom).Open * 1.03m;
live.Rig.Quote("SOL-EUR", sol * 0.9999m, sol * 1.0001m, 1000m);
await live.MinutesAsync(10).ConfigureAwait(false);
var runs = await live.Rig.QueryAsync("SELECT run_key, mode FROM engine_runs", r => (r.Text("run_key"), r.Text("mode"))).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { ("crypto_trend:2026-08-31", DecisionModes.Full) }, runs.ToList());
var fills = await live.LiveFillsAsync().ConfigureAwait(false);
Assert.IsTrue(fills.Any(f => f.Symbol == "ETH-EUR" && f.Side == OrderSide.Buy), "The recovered purchase goes.");
Assert.IsFalse(fills.Any(f => f.Symbol == "SOL-EUR"), "The purchase whose price moved 3% is dropped.");
var diary = await DiaryAsync(live.Rig).ConfigureAwait(false);
Assert.Contains("Recuperato un lavoro saltato: la chiusura giornaliera crypto (previsto alle 02:05).", diary);
Assert.Contains("Recuperato un lavoro saltato: l'acquisto di ETH/EUR (previsto alle 02:05).", diary);
Assert.IsTrue(diary.Any(d => d.StartsWith("Scartato l'acquisto di SOL/EUR: il prezzo si è mosso del 3", StringComparison.Ordinal)), string.Join("\n", diary));
var planned = await live.Rig.QueryAsync("SELECT outcome FROM planned_orders WHERE status = @s", r => r.Text("outcome"), ("s", PlannedStates.Dropped)).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { LiveReasons.PriceMoved }, planned.ToList());
}
/// <summary>
/// Off for 20 hours, back at 19:00 UTC: the crypto decision is past 12:00 and only exits and stops are updated;
/// the meanrev purchase decided at the last close expired an hour after the open; the morning summary is
/// skipped (past 12:00 in Italy) and said so in the diary; the backup is taken once; no notice on the Panoramica.
/// </summary>
[TestMethod]
public async Task TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries()
{
await using (var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false))
{
var jobs = await RestartAsync(live.Rig, Off.AddHours(20)).ConfigureAwait(false);
Assert.AreEqual(1, jobs.Backups);
Assert.AreEqual(0, jobs.Summaries);
Assert.HasCount(1, jobs.Skipped);
Assert.AreEqual("Saltato: riepilogo del mattino (previsto alle 08:00). Il riavvio è arrivato oltre l'orario utile.",
AbsenceBook.MissedLine(jobs.Skipped[0], Zones.Rome));
Assert.IsNull(await new AbsenceBook(live.Rig.Db, live.Rig.Clock).DeclaredAsync(_none).ConfigureAwait(false));
// The engine pulses before the data step has brought yesterday's bar: the late decision waits for it and
// asks for it, instead of being written off as "no data" at the first pulse.
live.Quotes(LiveFrom, b => b.Close);
await live.MinutesAsync(3).ConfigureAwait(false);
Assert.IsEmpty(await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false), "A late decision waits for its bars.");
await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false);
await live.MinutesAsync(10).ConfigureAwait(false);
var runs = await live.Rig.QueryAsync("SELECT mode FROM engine_runs", r => r.Text("mode")).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { DecisionModes.ExitsOnly }, runs.ToList());
Assert.IsEmpty(await live.LiveFillsAsync().ConfigureAwait(false), "No purchase after 12:00 UTC: the next close decides.");
var decision = await LastDiaryAsync(live.Rig, "decision").ConfigureAwait(false);
Assert.Contains(ReasonCatalog.Text(LiveReasons.LateExitsOnly), decision!);
}
// The stock side: the bot goes off after the signals of the close and comes back the next day at 12:30 in New
// York, past the hour after the open in which a meanrev purchase is valid.
await using var stocks = await StockRig.CreateAsync(LiveFrom, LiveFrom.AddDays(41)).ConfigureAwait(false);
await stocks.SessionAsync(LiveFrom).ConfigureAwait(false);
var pending = await stocks.Rig.QueryAsync("SELECT id FROM planned_orders WHERE status = @s", r => r.Id("id"), ("s", PlannedStates.Pending)).ConfigureAwait(false);
Assert.HasCount(1, pending, "The close of the first day plans a purchase for the next open.");
stocks.Rig.Clock.Set(new DateTimeOffset(2026, 9, 2, 16, 30, 0, TimeSpan.Zero));
stocks.Quotes(LiveFrom.AddDays(1), b => b.Open);
await stocks.MinutesAsync(3).ConfigureAwait(false);
var expired = await stocks.Rig.QueryAsync("SELECT outcome FROM planned_orders WHERE status = @s", r => r.Text("outcome"), ("s", PlannedStates.Expired)).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { LiveReasons.EntryExpired }, expired.ToList());
Assert.IsEmpty(await stocks.LiveFillsAsync().ConfigureAwait(false));
Assert.IsTrue((await DiaryAsync(stocks.Rig).ConfigureAwait(false)).Any(d => d.StartsWith("Saltato: l'acquisto di BBB. Ingresso scaduto", StringComparison.Ordinal)));
}
/// <summary>
/// Off for 3 days: only the decision of the restart day is made (the missed ones are not replayed), the backup is
/// taken once and not three times, and the Panoramica declares the absence until the user has seen it.
/// </summary>
[TestMethod]
public async Task ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce()
{
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false);
var back = Off.AddDays(3);
var jobs = await RestartAsync(live.Rig, back).ConfigureAwait(false);
Assert.AreEqual(1, jobs.Backups, "Three nights missed, one backup at the restart.");
Assert.AreEqual("Sono stato fermo per 3 giorni. Ho ripreso i lavori saltati con le regole del recupero.", await LastDiaryAsync(live.Rig, "absence").ConfigureAwait(false));
var book = new AbsenceBook(live.Rig.Db, live.Rig.Clock);
var declared = await book.DeclaredAsync(_none).ConfigureAwait(false);
Assert.IsNotNull(declared);
Assert.AreEqual(TimeSpan.FromDays(3), declared.Length);
await book.AcknowledgeAsync(declared.Id, _none).ConfigureAwait(false);
Assert.IsNull(await book.DeclaredAsync(_none).ConfigureAwait(false));
for (var day = LiveFrom.AddDays(-1); day <= LiveFrom.AddDays(2); day = day.AddDays(1))
{
await live.StoreBarAsync(day).ConfigureAwait(false);
}
live.Quotes(LiveFrom.AddDays(2), b => b.Close);
await live.MinutesAsync(5).ConfigureAwait(false);
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { "crypto_trend:2026-09-02" }, runs.ToList());
}
private sealed class Counts
{
public int Backups { get; set; }
public int Summaries { get; set; }
public int Plain { get; set; }
public List<JobRun> Skipped { get; } = [];
}
/// <summary>
/// The restart: the last sign of life was at <see cref="Off"/>; the clock is now <paramref name="back"/>. The
/// absence is recorded, then the scheduler starts with three jobs that ran last at <see cref="Off"/>: the nightly
/// backup (made once whenever the restart comes), the morning summary (only until 12:00 in Italy) and a job without
/// recovery rules.
/// </summary>
private static async Task<Counts> RestartAsync(TradingRig rig, DateTimeOffset back)
{
await rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, created_at, updated_at) VALUES (@id, 'motore', 'Motore', @t, @t, @t, 'completed', @t, @t)",
_none, ("id", Ids.NewId(rig.Clock)), ("t", Off)), _none).ConfigureAwait(false);
rig.Clock.Set(back);
await new AbsenceBook(rig.Db, rig.Clock).RecordAsync(_none).ConfigureAwait(false);
var counts = new Counts();
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(rig.Clock, bus);
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Zones.Rome), _ =>
{
counts.Backups++;
return Task.CompletedTask;
})
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) }, Off);
scheduler.Add(new ScheduledJob("riepilogo", "Riepilogo del mattino", Schedule.Daily(new TimeOnly(8, 0), Zones.Rome), _ =>
{
counts.Summaries++;
return Task.CompletedTask;
})
{ CatchUpWithin = TimeSpan.FromHours(4) }, Off);
scheduler.Add(new ScheduledJob("pulizia", "Pulizia", Schedule.Daily(new TimeOnly(1, 0), Zones.Rome), _ =>
{
counts.Plain++;
return Task.CompletedTask;
}), Off);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
while (runs.TryRead(out var run))
{
if (run!.Missed && run.Outcome == JobOutcome.Skipped)
{
counts.Skipped.Add(run);
}
else if (run.Missed)
{
Assert.AreEqual(JobOutcome.Completed, run.Outcome);
StringAssert.StartsWith(AbsenceBook.MissedLine(run, Zones.Rome), "Recuperato un lavoro saltato: salvataggio del database (previsto alle 03:30)");
}
}
return counts;
}
private static async Task<List<string>> DiaryAsync(TradingRig rig) =>
[.. await rig.QueryAsync("SELECT message FROM journal ORDER BY occurred_at, id", r => r.Text("message")).ConfigureAwait(false)];
private static async Task<string?> LastDiaryAsync(TradingRig rig, string code) =>
(await rig.QueryAsync("SELECT message FROM journal WHERE code = @c ORDER BY occurred_at DESC, id DESC", r => r.Text("message"), ("c", code)).ConfigureAwait(false)) is { Count: > 0 } rows ? rows[0] : null;
}
+136
View File
@@ -0,0 +1,136 @@
using System.Reflection;
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The diary from reason codes and the "senza bot" comparison (issue #50, SPEC 5.2, 7.5, appendix B and F.10).</summary>
[TestClass]
public sealed class DiaryTests
{
private static readonly CancellationToken _none = CancellationToken.None;
// The appendix writes plain spaces; the bot puts a non-breaking one between a number and its currency.
private static string Plain(string text) => text.Replace(' ', ' ');
[TestMethod]
public void TheTemplatesWriteTheSentencesOfTheAppendix()
{
Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.",
Plain(DiaryText.StopRaised("BTC-EUR", 65400m, 66180m, "EUR")));
Assert.AreEqual(
"Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.",
DiaryText.CryptoClose(new DecisionSummary([], [], [], [], ["BTC-EUR", "ETH-EUR", "SOL-EUR"], 7)));
Assert.AreEqual("Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.",
Plain(DiaryText.Fill(OrderSide.Sell, 1m, "MSFT", crypto: false, 522.14m, "USD", closed: new ClosedTrade(9.84m, 3))));
Assert.AreEqual("Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.",
Plain(DiaryText.Fill(OrderSide.Buy, 2m, "AAPL", crypto: false, 259.80m, "USD", "Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.")));
Assert.AreEqual("Rimessi 6 stop giornalieri sulle frazioni di azione.", DiaryText.StopsReplaced(6));
Assert.AreEqual("Azioni: nessun nuovo acquisto. AAPL resta aperta.", DiaryText.StockSignals(new DecisionSummary([], [], [], [], ["AAPL"], 0)));
// Changes, coins and agreement.
Assert.AreEqual("Chiusura giornaliera crypto: compro ETH, vendo SOL. BTC resta in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.",
DiaryText.CryptoClose(new DecisionSummary(["ETH-EUR"], [], [], ["SOL-EUR"], ["BTC-EUR"], 7)));
Assert.AreEqual("Azioni: domani compro AAPL e MSFT, vendo JPM.", DiaryText.StockSignals(new DecisionSummary(["AAPL", "MSFT"], [], [], ["JPM"], [], 0)));
Assert.AreEqual("Comprati 0,0512 BTC/EUR a 66.180,00 €.", Plain(DiaryText.Fill(OrderSide.Buy, 0.0512m, "BTC-EUR", crypto: true, 66180m, "EUR")));
Assert.AreEqual("Venduto 1 ETH/EUR a 3.010,50 €: −42,10 € in giornata. Stop di protezione raggiunto.",
Plain(DiaryText.Fill(OrderSide.Sell, 1m, "ETH-EUR", crypto: true, 3010.50m, "EUR", ReasonCatalog.Text("stop"), new ClosedTrade(-42.10m, 0))));
Assert.AreEqual("Trend crypto, in osservazione: avrei comprato BTC/EUR. Nessun ordine: registro solo il segnale.",
DiaryText.Observed(StrategyNames.CryptoTrend, new DecisionSummary(["BTC-EUR"], [], [], [], [], 0)));
Assert.AreEqual("3 ore", DiaryText.Duration(TimeSpan.FromHours(3)));
Assert.AreEqual("20 ore e 5 minuti", DiaryText.Duration(new TimeSpan(20, 5, 0)));
Assert.AreEqual("3 giorni", DiaryText.Duration(TimeSpan.FromDays(3)));
Assert.AreEqual("1 giorno e 1 ora", DiaryText.Duration(TimeSpan.FromHours(25)));
// No jargon and no exclamation marks (appendix B).
foreach (var sentence in new[] { DiaryText.Absence(TimeSpan.FromHours(20)), DiaryText.EntryDropped("AAPL", 1.4m, 1m), DiaryText.NoData(StrategyNames.EquityMomentum, "le barre di chiusura") })
{
Assert.DoesNotContain("!", sentence);
Assert.DoesNotContain("stop loss", sentence, StringComparison.OrdinalIgnoreCase);
}
}
[TestMethod]
public void EveryReasonCodeHasItsSentence()
{
// Every code a strategy, a corrective, the risk engine or the order rules can write: the diary never shows a bare code.
var holders = typeof(DiaryText).Assembly.GetTypes().Where(t => t.Name == "Reasons" || (t.Name.EndsWith("Reasons", StringComparison.Ordinal) && t.IsAbstract && t.IsSealed));
var codes = holders.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static))
.Where(f => f.IsLiteral && f.FieldType == typeof(string) && !f.Name.EndsWith("Prefix", StringComparison.Ordinal))
.Select(f => (string)f.GetRawConstantValue()!)
.ToList();
Assert.IsGreaterThan(40, codes.Count, "The reason classes were found.");
var missing = codes.Where(c => !ReasonCatalog.Has(c)).ToList();
Assert.IsEmpty(missing, "Codes without a sentence: " + string.Join(", ", missing));
Assert.IsTrue(codes.All(c => !ReasonCatalog.Text(c).Contains('!', StringComparison.Ordinal)));
}
[TestMethod]
public void TheComparisonInvestsEveryFlowOnItsDayAndNeverTouchesIt()
{
var d1 = new DateOnly(2026, 1, 5);
var d2 = new DateOnly(2026, 2, 2);
var d3 = new DateOnly(2026, 3, 2);
var prices = new Dictionary<DateOnly, (decimal Bitcoin, decimal Stock)>
{
[d1] = (50000m, 500m),
[d2] = (60000m, 500m),
[d3] = (60000m, 550m),
};
(decimal Bitcoin, decimal Stock)? At(DateOnly day) => prices.TryGetValue(day, out var p) ? p : null;
// 10,000 € on day 1: 4,000 in Bitcoin, 6,000 in the S&P 500. Bitcoin +20%: 4,800 + 6,000.
Assert.AreEqual(10800m, NoBot.Value([(d1, 10000m)], At, d2));
// A deposit of 1,000 € on day 2 buys at day 2's prices: it is not a gain. S&P +10% on day 3.
// Units: 0.08 + 0.0066667 BTC = 0.0866667 × 60,000 = 5,200; 12 + 1.2 SPY = 13.2 × 550 = 7,260.
Assert.AreEqual(12460m, NoBot.Value([(d1, 10000m), (d2, 1000m)], At, d3));
// A withdrawal sells both in the proportion they reached: half of 10,800 out leaves 5,400, then S&P +10%.
Assert.AreEqual(5700m, NoBot.Value([(d1, 10000m), (d2, -5400m)], At, d3));
// No flows, or a missing price: no comparison rather than a wrong one.
Assert.IsNull(NoBot.Value([], At, d3));
Assert.IsNull(NoBot.Value([(new DateOnly(2025, 12, 1), 10000m)], At, d3));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePhotographOfTheTotalCarriesTheComparisonOnlyWithBothSeries()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var fx = new FxStore(rig.Db, rig.Clock);
var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, 1)",
_none, ("id", Ids.NewId(rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", okx.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false);
var today = DateOnly.FromDateTime(rig.Clock.UtcNow.UtcDateTime);
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx);
await fx.UpsertAsync([new FxRate("EUR", "USD", today.AddDays(-3), 1.10m, "ecb")], _none).ConfigureAwait(false);
await capital.SetAsync(Venues.Okx, 10000m, "test", _none).ConfigureAwait(false);
var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx);
// Without the SPY history (no Alpaca keys) there is no comparison: null, never a half one.
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.IsNull(await BenchmarkAsync(rig).ConfigureAwait(false));
// With both: BTC-EUR on OKX, SPY on Alpaca in dollars at 1.10 $/€.
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
var spy = await rig.InstrumentAsync(TradingRig.Stock("SPY")).ConfigureAwait(false);
var bars = new BarStore(rig.Db, rig.Clock);
await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today.AddDays(-1), 50000, 50000, 50000, 50000, 1)], "test", _none).ConfigureAwait(false);
await bars.UpsertDailyAsync(spy.Id, [new DailyBar(today.AddDays(-1), 550, 550, 550, 550, 1)], "test", _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMinutes(5));
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.AreEqual(10000m, await BenchmarkAsync(rig).ConfigureAwait(false), "Invested today at today's prices: worth what was put in.");
// The next day Bitcoin is up 10%: 4,000 € become 4,400 €.
rig.Clock.Advance(TimeSpan.FromDays(1));
await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today, 55000, 55000, 55000, 55000, 1)], "test", _none).ConfigureAwait(false);
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.AreEqual(10400m, await BenchmarkAsync(rig).ConfigureAwait(false));
}
private static async Task<decimal?> BenchmarkAsync(TradingRig rig) =>
(await rig.QueryAsync("SELECT benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC, id DESC LIMIT 1", r => r.MoneyOrNull("benchmark")).ConfigureAwait(false))[0];
}
+425
View File
@@ -0,0 +1,425 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Supervision;
using Anubis.Trading;
using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Tests;
/// <summary>The guard (issue #48, SPEC 9.3, 9.4): when it intervenes, what it does on the broker, and the restart.</summary>
[TestClass]
public sealed class GuardTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly TimeSpan _minute = TimeSpan.FromMinutes(1);
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TwoMinutesOfSilenceAfterAStartMakeTheGuardInterveneAndRestartWithoutTheFault()
{
using var g = new GuardRig(fault: true);
g.Engine.Beat(GuardStages.Starting, "database");
await g.PassAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
g.Engine.Beat(GuardStages.Running);
await g.PassAsync(TimeSpan.FromMinutes(10), () => g.Engine.Beat(GuardStages.Running)).ConfigureAwait(false);
await g.PassAsync(TimeSpan.FromSeconds(110)).ConfigureAwait(false);
Assert.AreEqual(0, g.Guardian.Interventions, "Five minutes of startup, a loop that beats, then 1:50 of silence: nothing yet.");
await g.PassAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false);
Assert.AreEqual(1, g.Guardian.Interventions);
Assert.IsTrue(g.Engines[0].Killed);
Assert.HasCount(2, g.Engines);
Assert.IsTrue(g.Engines[0].Start.Fault, "The first engine had the drill's fault…");
Assert.IsFalse(g.Engines[1].Start.Fault, "…the one the guard restarts never has it.");
Assert.Contains("non dava segni di vita da 2 minuti", g.Alerts.Single());
var note = GuardFiles.ReadNotes(g.Paths).Single().Note;
Assert.AreEqual(GuardNote.Silence, note.Reason);
Assert.Contains("Non ho trovato il file di stato", string.Join(" ", note.Lines));
Assert.IsFalse(File.Exists(g.Paths.StopFile));
// What the stopped engine's pipe still delivers is not about the new one: it is not "running", and its crash
// is not a planned stop.
g.Engines[0].Beat(GuardStages.Running);
g.Engines[0].Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" });
Assert.AreEqual(GuardStages.Starting, g.Guardian.Stage);
g.Engine.Beat(GuardStages.Running);
Assert.AreEqual(GuardStages.Running, g.Guardian.Stage);
g.Engine.Exit(1);
await g.PassAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
Assert.HasCount(3, g.Engines, "An exit without notice is restarted, whatever the old engine said.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheErrorPageIsNeverAReasonToIntervene()
{
using var g = new GuardRig();
g.Engine.Beat(GuardStages.Waiting);
await g.PassAsync(TimeSpan.FromHours(1)).ConfigureAwait(false);
Assert.AreEqual(0, g.Guardian.Interventions);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task StartupStepsThatDoNotMoveForTenMinutesMakeTheGuardIntervene()
{
using var g = new GuardRig();
g.Engine.Beat(GuardStages.Starting, "migrazioni e identità");
await g.PassAsync(TimeSpan.FromMinutes(9)).ConfigureAwait(false);
g.Engine.Beat(GuardStages.Starting, "riconciliazione OKX demo");
await g.PassAsync(TimeSpan.FromMinutes(9), () => g.Engine.Beat(GuardStages.Starting, "riconciliazione OKX demo")).ConfigureAwait(false);
Assert.AreEqual(0, g.Guardian.Interventions, "A step that moves resets the count; the same step repeated does not.");
await g.PassAsync(TimeSpan.FromMinutes(2)).ConfigureAwait(false);
Assert.AreEqual(1, g.Guardian.Interventions);
Assert.Contains("al passo \"riconciliazione OKX demo\"", g.Alerts.Single());
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AJumpOfTheGuardsOwnClockIsNotSilence()
{
using var g = new GuardRig();
g.Engine.Beat(GuardStages.Running);
await g.PassAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
// The computer slept for a quarter of an hour: guard and engine both stopped.
g.Clock.Advance(TimeSpan.FromMinutes(15));
await g.Guardian.RoundAsync(_none).ConfigureAwait(false);
await g.PassAsync(TimeSpan.FromSeconds(110)).ConfigureAwait(false);
Assert.AreEqual(0, g.Guardian.Interventions);
await g.PassAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false);
Assert.AreEqual(1, g.Guardian.Interventions, "After the jump the silence counts again from the wake-up.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheContainersStopIsPassedOnAndNeverRestarted()
{
using var g = new GuardRig();
g.Engine.Beat(GuardStages.Running);
Assert.AreEqual(0, await g.Guardian.StopAsync().ConfigureAwait(false));
Assert.IsTrue(g.Engine.StopAsked);
Assert.IsFalse(g.Engine.Killed);
Assert.HasCount(1, g.Engines);
// An engine that does not close in time is ended.
using var slow = new GuardRig(options: new GuardOptions { GracefulStop = TimeSpan.FromMilliseconds(200) });
slow.Engine.ExitOnStop = false;
Assert.AreEqual(137, await slow.Guardian.StopAsync().ConfigureAwait(false));
Assert.IsTrue(slow.Engine.Killed);
Assert.AreEqual(0, slow.Guardian.Interventions);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AStopTheEngineAnnouncesEndsTheGuardWithoutARestart()
{
using var g = new GuardRig();
g.Engine.Beat(GuardStages.Running);
g.Engine.Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" });
g.Engine.Exit(0);
Assert.AreEqual(0, await g.Guardian.RoundAsync(_none).ConfigureAwait(false));
Assert.HasCount(1, g.Engines);
Assert.AreEqual(0, g.Guardian.Interventions);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheThirdForcedRestartWithinAnHourRestartsInStopEverything()
{
using var g = new GuardRig();
for (var i = 1; i <= 3; i++)
{
g.Engine.Beat(GuardStages.Running);
await g.PassAsync(TimeSpan.FromMinutes(3)).ConfigureAwait(false);
Assert.AreEqual(i, g.Guardian.Interventions);
Assert.AreEqual(i == 3, File.Exists(g.Paths.StopFile), $"After intervention {i}.");
}
var last = GuardFiles.ReadNotes(g.Paths)[^1].Note;
Assert.IsTrue(last.StopFileCreated);
Assert.Contains("\"Ferma tutto\"", g.Alerts[^1]);
// Spread over more than an hour, three are not three within an hour.
using var spread = new GuardRig();
for (var i = 0; i < 3; i++)
{
spread.Engine.Beat(GuardStages.Running);
await spread.PassAsync(TimeSpan.FromMinutes(3)).ConfigureAwait(false);
spread.Engine.Beat(GuardStages.Running);
await spread.PassAsync(TimeSpan.FromMinutes(30), () => spread.Engine.Beat(GuardStages.Running)).ConfigureAwait(false);
}
Assert.AreEqual(3, spread.Guardian.Interventions);
Assert.IsFalse(File.Exists(spread.Paths.StopFile));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AnEngineThatKeepsClosingIsRestartedWithPausesAndTheUserIsRemindedEveryHour()
{
using var g = new GuardRig(options: new GuardOptions { StalledStart = TimeSpan.FromHours(5) });
g.Engine.Exit(1);
await g.Guardian.RoundAsync(_none).ConfigureAwait(false);
Assert.HasCount(2, g.Engines, "The first restart is immediate.");
Assert.Contains("si è chiuso senza avvisare", g.Alerts[0]);
g.Engine.Exit(1);
await g.Guardian.RoundAsync(_none).ConfigureAwait(false);
Assert.HasCount(2, g.Engines, "The second waits ten seconds.");
await g.PassAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.HasCount(3, g.Engines);
// It starts, but never gets to run: every hour a reminder about the stops on fractions of shares.
await g.PassAsync(TimeSpan.FromMinutes(61)).ConfigureAwait(false);
var reminder = g.Alerts.Single(a => a.Contains("non riparte", StringComparison.Ordinal));
Assert.Contains("frazioni di azione scadono a fine seduta", reminder);
g.Engine.Beat(GuardStages.Running);
await g.PassAsync(TimeSpan.FromMinutes(70), () => g.Engine.Beat(GuardStages.Running)).ConfigureAwait(false);
Assert.AreEqual(1, g.Alerts.Count(a => a.Contains("non riparte", StringComparison.Ordinal)), "Once it runs, the reminders stop.");
}
/// <summary>
/// The acceptance test of issue #48 on a broker account: the main loop blocks right after a sale leaves, with the
/// stop already removed. The guard stops the engine, cancels the sale, puts the stop back for the quantity held and
/// restarts the engine, which adopts the guard's stop and finds the account in order.
/// </summary>
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo).ConfigureAwait(false);
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
var paper = rig.Paper(PaperOptions.Okx(), account.AccountId);
await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 100_000m, "EUR", "test", _none).ConfigureAwait(false);
rig.Quote(btc.Symbol, 60000m, 60010m);
// The demo account at the broker, which the guard reaches on its own.
var remote = new FaultyBroker(paper, TradingEnvironments.Demo);
using var hang = new CancellationTokenSource();
var sold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
OrderManager Engine(Func<CancellationToken, Task>? afterSale) => new(rig.Db, rig.Clock, rig.Ledger, remote, account, TradingRig.Installation, rig.FindAsync, rig.QuoteAsync)
{
ConfirmPrice = rig.QuoteAsync,
MarketOpen = (_, _) => Task.FromResult(true),
AfterSale = afterSale,
};
using var first = Engine(async _ =>
{
sold.TrySetResult();
await Task.Delay(Timeout.Infinite, hang.Token).ConfigureAwait(false);
});
await first.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock))
{
StopLevel = 57000m,
StartAggressive = true,
}, _none).ConfigureAwait(false);
await rig.TurnsAsync(first, 3, _minute).ConfigureAwait(false);
var held = (await rig.Ledger.PositionAsync(account.AccountId, btc.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
Assert.AreEqual(held, (await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false)).Sum(o => o.Quantity));
var folder = Directory.CreateTempSubdirectory("anubis-guard-").FullName;
try
{
var paths = new GuardPaths(folder);
GuardFiles.WriteState(paths, new GuardState(rig.Clock.UtcNow, TradingRig.Installation, [await first.GuardAccountAsync(_none).ConfigureAwait(false)]));
// The sale: the stop goes, the order leaves, and the loop never comes back.
await first.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(rig.Clock)), _none).ConfigureAwait(false);
var blocked = Task.Run(() => first.TickAsync(hang.Token));
await sold.Task.WaitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
Assert.IsEmpty(await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false), "Halfway: the stop is gone…");
Assert.HasCount(1, await OpenAsync(remote, OrderPurpose.Exit).ConfigureAwait(false), "…and the sale waits on the book.");
// The guard: two minutes of silence, then it works on the account with the keys it was given.
var engines = new List<FakeEngine>();
var guardian = new Guardian(paths, rig.Clock, new GuardOptions(), s =>
{
var engine = new FakeEngine(s);
engines.Add(engine);
return engine;
}, (a, keys) => a.AccountId == account.AccountId && keys.Count > 0 ? remote : null, (_, _, _) => Task.CompletedTask, NullLogger.Instance);
guardian.Start();
engines[0].Start.OnMessage(new GuardMessage(GuardMessageTypes.Keys) { Keys = [new GuardKeys(Venues.Okx, TradingEnvironments.Demo, ["k", "s", "p"])] });
engines[0].Beat(GuardStages.Running);
for (var i = 0; i < 13 && guardian.Interventions == 0; i++)
{
rig.Clock.Advance(TimeSpan.FromSeconds(10));
await guardian.RoundAsync(_none).ConfigureAwait(false);
}
Assert.AreEqual(1, guardian.Interventions);
Assert.IsTrue(engines[0].Killed);
Assert.HasCount(2, engines, "The guard restarted the engine.");
Assert.IsEmpty(await OpenAsync(remote, OrderPurpose.Exit).ConfigureAwait(false), "The sale left waiting is canceled.");
var stops = await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false);
Assert.AreEqual((held, 57000m), (stops.Sum(o => o.Quantity), stops.Single().StopPrice), "The stop is back for the whole quantity.");
var note = GuardFiles.ReadNotes(paths).Single().Note;
Assert.AreEqual(stops.Single().ClientOrderId, note.Placed.Single().ClientOrderId);
Assert.IsTrue(note.Lines.Any(l => l.Contains("Ho annullato la vendita di BTC", StringComparison.Ordinal)), string.Join(" | ", note.Lines));
// The engine starts again (SPEC 9.4): it adopts the guard's stop, reconciles, cancels what it had left open.
using var second = Engine(null);
using var live = new LiveEngine(rig.Db, rig.Clock, rig.Ledger, new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)),
_ => second, rig.QuoteAsync);
Assert.IsTrue(await second.AdoptStopAsync(note.Placed.Single(), _none).ConfigureAwait(false));
var report = await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(second, _none).ConfigureAwait(false);
await live.ResumeAsync(second, _none).ConfigureAwait(false);
await second.AlignStopsAsync(_none).ConfigureAwait(false);
engines[1].Beat(GuardStages.Running);
await rig.TurnsAsync(second, 2, _minute).ConfigureAwait(false);
// The only thing the engine finds changed is the sale the guard canceled; nothing is left different.
Assert.IsEmpty(report.Differences, string.Join(" | ", report.Differences.Select(d => d.Message)));
Assert.AreEqual(OrderPurpose.Exit, ClientOrderIds.Parse(report.Healed.Single().Split(':')[1])?.Purpose, report.Healed.Single());
Assert.AreEqual(GuardStages.Running, guardian.Stage);
var after = await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false);
Assert.AreEqual(stops.Single().ClientOrderId, after.Single().ClientOrderId, "The guard's stop stays: no second stop on the same quantity.");
var sale = await rig.QueryAsync("SELECT status, reason FROM executions WHERE side = 'sell'", r => r.Text("status") + "/" + r.TextOrNull("reason")).ConfigureAwait(false);
Assert.AreEqual("canceled/" + LiveReasons.Restart, sale.Single());
var adopted = await rig.QueryAsync("SELECT status, reason FROM orders WHERE client_order_id = @c", r => r.Text("status") + "/" + r.TextOrNull("reason"),
("c", after.Single().ClientOrderId)).ConfigureAwait(false);
Assert.AreEqual("submitted/placed by the guard", adopted.Single());
Assert.AreEqual((held, 57000m), await rig.Ledger.PositionAsync(account.AccountId, btc.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false) is { } p
? (p.Quantity, p.StopPrice!.Value) : default);
await hang.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => blocked).ConfigureAwait(false);
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
/// <summary>
/// The same proof with real processes (the drill that also runs in the Docker image): the real guard, the real
/// engine as its child, a sale blocked halfway on the internal simulator, then the restart by SPEC 9.4.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
[Timeout(600_000, CooperativeCancellation = true)]
public async Task TheGuardDrillPassesWithTheRealEngineAsChildProcess()
{
if (TestDatabase.Engine == "postgres")
{
Assert.Inconclusive("The drill has its own SQLite database: it runs in the SQLite pass.");
}
var folder = Directory.CreateTempSubdirectory("anubis-drill-").FullName;
try
{
var result = await GuardDrill.RunInAsync(folder, Path.Combine(AppContext.BaseDirectory, "Anubis.Server.dll"), GuardDrill.Options,
line => Console.WriteLine(line), _none).ConfigureAwait(false);
Assert.IsTrue(result.Passed, string.Join(Environment.NewLine, result.Lines));
}
finally
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (IOException)
{
}
}
}
private static async Task<List<BrokerOrder>> OpenAsync(FaultyBroker broker, OrderPurpose purpose) =>
[.. (await broker.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Where(o => ClientOrderIds.Parse(o.ClientOrderId)?.Purpose == purpose)];
/// <summary>The engine process as the guard sees it, driven by the test.</summary>
private sealed class FakeEngine(EngineStart start) : IEngineProcess
{
private readonly TaskCompletionSource<int> _exit = new(TaskCreationOptions.RunContinuationsAsynchronously);
public EngineStart Start { get; } = start;
public Task<int> Exited => _exit.Task;
public bool StopAsked { get; private set; }
public bool Killed { get; private set; }
public bool ExitOnStop { get; set; } = true;
public Task RequestStopAsync(CancellationToken cancellationToken)
{
StopAsked = true;
if (ExitOnStop)
{
Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" });
_exit.TrySetResult(0);
}
return Task.CompletedTask;
}
public void Kill()
{
Killed = true;
_exit.TrySetResult(137);
}
public void Exit(int code) => _exit.TrySetResult(code);
public void Beat(string stage, string? step = null) => Start.OnMessage(GuardMessage.Beat(stage, step));
public void Dispose()
{
}
}
/// <summary>A guard on a manual clock with fake engines, a data folder of its own and the alerts it sends.</summary>
private sealed class GuardRig : IDisposable
{
public GuardRig(bool fault = false, GuardOptions? options = null)
{
Folder = Directory.CreateTempSubdirectory("anubis-guard-").FullName;
Paths = new GuardPaths(Folder);
Guardian = new Guardian(Paths, Clock, options ?? new GuardOptions(), s =>
{
var engine = new FakeEngine(s);
Engines.Add(engine);
return engine;
}, (_, _) => null, (text, _, _) =>
{
Alerts.Add(text);
return Task.CompletedTask;
}, NullLogger.Instance);
Guardian.Start(fault);
}
public ManualClock Clock { get; } = new(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
public string Folder { get; }
public GuardPaths Paths { get; }
public Guardian Guardian { get; }
public List<FakeEngine> Engines { get; } = [];
public List<string> Alerts { get; } = [];
public FakeEngine Engine => Engines[^1];
/// <summary>Time passes in rounds of ten seconds; <paramref name="each"/> runs before every round.</summary>
public async Task PassAsync(TimeSpan span, Action? each = null)
{
for (var t = TimeSpan.Zero; t < span; t += TimeSpan.FromSeconds(10))
{
Clock.Advance(TimeSpan.FromSeconds(10));
each?.Invoke();
await Guardian.RoundAsync(_none).ConfigureAwait(false);
}
}
public void Dispose() => Directory.Delete(Folder, recursive: true);
}
}
+178
View File
@@ -0,0 +1,178 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The live engine in simulation (issue #47, SPEC 5.5, 5.6, 12.3, 17 phase 6).</summary>
[TestClass]
public sealed class LiveEngineTests
{
private static readonly DateOnly LiveFrom = new(2026, 9, 1);
[TestMethod]
public async Task TheLiveEngineMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(39);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.DayAsync(day).ConfigureAwait(false);
}
// The backtest decides on the close of the day before the first live morning and fills on the live days, with
// the same correctives (crypto regime) and the same risk stage.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic path should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// Every decision was written once, with its run key.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
Assert.HasCount(40, runs);
Assert.AreEqual(0, live.Failures);
}
/// <summary>
/// The stock side (SPEC 5.5): equity_meanrev decides after the close, buys at the next open, leaves five minutes
/// before the close; the trades are the backtest's, which buys at the open and sells at the close.
/// </summary>
[TestMethod]
public async Task TheStockSideMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(41);
await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.SessionAsync(day).ConfigureAwait(false);
}
var run = live.Backtest(StrategyNames.EquityMeanrev, LiveFrom.AddDays(-1), last);
var expected = LiveRig.Grouped(run, LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic stocks should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// One decision per session, each written once: the close of the day before the first one included, made at the
// first start as a recovered decision.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
var sessions = WeekdayCalendar.Sessions(LiveFrom.AddDays(-1), last).Count();
Assert.HasCount(sessions, runs.Where(r => r.StartsWith(StrategyNames.EquityMeanrev + ":", StringComparison.Ordinal)).ToList());
}
/// <summary>
/// SPEC 17 phase 6: an accelerated run of at least 10 market days with faults injected (network, a restart
/// halfway through an order, the database unreachable) ends with ledger and account reconciled and no order sent
/// twice; the trades are still the backtest's.
/// </summary>
[TestMethod]
public async Task TenDaysWithFaultsEndReconciledWithoutDuplicateOrders()
{
var last = LiveFrom.AddDays(13);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
var restarted = false;
var waited = false;
(int Runs, int Sent) before = default;
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
var index = day.DayNumber - LiveFrom.DayNumber;
Func<int, Task>? faults = index switch
{
// Network down for the first minutes of the decision: no quotes, no broker. When it comes back, the
// answer to the first order is lost on the way back.
0 => minute =>
{
live.Rig.QuotesDown = live.Broker.Down = minute < 4;
if (minute == 4)
{
live.Broker.LoseNextAnswer = true;
}
return Task.CompletedTask;
}
,
// The account has not finished its startup (the broker did not answer it): for three minutes nothing is
// decided or sent on it, then the decision is made late.
5 => async minute =>
{
var runs = (await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false)).Count;
if (minute == 0)
{
before = (runs, live.Sent.Count);
}
else if (minute == 3)
{
Assert.AreEqual(before, (runs, live.Sent.Count), "Nothing is decided or sent on an account not started.");
waited = true;
}
live.AccountStarted = minute >= 3;
}
,
// The process dies with a purchase working at the broker and starts again.
11 => async minute =>
{
if (!restarted && await live.WorkingOrdersAsync().ConfigureAwait(false) > 0)
{
restarted = true;
await live.RestartAsync().ConfigureAwait(false);
}
}
,
// The database cannot be reached around the decision.
12 => minute =>
{
live.DatabaseDown = minute < 6;
return Task.CompletedTask;
}
,
_ => null,
};
await live.DayAsync(day, faults).ConfigureAwait(false);
if (index == 0)
{
Assert.IsFalse(live.Broker.LoseNextAnswer, "An answer must have been lost.");
}
}
Assert.IsTrue(restarted, "The run must restart halfway through an order.");
Assert.IsTrue(waited, "The run must hold an account not started.");
Assert.AreEqual(1, live.Restarts);
Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work.");
// The trades are the backtest's: the faults delayed them by minutes, never changed or repeated them.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// No order twice: one order per client id, one execution per order key, one decision per run key.
var orders = await live.Rig.QueryAsync("SELECT client_order_id FROM orders", r => r.Text("client_order_id")).ConfigureAwait(false);
Assert.HasCount(orders.Distinct(StringComparer.Ordinal).Count(), orders);
foreach (var id in live.Sent.Select(r => r.ClientOrderId).Distinct(StringComparer.Ordinal))
{
Assert.Contains(id, orders, "Every order sent is in the ledger.");
}
var keys = await live.Rig.QueryAsync("SELECT order_key FROM executions", r => r.Text("order_key")).ConfigureAwait(false);
Assert.HasCount(keys.Distinct(StringComparer.Ordinal).Count(), keys);
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(14, runs.Distinct(StringComparer.Ordinal));
Assert.HasCount(14, runs);
// Ledger and account agree; the account may keep dust below the lot that the ledger wrote off (SPEC 7.2).
var report = await live.Reconciler.ReconcileAsync(live.Manager, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences));
var ledger = (await live.Rig.Ledger.PositionsAsync(live.Okx.AccountId, CancellationToken.None).ConfigureAwait(false))
.Where(p => p.Quantity != 0m)
.GroupBy(p => p.InstrumentId).ToDictionary(g => live.Instruments.Values.Single(i => i.Id == g.Key).Symbol, g => g.Sum(p => p.Quantity), StringComparer.Ordinal);
var account = (await live.Paper.GetPositionsAsync(CancellationToken.None).ConfigureAwait(false)).Where(p => p.Quantity != 0m)
.ToDictionary(p => p.Symbol, p => p.Quantity, StringComparer.Ordinal);
CollectionAssert.AreEquivalent(account.Where(a => a.Value >= (live.Instruments[a.Key].Spec.LotSize ?? 0m)).Select(a => a.Key).ToList(), ledger.Keys.ToList());
foreach (var (symbol, quantity) in account.Where(a => ledger.ContainsKey(a.Key)))
{
Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol);
}
}
}
+217
View File
@@ -0,0 +1,217 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>Every weekday is a session, 9:30–16:00 in New York (13:30–20:00 UTC in September and October).</summary>
internal sealed class WeekdayCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day) => day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday
? null
: new MarketSession(day, new DateTimeOffset(day.ToDateTime(new TimeOnly(13, 30)), TimeSpan.Zero), new DateTimeOffset(day.ToDateTime(new TimeOnly(20, 0)), TimeSpan.Zero));
public static IEnumerable<DateOnly> Sessions(DateOnly from, DateOnly to)
{
for (var day = from; day <= to; day = day.AddDays(1))
{
if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
{
yield return day;
}
}
}
}
/// <summary>
/// The stock side of the live engine on the internal Alpaca simulator (issue #47, SPEC 5.5): signals after the close,
/// the orders at the next open, the exits of equity_meanrev five minutes before the close, with synthetic stocks that
/// dip for three sessions and recover.
/// </summary>
internal sealed class StockRig : IAsyncDisposable
{
public static readonly string[] Stocks = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"];
/// <summary>Dollars for a euro: the capital is entrusted in euro (SPEC 7.1).</summary>
public const decimal Rate = 1.10m;
private readonly Dictionary<string, Instrument> _instruments = new(StringComparer.Ordinal);
private readonly WeekdayCalendar _calendar = new();
private StockRig(TradingRig rig) => Rig = rig;
public TradingRig Rig { get; }
public AccountContext Alpaca { get; private set; } = null!;
public PaperBroker Paper { get; private set; } = null!;
public OrderManager Manager { get; private set; } = null!;
public LiveEngine Engine { get; private set; } = null!;
public EquityBook Equity { get; private set; } = null!;
public Dictionary<string, List<DailyBar>> Bars { get; } = new(StringComparer.Ordinal);
public static async Task<StockRig> CreateAsync(DateOnly liveFrom, DateOnly last, string strategy = StrategyNames.EquityMeanrev, decimal capital = 10_000m)
{
var rig = new StockRig(await TradingRig.CreateAsync().ConfigureAwait(false));
await rig.SetUpAsync(liveFrom, last, strategy, capital).ConfigureAwait(false);
return rig;
}
private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, string strategy, decimal capital)
{
var none = CancellationToken.None;
Rig.Clock.Set(new DateTimeOffset(liveFrom.AddDays(-1).ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero));
Alpaca = await Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
var sessions = WeekdayCalendar.Sessions(last.AddDays(-700), last).ToList();
var store = new BarStore(Rig.Db, Rig.Clock);
var members = new List<UniverseMember>();
for (var i = 0; i < Stocks.Length; i++)
{
var symbol = Stocks[i];
_instruments[symbol] = await Rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false);
Bars[symbol] = Path(sessions, 50 + (i * 20), phase: i * 3, seed: (uint)(i + 11));
members.Add(new UniverseMember(_instruments[symbol].Id, symbol, i + 1, 1e9));
}
_instruments[StrategyNames.MarketSymbol] = await Rig.InstrumentAsync(TradingRig.Stock(StrategyNames.MarketSymbol) with { IsFund = true }).ConfigureAwait(false);
Bars[StrategyNames.MarketSymbol] = Path(sessions, 400, phase: 5, seed: 3, dips: false);
foreach (var (symbol, bars) in Bars)
{
await store.UpsertDailyAsync(_instruments[symbol].Id, bars.Where(b => b.Day < liveFrom), "test", none).ConfigureAwait(false);
}
await new UniverseStore(Rig.Db, Rig.Clock).SaveAsync(Universes.Equity, liveFrom.AddDays(-30), members, none).ConfigureAwait(false);
await Rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)",
none, ("id", Ids.NewId(Rig.Clock)), ("s", strategy), ("a", Alpaca.AccountId), ("st", StrategyStages.Simulation), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none)
.ConfigureAwait(false);
var fx = new FxStore(Rig.Db, Rig.Clock);
await fx.UpsertAsync(WeekdayCalendar.Sessions(liveFrom.AddDays(-10), last).Select(d => new FxRate("EUR", "USD", d, Rate, "test")), none).ConfigureAwait(false);
await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Alpaca, capital, "test", none).ConfigureAwait(false);
Paper = Rig.Paper(PaperOptions.Alpaca(), Alpaca.AccountId);
await Paper.DepositAsync(capital * Rate, "USD", none).ConfigureAwait(false);
Manager = Rig.Manager(Paper, Alpaca);
var stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar);
Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx);
}
/// <summary>
/// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the
/// close under its 5-session average, so equity_meanrev buys and sells a few sessions later.
/// </summary>
public static List<DailyBar> Path(IReadOnlyList<DateOnly> sessions, double start, int phase, uint seed, bool dips = true)
{
var bars = new List<DailyBar>(sessions.Count);
var price = start;
var state = (seed * 2654435761u) + 1u;
double Next()
{
state = (state * 1664525u) + 1013904223u;
return (state >> 8) / (double)(1 << 24);
}
for (var i = 0; i < sessions.Count; i++)
{
var cycle = (i + phase) % 17;
var change = dips && cycle >= 14 ? -0.025 : (dips ? 0.008 : 0.003) + ((Next() - 0.5) * 0.012);
var open = Math.Round(price * (1 + ((Next() - 0.5) * 0.004)), 2);
var close = Math.Round(open * (1 + change), 2);
var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.006)), 2);
var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.006)), 2);
bars.Add(new DailyBar(sessions[i], open, high, low, close, 5_000_000));
price = close;
}
return bars;
}
private DailyBar? Bar(string symbol, DateOnly day) => Bars[symbol].SingleOrDefault(b => b.Day == day);
public void Quotes(DateOnly day, Func<DailyBar, double> pick)
{
foreach (var symbol in Bars.Keys)
{
if (Bar(symbol, day) is { } bar)
{
var price = (decimal)pick(bar);
Rig.Quote(symbol, price - 0.01m, price + 0.01m, 1000m);
}
}
}
public async Task MinutesAsync(int count)
{
for (var i = 0; i < count; i++)
{
await Engine.PulseAsync(CancellationToken.None).ConfigureAwait(false);
await Rig.TurnsAsync(Manager, 1, TimeSpan.FromMinutes(1)).ConfigureAwait(false);
}
}
/// <summary>
/// One session: the orders decided last night go at 9:35 with the open as price; at midday the quotes touch the
/// low (stops); at 15:55 the price is the close and the meanrev exits leave; at 16:16 the bar of the day arrives and
/// at 16:20 the signals are computed; the day orders expire and the equity is photographed.
/// </summary>
public async Task SessionAsync(DateOnly day)
{
if (_calendar.SessionOn(day) is not { } session)
{
return;
}
var none = CancellationToken.None;
Rig.Clock.Set(session.OpenUtc.AddMinutes(5));
Quotes(day, b => b.Open);
await MinutesAsync(15).ConfigureAwait(false);
Rig.Clock.Set(session.OpenUtc.AddHours(3));
Quotes(day, b => b.Low);
await MinutesAsync(3).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(-5));
Quotes(day, b => b.Close);
await MinutesAsync(4).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(1));
await Paper.ExpireDayOrdersAsync(none).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(16));
await Task.WhenAll(Bars.Select(b => new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[b.Key].Id, b.Value.Where(x => x.Day == day), "test", none)))
.ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(20));
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 Equity.TakeAsync(none).ConfigureAwait(false);
}
public BacktestRun Backtest(string strategy, DateOnly from, DateOnly to, decimal capital = 10_000m * Rate)
{
var instruments = Bars.Select(b => new BacktestInstrument(_instruments[b.Key].Spec, b.Value.Where(x => x.Day <= to && x.Day >= to.AddDays(-700)).ToList()));
var calendar = Bars[Stocks[0]].Select(b => b.Day).Where(d => d <= to.AddDays(14));
var data = new BacktestDataset(instruments, "USD", calendar, [StrategyNames.MarketSymbol]);
var options = StrategyPipeline.For(strategy, data, new BacktestOptions { InitialCapital = capital, From = from, To = to });
return BacktestEngine.Run(LiveEngine.CreateStrategy(strategy, null), data, options);
}
/// <summary>The live fills by New York day, symbol and side.</summary>
public async Task<IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)>> LiveFillsAsync()
{
var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at",
r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false);
return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))];
}
public ValueTask DisposeAsync()
{
Engine.Dispose();
return Rig.DisposeAsync();
}
}
+302
View File
@@ -0,0 +1,302 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The live engine on the internal simulator, driven by a manual clock through synthetic days (issue #47): the bars
/// of each day arrive at its end, the quotes follow the open, the low and the close of the day, and the engine and
/// the order manager work minute by minute. The same bars run through the backtest for the parity test; the broker,
/// the quotes and the database can fail, and the process can restart, for the fault run.
/// </summary>
internal sealed class LiveRig : IAsyncDisposable
{
public static readonly string[] Coins = ["BTC-EUR", "ETH-EUR", "SOL-EUR"];
private readonly Dictionary<string, Instrument> _instruments = new(StringComparer.Ordinal);
private readonly List<OrderRequest> _sent = [];
private LiveRig(TradingRig rig) => Rig = rig;
public TradingRig Rig { get; }
public AccountContext Okx { get; private set; } = null!;
public PaperBroker Paper { get; private set; } = null!;
/// <summary>The simulator behind a broker that can lose answers or go down (network faults).</summary>
public FaultyBroker Broker { get; private set; } = null!;
public OrderManager Manager { get; private set; } = null!;
public StageBook Stages { get; private set; } = null!;
public LiveEngine Engine { get; private set; } = null!;
/// <summary>Whether the account finished its startup (SPEC 9.4); while false the engine leaves it alone.</summary>
public bool AccountStarted { get; set; } = true;
public EquityBook Equity { get; private set; } = null!;
public Reconciler Reconciler { get; private set; } = null!;
public Dictionary<string, List<DailyBar>> Bars { get; } = new(StringComparer.Ordinal);
public IReadOnlyDictionary<string, Instrument> Instruments => _instruments;
/// <summary>Work that failed as the scheduler would see it: a pulse or a turn during a fault.</summary>
public int Failures { get; private set; }
public int Restarts { get; private set; }
/// <summary>Every order request that reached the broker, across restarts.</summary>
public IReadOnlyList<OrderRequest> Sent => [.. _sent, .. Broker.Sent];
/// <summary>Every new database connection fails while this is true.</summary>
public bool DatabaseDown
{
get => Rig.Db.Unreachable;
set => Rig.Db.Unreachable = value;
}
/// <summary>
/// <paramref name="days"/> synthetic daily bars for each coin up to <paramref name="last"/>; those before
/// <paramref name="liveFrom"/> are stored at once, the others arrive one per day.
/// </summary>
public static async Task<LiveRig> CreateAsync(DateOnly liveFrom, DateOnly last, int days = 700, string stage = StrategyStages.Simulation, decimal capital = 10_000m)
{
var rig = new LiveRig(await TradingRig.CreateAsync().ConfigureAwait(false));
await rig.SetUpAsync(liveFrom, last, days, stage, capital).ConfigureAwait(false);
return rig;
}
private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, int days, string stage, decimal capital)
{
var none = CancellationToken.None;
Rig.Clock.Set(new DateTimeOffset(liveFrom.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero));
Okx = await Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
var store = new BarStore(Rig.Db, Rig.Clock);
var seed = 7u;
foreach (var (symbol, start) in new[] { ("BTC-EUR", 30000.0), ("ETH-EUR", 2000.0), ("SOL-EUR", 60.0) })
{
var spec = MarketDataStoreTests.Okx(symbol) with { ListedAt = null };
_instruments[symbol] = await Rig.InstrumentAsync(spec).ConfigureAwait(false);
Bars[symbol] = Synthetic(last.AddDays(1 - days), days, start, seed++);
await store.UpsertDailyAsync(_instruments[symbol].Id, Bars[symbol].Where(b => b.Day < liveFrom.AddDays(-1)), "test", none).ConfigureAwait(false);
}
await Rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)",
none, ("id", Ids.NewId(Rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none)
.ConfigureAwait(false);
var fx = new FxStore(Rig.Db, Rig.Clock);
await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Okx, capital, "test", none).ConfigureAwait(false);
Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId);
await Paper.DepositAsync(capital, "EUR", none).ConfigureAwait(false);
Stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx);
Reconciler = new Reconciler(Rig.Db, Rig.Clock, Rig.Ledger);
Build();
}
private void Build()
{
Broker = new FaultyBroker(Paper);
Manager = Rig.Manager(Broker, Okx);
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync)
{
AccountReady = _ => AccountStarted,
};
}
/// <summary>
/// The process dies and starts again: a new simulator on its saved book, a new order manager and engine on the same
/// database, the account reconciled before the first pulse as at a real start (SPEC 9.4).
/// </summary>
public async Task RestartAsync()
{
_sent.AddRange(Broker.Sent);
Engine.Dispose();
Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId);
Build();
Restarts++;
await Reconciler.ReconcileAsync(Manager, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// A deterministic path with regimes: long rises, falls and flat stretches with noise, so the trend strategy enters,
/// moves its stops and leaves. The open of each day is the close of the day before; the volume makes the coin
/// liquid enough for the universe.
/// </summary>
public static List<DailyBar> Synthetic(DateOnly first, int days, double start, uint seed)
{
var bars = new List<DailyBar>(days);
var price = start;
var state = (seed * 2654435761u) + 1u;
double Next()
{
state = (state * 1664525u) + 1013904223u;
return (state >> 8) / (double)(1 << 24);
}
for (var i = 0; i < days; i++)
{
var regime = ((i / 45) + (int)seed) % 4;
var drift = regime switch { 0 => 0.009, 1 => -0.008, 2 => 0.002, _ => 0.012 };
var change = drift + ((Next() - 0.5) * 0.04);
var open = price;
var close = Math.Round(price * (1 + change), 2);
var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.01)), 2);
var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.01)), 2);
bars.Add(new DailyBar(first.AddDays(i), open, high, low, close, 50_000_000 / close));
price = close;
}
return bars;
}
public DailyBar Bar(string symbol, DateOnly day) => Bars[symbol].Single(b => b.Day == day);
/// <summary>The bar of a day reaches the database, as the history step stores it after midnight.</summary>
public Task StoreBarAsync(DateOnly day) => Task.WhenAll(Coins.Select(c =>
new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[c].Id, Bars[c].Where(b => b.Day == day), "test", CancellationToken.None)));
public void Quotes(DateOnly day, Func<DailyBar, double> pick)
{
foreach (var coin in Coins)
{
var price = (decimal)pick(Bar(coin, day));
Rig.Quote(coin, price * 0.9999m, price * 1.0001m, 1000m);
}
}
/// <summary>
/// One UTC day, minute by minute where it matters: yesterday's bar arrives, from 00:05 the engine pulses every
/// minute with the open as price and the orders are worked; at noon the quotes go to the day's low (stops), at the
/// end of the day to the close, where positions are valued and the equity photographed. <paramref name="minute"/>
/// runs before each morning minute with its index: the fault tests break and mend things there.
/// </summary>
public async Task DayAsync(DateOnly day, Func<int, Task>? minute = null, int morning = 20)
{
var none = CancellationToken.None;
var midnight = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
Rig.Clock.Set(midnight.AddMinutes(1));
await StoreBarAsync(day.AddDays(-1)).ConfigureAwait(false);
Rig.Clock.Set(midnight.AddMinutes(5));
Quotes(day, b => b.Open);
for (var i = 0; i < morning; i++)
{
if (minute is not null)
{
await minute(i).ConfigureAwait(false);
}
await MinuteAsync().ConfigureAwait(false);
}
Rig.Clock.Set(midnight.AddHours(12));
Quotes(day, b => b.Low);
for (var i = 0; i < 3; i++)
{
await MinuteAsync().ConfigureAwait(false);
}
Rig.Clock.Set(midnight.AddHours(23).AddMinutes(55));
Quotes(day, b => b.Close);
for (var i = 0; i < 2; i++)
{
await MinuteAsync().ConfigureAwait(false);
}
foreach (var coin in Coins)
{
await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false);
}
await Equity.TakeAsync(none).ConfigureAwait(false);
}
/// <summary>Several minutes of the process from the clock's time.</summary>
public async Task MinutesAsync(int count)
{
for (var i = 0; i < count; i++)
{
await MinuteAsync().ConfigureAwait(false);
}
}
/// <summary>One minute of the process: the engine's pulse, then a turn of the simulator and of the order manager.</summary>
private async Task MinuteAsync()
{
await SafeAsync(() => Engine.PulseAsync(CancellationToken.None)).ConfigureAwait(false);
await SafeAsync(async () =>
{
Rig.Refresh();
await Paper.PumpAsync(CancellationToken.None).ConfigureAwait(false);
await Manager.TickAsync(CancellationToken.None).ConfigureAwait(false);
}).ConfigureAwait(false);
Rig.Clock.Advance(TimeSpan.FromMinutes(1));
}
/// <summary>A failure the scheduler would log and retry at the next run: counted, never thrown.</summary>
private async Task SafeAsync(Func<Task> work)
{
try
{
await work().ConfigureAwait(false);
}
catch (Exception ex) when (ex is System.Data.Common.DbException or BrokerException)
{
Failures++;
}
}
/// <summary>Orders other than the protective stops still working at the simulator.</summary>
public async Task<int> WorkingOrdersAsync() =>
(await Paper.GetOpenOrdersAsync(CancellationToken.None).ConfigureAwait(false)).Count(o => o.StopPrice is null);
/// <summary>The same bars through the backtest, with the same correctives and risk stage, from <paramref name="from"/>.</summary>
public BacktestRun Backtest(DateOnly from, DateOnly to, decimal capital = 10_000m)
{
var data = new BacktestDataset(Coins.Select(c => new BacktestInstrument(_instruments[c].Spec, Bars[c].Where(b => b.Day <= to).ToList())), "EUR");
var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = capital, From = from, To = to });
return BacktestEngine.Run(LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, options);
}
/// <summary>The backtest fills from <paramref name="from"/>, by day, symbol and side.</summary>
public static List<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> Grouped(BacktestRun run, DateOnly from) =>
[.. run.Fills.Where(f => f.Day >= from).GroupBy(f => (f.Day, f.Symbol, f.Side)).Select(g => (g.Key.Day, g.Key.Symbol, g.Key.Side, g.Sum(f => f.Quantity)))];
/// <summary>The live fills by UTC day, symbol and side.</summary>
public async Task<IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)>> LiveFillsAsync()
{
var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at",
r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false);
return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))];
}
/// <summary>The live fills match the backtest's: the same days, symbols and sides, quantities within 1%.</summary>
public static void AssertSameTrades(IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> expected,
IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> actual)
{
var report = "backtest:\n" + string.Join("\n", expected.Select(e => " " + e)) + "\nlive:\n" + string.Join("\n", actual.Select(a => " " + a));
Console.WriteLine(report);
Assert.HasCount(expected.Count, actual, report);
foreach (var e in expected)
{
var match = actual.SingleOrDefault(a => a.Day == e.Day && a.Symbol == e.Symbol && a.Side == e.Side);
Assert.AreNotEqual(default, match, "Missing live fill " + e + "\n" + report);
Assert.IsLessThanOrEqualTo(0.01m, Math.Abs(match.Quantity - e.Quantity) / e.Quantity, "Quantity apart: " + e + " vs " + match + "\n" + report);
}
}
public ValueTask DisposeAsync()
{
DatabaseDown = false;
Engine.Dispose();
return Rig.DisposeAsync();
}
}
+175
View File
@@ -0,0 +1,175 @@
using System.IO.Compression;
using System.Net;
using Anubis.Server;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The Panoramica and "Diario e sistema" screens (issue #51, mockups 01, 08 and 09).</summary>
[TestClass]
public sealed class OverviewScreenTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoPanoramicaShowsAccountsPositionsAndLimits()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var page = await server.TextAsync("/");
foreach (var text in new[]
{
// Adesso e dopo (F.10).
"Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.", "Rimetto gli stop del giorno sulle frazioni di 6 azioni",
"Alzato lo stop di BTC a 66.180", "Apri il diario completo", "Tutte le mosse e il diario",
// The two accounts with their last 30 days (F.2).
"4.231,60", "+231,60", "2.326,50", "1.905,10", "+158,20", "3 posizioni, 3 stop attivi.",
"6.180,86", "4.344,63", "1.836,23", "+93,50", "sulle frazioni tornano alle 15:35",
// The four limits (F.10).
"Tutti i limiti rispettati", "Perdita di oggi", "nessuna", "−2,00%", "Calo dal massimo", "−15,00%", "Capitale investito", "64,1%",
"Posizione più grande (BTC)", "12,5%", "La tacca segna il calo peggiore finora: −2,82%.", "Vedi tutti i limiti",
// Positions by value, strategies, news, model, system.
"BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6",
"In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)",
"Nessuna strategia usa soldi veri.",
"Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL",
"Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00",
"connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00",
})
{
StringAssert.Contains(page, text, $"Missing «{text}» on the Panoramica.");
}
Assert.IsLessThan(page.IndexOf("ETH/EUR", StringComparison.Ordinal), page.IndexOf("BTC/EUR", StringComparison.Ordinal), "Positions in order of value.");
}
finally
{
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDiaryFiltersAndSearches()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var all = await server.TextAsync("/diario");
StringAssert.Contains(all, "Oggi, venerdì 9 ottobre");
StringAssert.Contains(all, "Ieri, giovedì 8 ottobre");
StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:");
StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.");
StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\"");
StringAssert.Contains(all, "Perché l'ho comprata e venduta");
Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown.");
StringAssert.Contains(all, "Tutto regolare");
StringAssert.Contains(all, "collegato, mercato chiuso fino alle 15:30");
StringAssert.Contains(all, "Dom 03:00");
StringAssert.Contains(all, "Anubis 0.9.2 in Docker, acceso dal 12 agosto: 58 giorni senza interruzioni.");
// A kind at a time.
var orders = await server.TextAsync("/diario?tipo=ordini");
StringAssert.Contains(orders, "Alzato lo stop di BTC/EUR");
Assert.IsFalse(orders.Contains("Inviato il riepilogo del mattino", StringComparison.Ordinal));
Assert.IsFalse(orders.Contains("Controllo del modello: nessuna anomalia.", StringComparison.Ordinal));
StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora.");
// The search ignores case and accents, and keeps the kind chosen.
var search = await server.TextAsync("/diario?cerca=MARTEDI");
StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:");
Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal));
StringAssert.Contains(search, "Una voce con «MARTEDI»");
var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana");
StringAssert.Contains(none, "Nessuna voce con «solana»");
}
finally
{
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheLogsDownloadNeedsASessionAndIsAZip()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
var logs = server.Host.Config.Data.Logs;
Directory.CreateDirectory(logs);
await File.WriteAllTextAsync(Path.Combine(logs, "anubis-2099-01-01.log"), "{\"message\":\"una riga\"}\n");
await File.WriteAllTextAsync(Path.Combine(logs, "altro.txt"), "non è un registro");
using (var anonymous = await server.GetAsync("/api/registri.zip"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode);
}
await server.SignInFirstTimeAsync();
using (var zip = await server.GetAsync("/api/registri.zip"))
{
Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType);
await using var stream = await zip.Content.ReadAsStreamAsync();
using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
var names = archive.Entries.Select(e => e.Name).ToList();
Assert.Contains("anubis-2099-01-01.log", names);
Assert.DoesNotContain("altro.txt", names);
using var reader = new StreamReader(archive.GetEntry("anubis-2099-01-01.log")!.Open());
StringAssert.Contains(await reader.ReadToEndAsync(), "una riga");
}
// A new installation: the screens say what is missing instead of showing numbers.
var home = await server.TextAsync("/");
StringAssert.Contains(home, "La lettura delle notizie non è ancora attiva.");
StringAssert.Contains(home, "L'apprendimento non è ancora attivo.");
var diary = await server.TextAsync("/diario");
StringAssert.Contains(diary, "Come sta il sistema");
StringAssert.Contains(diary, "non configurato");
StringAssert.Contains(diary, "Il computer che lo ospita");
// SPEC 5.6: an absence longer than a day stays at the top of the Panoramica until "Ho visto".
var now = server.Host.Clock.UtcNow;
var id = Guid.NewGuid();
await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)",
CancellationToken.None, ("id", id), ("s", now.AddDays(-3).AddHours(-2)), ("e", now)));
StringAssert.Contains(await server.TextAsync("/"), "Sono stato spento per 3 giorni e 2 ore, fino a oggi alle");
using (var seen = await server.PostFormAsync("/", $"/azioni/assenza/{id}/vista"))
{
Assert.AreEqual("/", ServerHarness.Location(seen));
}
Assert.DoesNotContain("Sono stato spento", await server.TextAsync("/"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DiaryEntriesAreSplitAsTheMockupDraws()
{
var at = DateTimeOffset.UnixEpoch;
var rule = DiaryView.Entry(at, DiaryKinds.News, "demo", "Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: la rete è ferma.");
Assert.AreEqual("Ho cambiato una regola per 24 ore:", rule.Lead);
Assert.AreEqual("Motivo: la rete è ferma.", rule.Rest);
Assert.IsTrue(rule.Attention);
var long1 = DiaryView.Entry(at, DiaryKinds.Orders, "stop_moved", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.");
Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €.", string.Concat(long1.Main.Select(p => p.Text)));
Assert.AreEqual("Lo stop segue il prezzo quando sale.", long1.Rest);
Assert.IsNull(long1.Trade);
var shortOne = DiaryView.Entry(at, DiaryKinds.News, "demo", "Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.");
Assert.IsNull(shortOne.Rest, "A short entry stays on one line.");
var sale = DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.");
Assert.AreEqual("MSFT", sale.Trade);
Assert.AreEqual("gain", sale.Main.Single(p => p.Class is not null).Class);
Assert.AreEqual("ETH", DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduto 0,1 ETH/EUR a 2.500 €: −12,00 € in 4 giorni.").Trade);
Assert.IsNull(DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Comprate 2 AAPL a 259,80 $.").Trade, "A purchase has no closed trade to explain.");
Assert.AreEqual("Oggi, venerdì 9 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 9), new DateOnly(2026, 10, 9)));
Assert.AreEqual("Mercoledì 7 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 7), new DateOnly(2026, 10, 9)));
}
}
+2 -1
View File
@@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
}
public static async Task<ServerHarness> StartAsync(string platform, IReadOnlyDictionary<string, string?> environment, string? dataDir = null,
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false)
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false, HttpMessageHandler? telegramHttp = null)
{
var owns = dataDir is null;
dataDir ??= TempFolder.Create("server");
@@ -90,6 +90,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
MarketHttp = marketHttp,
MarketSockets = marketHttp is null ? null : () => new FakeSocket(),
Trading = trading,
TelegramHttp = telegramHttp,
});
await app.StartAsync().ConfigureAwait(false);
var cookies = new CookieContainer();
+18 -14
View File
@@ -200,23 +200,27 @@ public sealed class ServerTests
ServerHarness.UsePostgres(env, empty);
}
await using var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false);
await server.WaitForAsync(HostMode.IdentityProblem);
Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict);
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
// The server stops before its data folder is removed: a running one may still hold the database file.
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
Assert.AreEqual("/", ServerHarness.Location(restore));
await server.WaitForAsync(HostMode.IdentityProblem);
Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict);
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
{
Assert.AreEqual("/", ServerHarness.Location(restore));
}
await server.WaitForAsync(HostMode.Ready);
// SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in.
var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key);
Assert.AreEqual("stopped", state.Value);
var row = await Installation.ReadRowAsync(server.Host.Services.Db);
Assert.IsTrue(row!.ProtectedRestart);
Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint);
Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")));
}
await server.WaitForAsync(HostMode.Ready);
// SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in.
var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key);
Assert.AreEqual("stopped", state.Value);
var row = await Installation.ReadRowAsync(server.Host.Services.Db);
Assert.IsTrue(row!.ProtectedRestart);
Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint);
Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")));
TempFolder.Delete(data);
}
+92
View File
@@ -0,0 +1,92 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Supervision;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The report of the endurance run (SPEC 17, phase 6): regular when the bot kept working, and it says what was not.</summary>
[TestClass]
public sealed class SoakReportTests
{
private static readonly DateTimeOffset From = new(2026, 11, 11, 18, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset To = From.AddHours(49);
[TestMethod]
public void TheDailyCryptoClosesAreCountedInTheWindow()
{
Assert.AreEqual(2, SoakReporter.DailyCloses(From, To)); // 12 and 13 November at 00:05 UTC
var close = new DateTimeOffset(2026, 11, 11, 0, 5, 0, TimeSpan.Zero);
Assert.AreEqual(1, SoakReporter.DailyCloses(close, close + SoakReporter.DecisionTime));
Assert.AreEqual(0, SoakReporter.DailyCloses(close, close.AddMinutes(10)), "A decision just started is not expected yet.");
Assert.AreEqual(3, SoakReporter.DailyCloses(close, To));
Assert.AreEqual(0, SoakReporter.DailyCloses(From, From.AddHours(5)));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AQuietRunIsRegularAndTroublesAreNamed()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var okx = await rig.AccountAsync("okx", "demo").ConfigureAwait(false);
// A quiet run: the scheduler at work from the first minute to the end, the account reconciled and normal at the
// end (a clean round writes no reconciliation row), a crypto decision at each daily close.
await rig.Db.WriteAsync(async s =>
{
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) " +
"VALUES (@id, 'riconciliazione', 'Riconciliazione dei conti', @to, @to, @to, 'ok', NULL, @from, @to)", CancellationToken.None,
("id", Guid.NewGuid()), ("from", From.AddMinutes(1)), ("to", To)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, mode_since, mode_reason, differences, last_reconciled_at, last_outcome, created_at, updated_at) " +
"VALUES (@id, @a, 'normal', NULL, NULL, @d, @to, 'clean', @from, @to)", CancellationToken.None,
("id", Guid.NewGuid()), ("a", okx.AccountId), ("d", new Anubis.Db.DbJson("{\"Current\":[],\"Excluded\":[]}")), ("from", From), ("to", To)).ConfigureAwait(false);
foreach (var day in new[] { 12, 13 })
{
var at = new DateTimeOffset(2026, 11, day, 0, 5, 0, TimeSpan.Zero);
await s.ExecuteAsync(
"INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, NULL, NULL, @at)",
CancellationToken.None, ("id", Guid.NewGuid()), ("s", StrategyNames.CryptoTrend), ("k", $"{StrategyNames.CryptoTrend}:2026-11-{day - 1}"),
("d", $"2026-11-{day - 1}"), ("dec", Guid.NewGuid()), ("m", DecisionModes.Observation), ("at", at)).ConfigureAwait(false);
}
}).ConfigureAwait(false);
var report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false);
var text = report.Markdown(Zones.Rome);
Assert.IsTrue(report.Passed, text);
Assert.Contains("**Esito: regolare.**", text);
Assert.Contains("Durata coperta dal lavoro del bot: 49 ore", text);
Assert.Contains("Al lavoro dall'inizio alla fine della finestra.", text);
Assert.Contains("Ogni conto riconciliato fino alla fine e in regola: ", text);
Assert.Contains("Decisioni di crypto_trend: 2 su 2 chiusure giornaliere.", text);
Assert.Contains("crypto_trend 2 (in osservazione)", text);
Assert.Contains("Ordini: nessuno.", text);
// Off for 35 minutes, a guard intervention, an unexplained difference at the end: each one is named.
await rig.Db.WriteAsync(async s =>
{
var off = From.AddHours(8).AddMinutes(16);
await s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)", CancellationToken.None,
("id", Guid.NewGuid()), ("s", off), ("e", off.AddMinutes(35))).ConfigureAwait(false);
rig.Clock.Set(From.AddHours(20));
await Diary.WriteAsync(s, rig.Clock, DiaryKinds.System, "guard_intervention", "La guardia è intervenuta.", null, CancellationToken.None).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @at, @at)",
CancellationToken.None, ("id", Guid.NewGuid()), ("a", okx.AccountId), ("o", ReconcileOutcomes.Different), ("d", new Anubis.Db.DbJson("{}")), ("at", To)).ConfigureAwait(false);
await s.ExecuteAsync("UPDATE account_status SET mode = 'prudent' WHERE account_id = @a", CancellationToken.None, ("a", okx.AccountId)).ConfigureAwait(false);
}).ConfigureAwait(false);
report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false);
Assert.IsFalse(report.Passed);
var failed = report.Checks.Where(c => !c.Ok).Select(c => c.Text).ToList();
Assert.HasCount(4, failed, string.Join(" | ", failed));
Assert.Contains("Spento: dal 12/11/2026 03:16 per 35 minuti.", failed);
Assert.Contains("Interventi della guardia: 1.", failed);
Assert.Contains("Riconciliazioni con differenze inspiegate: 1.", failed);
Assert.IsTrue(failed.Any(f => f.Contains("in modalità prudente", StringComparison.Ordinal)), string.Join(" | ", failed));
Assert.Contains("**Esito: da guardare.**", report.Markdown(Zones.Rome));
// A bot that fell silent before the end of the window: its last job and the account's last round say when.
var later = await SoakReporter.BuildAsync(rig.Db, From.AddHours(2), To.AddHours(2), TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false);
Assert.IsTrue(later.Checks.Any(c => !c.Ok && c.Text.EndsWith("da allora il bot tace.", StringComparison.Ordinal)), later.Markdown(Zones.Rome));
Assert.IsTrue(later.Checks.Any(c => !c.Ok && c.Text.StartsWith("Durata coperta dal lavoro del bot: 46,4 ore", StringComparison.Ordinal)), later.Markdown(Zones.Rome));
}
}
+366
View File
@@ -0,0 +1,366 @@
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Notifications;
using Anubis.Server;
using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Tests;
/// <summary>Telegram and the sign of life (issue #52, SPEC 14), against a fake Telegram server.</summary>
[TestClass]
public sealed class TelegramTests
{
private const string Token = "123456:fake-token-for-tests_abcdefghijklmnop";
private const string Chat = "424242";
private static readonly CancellationToken _none = CancellationToken.None;
[TestMethod]
[TestCategory(Category.Unit)]
public async Task EveryMessageHasItsStateAndAFailureIsTriedAgainLater()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var telegram = new FakeTelegram();
TelegramSettings? configured = null;
using var http = new HttpClient(telegram);
var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(configured), token => new TelegramClient(http, token));
await EnqueueAsync(rig, "uno", "due").ConfigureAwait(false);
// Without Telegram the messages wait in the queue: never "sent".
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
Assert.AreEqual(new NotificationSummary(null, 2, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
// Telegram slows us down: the first fails, the second waits for the next pass.
configured = new TelegramSettings(Token, Chat);
telegram.Refuse = "sendMessage";
telegram.RefusalStatus = HttpStatusCode.TooManyRequests;
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
var states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/1/Telegram ha risposto 429: Too Many Requests: retry after 90", states["uno"].Text);
Assert.AreEqual(rig.Clock.UtcNow.AddSeconds(90), states["uno"].Next, "Telegram's own wait, longer than the first pause of a minute.");
Assert.AreEqual("pending/0/", states["due"].Text);
// Back up: what is due leaves, the failed one when its time comes.
telegram.Refuse = null;
Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
rig.Clock.Advance(TimeSpan.FromSeconds(90));
Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false));
states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual(("sent/2/", "sent/1/"), (states["uno"].Text, states["due"].Text));
Assert.AreEqual(2, telegram.Sent.Count(m => m.Chat == Chat));
Assert.AreEqual(new NotificationSummary(rig.Clock.UtcNow, 0, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ARefusalIsNotTriedAgainAndAMessageOlderThanADayIsGivenUp()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var telegram = new FakeTelegram { Refuse = "sendMessage", RefusalStatus = HttpStatusCode.BadRequest };
using var http = new HttpClient(telegram);
var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult<TelegramSettings?>(new TelegramSettings(Token, Chat)),
token => new TelegramClient(http, token));
await EnqueueAsync(rig, "rifiutato").ConfigureAwait(false);
await sender.SendDueAsync(_none).ConfigureAwait(false);
var states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/1/Telegram ha risposto 400: Bad Request: chat not found", states["rifiutato"].Text);
Assert.IsNull(states["rifiutato"].Next, "A refusal is final: the same message would be refused again.");
telegram.Refuse = null;
await EnqueueAsync(rig, "vecchio").ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromHours(25));
Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false));
states = await StatesAsync(rig).ConfigureAwait(false);
Assert.AreEqual("failed/0/Non partito entro un giorno: non lo mando più.", states["vecchio"].Text);
Assert.IsEmpty(telegram.Sent);
var summary = await sender.SummaryAsync(_none).ConfigureAwait(false);
Assert.AreEqual((0, 0, 2), (summary.Pending, summary.Retrying, summary.GaveUp));
// The pauses between attempts grow up to an hour.
Assert.AreEqual("1 2 4 8 16 32 60 60", string.Join(" ", Enumerable.Range(1, 8).Select(a => NotificationSender.Pause(a).TotalMinutes)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task FermaWantsAConfirmationWithinTwoMinutes()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var desk = new FakeDesk();
var commands = new TelegramCommands(desk, clock);
Assert.Contains("/conferma entro 2 minuti", (await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false))!);
Assert.AreEqual(0, desk.Stops);
clock.Advance(TimeSpan.FromSeconds(100));
Assert.AreEqual("fermato", await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false));
Assert.AreEqual(1, desk.Stops);
// Too late, or another command in between: nothing to confirm.
await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(3));
Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false);
await commands.AnswerAsync("/stato", _none).ConfigureAwait(false);
Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!);
Assert.AreEqual(1, desk.Stops);
// The other commands, the bot's name of a group, help, and plain text that is no command.
Assert.AreEqual("stato", await commands.AnswerAsync("/stato@AnubisBot", _none).ConfigureAwait(false));
Assert.AreEqual("posizioni", await commands.AnswerAsync("/POSIZIONI", _none).ConfigureAwait(false));
Assert.AreEqual("oggi", await commands.AnswerAsync(" /oggi grazie", _none).ConfigureAwait(false));
Assert.AreEqual("pausa", await commands.AnswerAsync("/pausa", _none).ConfigureAwait(false));
Assert.AreEqual("riprendi", await commands.AnswerAsync("/riprendi", _none).ConfigureAwait(false));
Assert.AreEqual(TelegramCommands.Help, await commands.AnswerAsync("/aiuto", _none).ConfigureAwait(false));
Assert.StartsWith("Non conosco questo comando.", (await commands.AnswerAsync("/compra BTC", _none).ConfigureAwait(false))!);
Assert.IsNull(await commands.AnswerAsync("ciao", _none).ConfigureAwait(false));
Assert.DoesNotContain("limiti", TelegramCommands.Help.Split('\n')[0]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var telegram = new FakeTelegram();
using var http = new HttpClient(telegram);
var desk = new FakeDesk();
var bot = new TelegramBot(clock, _ => Task.FromResult<TelegramSettings?>(new TelegramSettings(Token, Chat)), token => new TelegramClient(http, token),
new TelegramCommands(desk, clock), NullLogger.Instance);
telegram.Write("999", "/pausa", clock.UtcNow);
telegram.Write(Chat, "/pausa", clock.UtcNow - TimeSpan.FromHours(20));
telegram.Write(Chat, "/stato", clock.UtcNow);
Assert.AreEqual(1, await bot.PollOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual((Chat, "stato"), telegram.Sent.Single());
Assert.AreEqual(0, desk.Pauses, "Neither the stranger's /pausa nor yesterday's.");
// The next read tells Telegram the first three were read.
Assert.AreEqual(0, await bot.PollOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual(4, telegram.LastOffset);
// Without Telegram configured the loop only waits.
var idle = new TelegramBot(clock, _ => Task.FromResult<TelegramSettings?>(null), token => new TelegramClient(http, token), new TelegramCommands(desk, clock),
NullLogger.Instance);
Assert.AreEqual(-1, await idle.PollOnceAsync(_none).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheSignOfLifeCallsTheServiceAndSaysWhenItFails()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
var calls = 0;
var fake = new FakeHttp().On(u => u.Host == "hc.example", _ => FakeHttp.Respond("OK", ++calls == 2 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK));
using var http = fake.Client();
Uri? address = null;
var beat = new Heartbeat(http, clock, _ => Task.FromResult(address), NullLogger.Instance);
Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false), "No address, no call.");
Assert.IsEmpty(fake.Requests);
address = new Uri("https://hc.example/ping/abc");
Assert.IsTrue(await beat.BeatAsync(_none).ConfigureAwait(false));
Assert.AreEqual(clock.UtcNow, beat.LastOk);
clock.Advance(TimeSpan.FromMinutes(1));
Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false));
Assert.AreEqual(("Il servizio ha risposto 503.", clock.UtcNow - TimeSpan.FromMinutes(1)), (beat.LastError, beat.LastOk));
Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid"));
Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x"));
Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid"));
Assert.IsNotNull(Heartbeat.Check("http://8.8.8.8/ping/x"), "A public address in plain http travels in clear.");
Assert.IsNull(Heartbeat.Check("http://10.0.0.5/ping/x"));
Assert.IsNull(Heartbeat.Check("http://[fd00::5]/ping/x"));
Assert.IsNotNull(Heartbeat.Check("ftp://example.com"));
Assert.IsNotNull(Heartbeat.Check("non è un indirizzo"));
}
/// <summary>
/// The acceptance criterion of SPEC 14 with the real server: commands from the phone change the bot's state, the
/// changes reach the phone, a stranger is ignored, and after "Ferma tutto" the phone cannot restart the bot.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheCommandsWorkFromThePhoneThroughTheRealServer()
{
var telegram = new FakeTelegram();
var env = ServerHarness.DockerSqlite();
env["TELEGRAM_BOT_TOKEN"] = Token;
env["TELEGRAM_CHAT_ID"] = Chat;
await using var server = await ServerHarness.StartAsync("docker", env, telegramHttp: telegram).ConfigureAwait(false);
var services = server.Host.Services!;
async Task<string> AskAsync(string text, string chat = Chat)
{
var before = telegram.Sent.Count;
telegram.Write(chat, text, DateTimeOffset.UtcNow);
var until = DateTimeOffset.UtcNow.AddSeconds(20);
while (DateTimeOffset.UtcNow < until)
{
if (telegram.Sent.Skip(before).FirstOrDefault(m => m.Chat == chat && !m.Text.Contains("(da Telegram)", StringComparison.Ordinal)) is { Text: { } answer })
{
return answer;
}
await Task.Delay(50).ConfigureAwait(false);
}
return "(nessuna risposta)";
}
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, _none).ConfigureAwait(false)).Value;
Assert.StartsWith("Bot attivo", await AskAsync("/stato").ConfigureAwait(false));
Assert.AreEqual("Nessuna posizione aperta.", await AskAsync("/posizioni").ConfigureAwait(false));
Assert.AreEqual("Nessun ordine oggi.", await AskAsync("/oggi").ConfigureAwait(false));
Assert.StartsWith("In pausa", await AskAsync("/pausa").ConfigureAwait(false));
Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("Bot in pausa (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
Assert.AreEqual("(nessuna risposta)", await AskAsync("/riprendi", "777").ConfigureAwait(false), "Another chat gets nothing.");
Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false));
Assert.AreEqual("Ripartito dalla pausa.", await AskAsync("/riprendi").ConfigureAwait(false));
Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
Assert.Contains("/conferma", await AskAsync("/ferma").ConfigureAwait(false));
Assert.AreEqual("active", await StateAsync().ConfigureAwait(false));
Assert.StartsWith("«Ferma tutto» fatto", await AskAsync("/conferma").ConfigureAwait(false));
Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
Assert.Contains("riattivalo dalla pagina Rischio", await AskAsync("/riprendi").ConfigureAwait(false));
Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false));
// Every notice has its state, and the Impostazioni page shows the last message that left.
await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("«Ferma tutto» (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false);
var notices = await services.Db.ReadAsync(s => s.QueryAsync("SELECT kind, status FROM notifications", r => r.Text("kind") + "/" + r.Text("status")), _none)
.ConfigureAwait(false);
Assert.Contains("bot_paused/sent", notices);
Assert.Contains("bot_active/sent", notices);
Assert.IsFalse(telegram.Sent.Any(m => m.Text.Contains(Token, StringComparison.Ordinal)));
await server.SignInFirstTimeAsync().ConfigureAwait(false);
var page = await server.TextAsync("/impostazioni").ConfigureAwait(false);
Assert.Contains("Telegram e segnale di vita", page);
Assert.Contains("Token e chat arrivano dalle variabili", page);
Assert.DoesNotContain(Token, page);
}
private static async Task WaitForAsync(Func<bool> condition)
{
var until = DateTimeOffset.UtcNow.AddSeconds(20);
while (!condition())
{
Assert.IsLessThan(until, DateTimeOffset.UtcNow, "Timed out.");
await Task.Delay(50).ConfigureAwait(false);
}
}
private static Task EnqueueAsync(TradingRig rig, params string[] messages) =>
rig.Db.WriteAsync(async s =>
{
foreach (var message in messages)
{
await NotificationSender.EnqueueAsync(s, rig.Clock, "test", message, _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMilliseconds(1));
}
}, _none);
private static async Task<Dictionary<string, (string Text, DateTimeOffset? Next)>> StatesAsync(TradingRig rig) =>
(await rig.QueryAsync("SELECT message, status, attempts, last_error, next_attempt_at FROM notifications",
r => (Message: r.Text("message"), Text: r.Text("status") + "/" + r.Number("attempts") + "/" + r.TextOrNull("last_error"), Next: r.MomentOrNull("next_attempt_at")))
.ConfigureAwait(false)).ToDictionary(x => x.Message, x => (x.Text, x.Next));
private sealed class FakeDesk : ITelegramDesk
{
public int Stops { get; private set; }
public int Pauses { get; private set; }
public Task<string> StatusAsync(CancellationToken cancellationToken) => Task.FromResult("stato");
public Task<string> PositionsAsync(CancellationToken cancellationToken) => Task.FromResult("posizioni");
public Task<string> TodayAsync(CancellationToken cancellationToken) => Task.FromResult("oggi");
public Task<string> PauseAsync(CancellationToken cancellationToken)
{
Pauses++;
return Task.FromResult("pausa");
}
public Task<string> ResumeAsync(CancellationToken cancellationToken) => Task.FromResult("riprendi");
public Task<string> StopAllAsync(CancellationToken cancellationToken)
{
Stops++;
return Task.FromResult("fermato");
}
}
}
/// <summary>
/// A Telegram Bot API on the test's side: messages written by the test come back from getUpdates, sendMessage is
/// recorded, and one method can be made to refuse. getUpdates answers at once (no long wait) after a short pause.
/// </summary>
internal sealed class FakeTelegram : HttpMessageHandler
{
private readonly ConcurrentQueue<(long Id, string Chat, string Text, DateTimeOffset Date)> _updates = new();
private long _nextId = 1;
public List<(string Chat, string Text)> Sent { get; } = [];
public long LastOffset { get; private set; }
/// <summary>The method that fails, with <see cref="RefusalStatus"/>.</summary>
public string? Refuse { get; set; }
public HttpStatusCode RefusalStatus { get; set; } = HttpStatusCode.BadRequest;
public void Write(string chat, string text, DateTimeOffset at) => _updates.Enqueue((Interlocked.Increment(ref _nextId) - 1, chat, text, at));
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var method = request.RequestUri!.AbsolutePath.Split('/')[^1];
using var body = JsonDocument.Parse(request.Content is null ? "{}" : await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
if (method == Refuse)
{
return RefusalStatus == HttpStatusCode.TooManyRequests
? Json(RefusalStatus, """{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 90","parameters":{"retry_after":90}}""")
: Json(RefusalStatus, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}""");
}
switch (method)
{
case "getMe":
return Json(HttpStatusCode.OK, """{"ok":true,"result":{"id":1,"is_bot":true,"username":"AnubisProvaBot"}}""");
case "sendMessage":
lock (Sent)
{
Sent.Add((body.RootElement.GetProperty("chat_id").GetString()!, body.RootElement.GetProperty("text").GetString()!));
}
return Json(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
case "getUpdates":
var offset = body.RootElement.TryGetProperty("offset", out var o) ? o.GetInt64() : 0;
LastOffset = offset;
while (_updates.TryPeek(out var first) && first.Id < offset)
{
_updates.TryDequeue(out _);
}
if (_updates.IsEmpty)
{
await Task.Delay(30, cancellationToken).ConfigureAwait(false);
}
var items = _updates.ToArray().Where(u => u.Id >= offset).Select(u => new
{
update_id = u.Id,
message = new { message_id = u.Id, date = u.Date.ToUnixTimeSeconds(), chat = new { id = long.Parse(u.Chat, System.Globalization.CultureInfo.InvariantCulture) }, text = u.Text },
});
return Json(HttpStatusCode.OK, JsonSerializer.Serialize(new { ok = true, result = items }));
default:
return Json(HttpStatusCode.NotFound, """{"ok":false,"description":"Not Found"}""");
}
}
private static HttpResponseMessage Json(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
+7 -2
View File
@@ -39,7 +39,7 @@ int Test(string engine, string[] extra)
["test", "Anubis.slnx", "--filter", "TestCategory!=LiveDemo", "--logger", "console;verbosity=normal", .. extra], env) ?? 0;
}
// What the remote CI does, run locally: check on SQLite, tests on PostgreSQL, image build.
// What the remote CI does, run locally: check on SQLite, tests on PostgreSQL, image build, the guard drill in the image.
int Ci()
{
var failed = Check();
@@ -70,9 +70,14 @@ int Ci()
}
}
return failed != 0 ? failed : BuildImage("ci");
failed = failed != 0 ? failed : BuildImage("ci");
return failed != 0 ? failed : GuardDrill("ci");
}
// The guard drill inside the image (issue #48): the real guard and the real engine, a sale blocked halfway, the restart.
int GuardDrill(string tag) =>
Step("Esercitazione della guardia nell'immagine", "docker", ["run", "--rm", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "drill"]) ?? 0;
int BuildImage(string tag) =>
Step("Costruzione dell'immagine Docker", "docker",
["build", "-f", "deploy/docker/Dockerfile", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0;