Compare commits
27
Commits
fase-5
..
a66e3439d8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a66e3439d8 | ||
|
|
1aede2fc1c | ||
|
|
78e77818eb | ||
|
|
5f0ce6b172 | ||
|
|
9ee2367693 | ||
|
|
f1ba452aba | ||
|
|
25e71b679f | ||
|
|
9cf386d08b | ||
|
|
6e365673b8 | ||
|
|
32673007a2 | ||
|
|
e561245d4e | ||
|
|
829fbd2eba | ||
|
|
f59eee8632 | ||
|
|
7291f5d15b | ||
|
|
9a4e31aa48 | ||
|
|
1c7205024f | ||
|
|
be6d5fb91f | ||
|
|
2185a0b36b | ||
|
|
3d174931e9 | ||
|
|
9ae107000b | ||
|
|
e96ca70a1a | ||
|
|
84c540786c | ||
|
|
d00dfbd32f | ||
|
|
680cab4bb6 | ||
|
|
41e067e7d1 | ||
|
|
98ee504dab | ||
|
|
e3c9eae65b |
No files matched your search
@@ -3,8 +3,14 @@
|
||||
*.sh text eol=lf
|
||||
.githooks/* text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
# Windows scripts and the instructions in the release zip keep CRLF (ADR 0013).
|
||||
*.cmd text eol=crlf
|
||||
deploy/windows/*.txt text eol=crlf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
*.ttf binary
|
||||
# Recorded API responses stay byte for byte as the source sent them (CRLF in nasdaqtraded.txt included).
|
||||
tests/Anubis.Tests/Fixtures/** -text
|
||||
# The tokenizer of the news classifier stays byte for byte as published (hashes in ADR 0014).
|
||||
src/Anubis/News/Model/*.json -text
|
||||
src/Anubis/News/Model/*.txt -text
|
||||
@@ -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
|
||||
@@ -20,6 +20,7 @@ Dalla radice del repository: `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh
|
||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
||||
- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
||||
- `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea.
|
||||
- `desktop-win` (Fase 10): non ancora disponibile.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||
<Company>BalboSoft</Company>
|
||||
<Product>Anubis</Product>
|
||||
<Version>0.0.1</Version>
|
||||
<Version>0.7.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
|
||||
|
||||
@@ -16,4 +16,9 @@
|
||||
<!-- Desktop secret key on Windows (DPAPI, SPEC 15.6). -->
|
||||
<PackageVersion Include="System.Security.Cryptography.ProtectedData" Version="10.0.14" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Local news classifier (SPEC 4.5, phase 7): the ONNX model and its RoBERTa tokenizer. -->
|
||||
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.31.1" />
|
||||
<PackageVersion Include="Microsoft.ML.Tokenizers" Version="2.0.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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 '"]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
@echo off
|
||||
rem Starts Anubis on this computer (desktop platform) and opens it in the browser. ADR 0013, point 6.
|
||||
cd /d "%~dp0"
|
||||
echo Anubis si avvia su http://localhost:8787
|
||||
echo Questa finestra resta aperta mentre il bot lavora. Per fermarlo premi Ctrl+C.
|
||||
start "" /b cmd /c "timeout /t 8 /nobreak >/dev/null & start http://localhost:8787"
|
||||
"%~dp0Anubis.Server.exe" --platform desktop
|
||||
if errorlevel 1 pause
|
||||
@@ -0,0 +1,44 @@
|
||||
ANUBIS - versione di prova per Windows
|
||||
======================================
|
||||
|
||||
Che cos'è
|
||||
---------
|
||||
Il bot di trading Anubis da far girare sul tuo computer per qualche giorno.
|
||||
Lavora solo in simulazione e sui conti di prova: non può usare soldi veri.
|
||||
Raccoglie da solo i dati per l'analisi (memoria, lavori, chiamate, errori),
|
||||
così chi segue lo sviluppo può capire come si è comportato.
|
||||
|
||||
Cosa serve
|
||||
----------
|
||||
Il runtime ASP.NET Core 10 di Microsoft. Se hai già l'SDK .NET 10, c'è già.
|
||||
Altrimenti lo scarichi da https://dotnet.microsoft.com/download/dotnet/10.0
|
||||
(sezione "ASP.NET Core Runtime", versione per Windows x64).
|
||||
|
||||
Come si avvia
|
||||
-------------
|
||||
1. Estrai lo zip in una cartella qualsiasi, per esempio C:\Anubis.
|
||||
2. Fai doppio clic su "Avvia Anubis.cmd".
|
||||
Si apre una finestra nera: lasciala aperta, il bot lavora lì dentro.
|
||||
Dopo qualche secondo il browser apre http://localhost:8787.
|
||||
3. La prima volta una procedura guidata ti chiede dove tenere i dati e una
|
||||
password. I dati vanno in %APPDATA%\Anubis.
|
||||
4. Per fermarlo premi Ctrl+C nella finestra nera.
|
||||
Chiudere la finestra lo ferma di colpo: funziona, ma il diario lo segnerà
|
||||
come uno spegnimento improvviso.
|
||||
|
||||
Mentre gira
|
||||
-----------
|
||||
Usalo come vuoi. Se il computer va in sospensione, il rapporto lo vedrà come
|
||||
un silenzio: va bene, ma per una prova pulita conviene lasciarlo acceso.
|
||||
|
||||
Come mandare i dati
|
||||
-------------------
|
||||
Quando hai finito (anche con il bot ancora acceso):
|
||||
- fai doppio clic su "Prepara i dati da incollare.cmd": si apre il Blocco
|
||||
note con il rapporto. Seleziona tutto (Ctrl+A), copia (Ctrl+C) e incolla
|
||||
il testo nella chat;
|
||||
- oppure, dall'interfaccia: Diario e sistema, pulsante "Scarica i dati per
|
||||
l'analisi".
|
||||
|
||||
Il rapporto copre tutto ciò che è stato raccolto, fino a 30 giorni. Non
|
||||
contiene chiavi, password né il tuo nome utente.
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
rem Writes the diagnostics report (issue #95) next to this file and opens it, ready to copy. It only reads.
|
||||
cd /d "%~dp0"
|
||||
"%~dp0Anubis.Server.exe" diagnostics --platform desktop --out "%~dp0anubis-diagnostica.md" >nul
|
||||
if errorlevel 1 (
|
||||
echo Non riuscito: avvia prima Anubis almeno una volta.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
start "" notepad "%~dp0anubis-diagnostica.md"
|
||||
@@ -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:
|
||||
|
||||
+2
-2
@@ -128,7 +128,7 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio
|
||||
|---|---|---|---|---|
|
||||
| M1 | `mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis`, licenza Apache-2.0 | confermato | — | https://huggingface.co/mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis |
|
||||
| M2 | Esportazione ONNX pronta nei repository `Xenova/...` | confermato | `Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`: `onnx/model.onnx` (circa 329 MB), `onnx/model_quantized.onnx` (circa 83 MB) e `tokenizer.json`. Revisione da fissare: `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`. Il repository **non dichiara una licenza**: vale quella del modello originale (Apache-2.0), da annotare nell'ADR della Fase 7. | https://huggingface.co/Xenova/distilroberta-finetuned-financial-news-sentiment-analysis |
|
||||
| M3 | 10–20 ms per titolo su CPU | non verificabile | Si misura nella Fase 7, con ONNX Runtime per .NET. | — |
|
||||
| M3 | 10–20 ms per titolo su CPU | misurato | Il 15/11/2026, con ONNX Runtime 1.31.1 per .NET e il modello quantizzato su un solo thread: 23–24 ms per titolo sul PC di sviluppo (test `TheModelReadsTheToneOfFinancialHeadlines`). Con più thread scende, ma Anubis ne usa uno (ADR 0014, punto 8). | — |
|
||||
| M4 | Claude Haiku 5.5: 0,10 $ in ingresso e 0,50 $ in uscita per milione di token (fino a 100.000 token); batch a metà prezzo; non ancora nella panoramica dei modelli | cambiato | Ora **è** nella panoramica, con identificativo `claude-haiku-5-5`. Prezzi confermati. Oltre i 100.000 token costa 0,50 $ e 2,50 $. | https://platform.claude.com/docs/en/about-claude/models/overview · https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
| M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
|
||||
@@ -265,7 +265,7 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
|
||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core`, `SQLitePCLRaw.lib.e_sqlite3`, `SQLitePCLRaw.provider.e_sqlite3` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 (in uso) | Contengono la libreria nativa di SQLite e il suo caricatore. Sono nell'elenco del test dalla Fase 1. |
|
||||
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | 8 | — |
|
||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 | — |
|
||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 (in uso) | Nell'elenco del test dalla Fase 7. |
|
||||
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||
|
||||
## Immagini Docker
|
||||
|
||||
+21
-20
@@ -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 nel container `anubis-prova`, ripartita da zero il 12/11/2026 alle 21:02 dopo uno spegnimento improvviso del PC; 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
|
||||
|
||||
@@ -212,7 +212,8 @@ Le notizie usate per evitare guai, mai per comprare.
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata
|
||||
- [ ] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013)
|
||||
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013)
|
||||
- [ ] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
|
||||
- [ ] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
|
||||
- [ ] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
|
||||
@@ -222,7 +223,7 @@ Le notizie usate per evitare guai, mai per comprare.
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate
|
||||
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013)
|
||||
- [ ] Su un archivio di notizie registrate la deduplica e il collegamento superano i test
|
||||
- [ ] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (test dedicato)
|
||||
- [ ] Senza chiave del modello linguistico tutto funziona
|
||||
|
||||
+34
-7
@@ -1,10 +1,10 @@
|
||||
# Stato del progetto
|
||||
|
||||
Aggiornato: 2026-11-11
|
||||
Aggiornato: 2026-11-15
|
||||
|
||||
## 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 7 — Notizie: in corso.** La Fase 6 è completata. La sua prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto. 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,24 @@ 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.
|
||||
- **Fase 7, in corso** (ADR 0013):
|
||||
- Raccolta dei dati per l'analisi (#95). Ogni 5 minuti, e a ogni avvio, il bot scrive una fotografia del processo in `diagnostic_samples`: memoria, GC, thread, handle, CPU, eccezioni, dimensione del database, avvisi ed errori dei registri, chiamate HTTP in uscita per destinazione con le durate. Ogni esecuzione di ogni lavoro va in `job_runs`. Si tiene tutto per 30 giorni.
|
||||
- Il rapporto da incollare, in Markdown fino a 60 KB e senza segreti, si ottiene in tre modi: dal pulsante «Scarica i dati per l'analisi» in Diario e sistema, da `/api/diagnostica.md` e da `anubis diagnostics`.
|
||||
- Release di prova per Windows con `tasks release-win`: uno zip con il server, `Avvia Anubis.cmd`, `Prepara i dati da incollare.cmd` e un `LEGGIMI.txt`.
|
||||
- Raccolta delle notizie (#56, ADR 0014, branch `fase-7`). Il lavoro "notizie" legge ogni 2 minuti le 14 fonti di SPEC 4.4. Le richieste sono condizionate e una fonte che sbaglia aspetta sempre di più, fino a un'ora. Poi:
|
||||
- i feed si leggono senza DTD né entità;
|
||||
- gli articoli doppi si tolgono per indirizzo e le riprese dello stesso fatto si raggruppano in una storia, contando le fonti indipendenti;
|
||||
- ogni storia si collega a strumenti, classi o mercato: simboli, ticker, nomi delle società e delle monete, temi.
|
||||
- Primo giudizio locale (#57): casi gravi trovati con parole chiave in inglese e in italiano, tono in cinque gradi, importanza da 1 a 4. Ogni articolo e ogni storia lo conservano.
|
||||
- Classificatore ONNX (#57, ADR 0014 punto 8): il modello Xenova quantizzato, con revisione e hash fissati, scaricato dal bot nella cartella `models` al primo giro delle notizie. Il tokenizzatore sta nella DLL e dà gli stessi identificativi dell'originale. 23–24 ms per titolo su un thread. Senza il modello giudicano le sole parole chiave.
|
||||
|
||||
## In corso
|
||||
|
||||
@@ -84,12 +102,20 @@ 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. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55.
|
||||
2. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56) e primo giudizio con il classificatore (#57) sono fatti. Restano:
|
||||
- l'analista facoltativo (#58);
|
||||
- lo stato per strumento (#59);
|
||||
- la schermata (#60).
|
||||
3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
|
||||
|
||||
## 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 prova nel container `anubis-prova` è chiusa (ADR 0013). I compiti programmati che la sorvegliavano sono spenti; il container si può fermare con `docker stop anubis-prova`.
|
||||
- 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 +123,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 +135,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 |
|
||||
| Far girare la release `v0.7.0` e incollare il rapporto in chat | Ora, per il tempo che vuoi | La prova di durata (#55) resta aperta |
|
||||
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria 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 |
|
||||
|
||||
@@ -90,6 +90,19 @@ 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.
|
||||
- Docker Desktop non si avvia dalla shell dell'app Claude (`Start-Process`, `docker desktop start`): il processo resta legato all'app e si chiude con lei quando si aggiorna o si chiude. Il 12 novembre 2026 è successo durante la prova di durata. Se va avviato da lì, si passa da WMI, che lo fa partire da un servizio di Windows:
|
||||
`Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='"C:\Program Files\Docker\Docker\Docker Desktop.exe"'}`
|
||||
- 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.
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,84 @@
|
||||
# 0013 — Raccolta dei dati per l'analisi al posto della prova di durata in casa
|
||||
|
||||
Data: 2026-11-14 · Stato: accettata · Precisa il criterio della prova di durata (SPEC 17, Fasi 6 e 7, issue #55) e aggiunge l'issue #95, senza aggiungere componenti esterni
|
||||
|
||||
## Contesto
|
||||
|
||||
La prova di durata di 48 ore della Fase 6 girava nel container `anubis-prova` di questo PC. In tre giorni il computer l'ha interrotta più volte, mai Anubis:
|
||||
- uno spegnimento improvviso del PC;
|
||||
- Docker chiuso insieme all'app Claude durante un suo aggiornamento;
|
||||
- un blocco del motore di Docker durato 18 ore.
|
||||
|
||||
Il 14 novembre 2026 l'utente ha scelto un'altra strada. Eseguirà l'ultima release pubblicata su Gitea per il tempo che vuole, sul suo computer e con il suo uso normale. Poi incollerà in chat un rapporto, da cui si analizza come si è comportato il bot. Serve quindi una raccolta di dati più ricca di quella che il rapporto `soak` legge dai soli registri del trading, e serve una release da scaricare.
|
||||
|
||||
## Decisione
|
||||
|
||||
**1. La verifica della prova di durata passa al rapporto della release.**
|
||||
- Il criterio della Fase 7 "Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate" resta com'è.
|
||||
- Il rapporto non viene più dal container di prova. È quello che l'utente incolla dopo aver fatto girare la release, salvato in `docs/diagnostica/`.
|
||||
- Il rapporto contiene gli stessi controlli di `anubis soak` (sezione «Controlli del lavoro»). Uno spegnimento voluto dall'utente compare come ✗ della continuità e va spiegato, non è un difetto.
|
||||
- La prova nel container `anubis-prova` è chiusa. Il suo primo tratto resta in `artifacts/prova-48h/primo-tratto/`. I due compiti programmati che la sorvegliavano sono spenti o cancellati.
|
||||
|
||||
**2. Che cosa si raccoglie (issue #95).** Tutto resta nel database del bot e niente esce dal computer.
|
||||
- Ogni 5 minuti, e una volta a ogni avvio, una fotografia del processo nella tabella `diagnostic_samples`:
|
||||
- memoria (privata, di lavoro, gestita, impegnata dal GC);
|
||||
- raccolte del GC per generazione e tempo di pausa;
|
||||
- thread, handle e coda del pool;
|
||||
- tempo di processore e contese sui lock;
|
||||
- eccezioni lanciate;
|
||||
- dimensione del database;
|
||||
- righe di avviso e di errore dei registri tecnici;
|
||||
- chiamate HTTP in uscita.
|
||||
- I contatori sono totali dall'avvio del processo: il rapporto fa le differenze. Il lavoro "diagnostica" non ha recupero: un campione perso mentre il bot era spento non si rifà.
|
||||
- Ogni esecuzione di ogni lavoro pianificato va in `job_runs`, con scadenza, inizio, fine, esito ed errore. La tabella `jobs` tiene solo l'ultima esecuzione.
|
||||
- Le chiamate HTTP si misurano ascoltando lo strumento che .NET già pubblica per ogni richiesta in uscita (`System.Net.Http`, `http.client.request.duration`) con un `MeterListener`. Non serve nessun pacchetto e non cambia nessun client.
|
||||
- Si tengono per destinazione: numero, esiti, fallite.
|
||||
- Le durate stanno in fasce fisse, così i tratti si sommano senza tenere ogni chiamata.
|
||||
- Si contano anche le eccezioni di primo lancio. Molte sono normali, ma un conto che sale sempre indica un ciclo che fallisce di continuo.
|
||||
- Le due tabelle tengono 30 giorni. La pulizia gira una volta al giorno dentro lo stesso lavoro.
|
||||
- Nella modalità dimostrativa non si raccoglie nulla.
|
||||
|
||||
**3. Il rapporto.**
|
||||
- Si ottiene in tre modi:
|
||||
- dal pulsante «Scarica i dati per l'analisi» in Diario e sistema;
|
||||
- da `GET /api/diagnostica.md?ore=N`, che richiede l'accesso;
|
||||
- dal comando `anubis diagnostics [--hours N | --from … --to …] [--out file.md]`, che legge soltanto e quindi gira anche mentre il bot lavora.
|
||||
- Senza periodo indicato copre tutto ciò che è stato raccolto, fino a 30 giorni.
|
||||
- È in Markdown e pesa al massimo 60 KB. Se serve, si tagliano per prime le righe della tabella delle risorse.
|
||||
- Le sezioni:
|
||||
- **In breve**: i segnali trovati da regole fisse, per esempio memoria o handle che crescono, lavori falliti o saltati, chiamate che falliscono o sono lente, errori nei registri, silenzi a processo acceso, ripartenze e spegnimenti;
|
||||
- **Installazione**: versione, commit, sistema, runtime e motore del database;
|
||||
- **Controlli del lavoro**: quelli di `soak`;
|
||||
- **Avvii, spegnimenti e silenzi**;
|
||||
- **Lavori pianificati**: esecuzioni, fallite, ritardi e durate;
|
||||
- **Chiamate esterne**: per destinazione, con mediana, 95° percentile e massimo;
|
||||
- **Registri tecnici**: avvisi ed errori raggruppati per messaggio, con numeri e id tolti;
|
||||
- **Risorse nel tempo**: le pendenze dopo la prima mezz'ora e una tabella di al massimo 48 righe.
|
||||
|
||||
**4. Niente di riservato nel rapporto.**
|
||||
- Tutto il testo passa dal `Redactor`.
|
||||
- La cartella dell'utente diventa `%USERPROFILE%` e il suo nome nei percorsi diventa `‹utente›`.
|
||||
- Delle variabili `ANUBIS_*` si mostra il valore solo se il nome non può contenere un segreto: niente `KEY`, `SECRET`, `PASS`, `TOKEN` o `URL`.
|
||||
- Il rapporto lascia il computer solo quando l'utente lo incolla.
|
||||
|
||||
**5. Un tipo di colonna in più: `{long}`.**
|
||||
- I byte di memoria e i contatori di una lunga esecuzione superano 2^31. SQLite in modalità `STRICT` non accetta `BIGINT`.
|
||||
- Il segnaposto `{long}` diventa `BIGINT` su PostgreSQL e `INTEGER` su SQLite, che è già a 64 bit.
|
||||
- `BIGINT` scritto a mano non è più ammesso nelle migrazioni.
|
||||
|
||||
**6. Release di prova su Gitea, prima della Fase 10.**
|
||||
- Prima che esista l'installatore della Fase 10, una release `v0.N.0` porta uno zip per Windows. Dentro ci sono:
|
||||
- il server, che richiede il runtime ASP.NET Core 10;
|
||||
- `Avvia Anubis.cmd`;
|
||||
- un `LEGGIMI.txt` in italiano.
|
||||
- Il numero di versione segue la fase in corso: `0.7.0` durante la Fase 7.
|
||||
- Lo zip usa la piattaforma desktop e la cartella dei dati dell'utente (`%APPDATA%\Anubis`). Il primo avvio apre la procedura guidata.
|
||||
- Mancano le chiavi dei conti reali e non c'è modo di abilitarli (SPEC 2.2).
|
||||
- L'immagine Docker della stessa versione si costruisce dal tag con `tasks build`. La sua pubblicazione nel registro aspetta il `REGISTRY_TOKEN` (Fase 9).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- La Fase 7 non aspetta più una prova in casa: il rapporto arriva quando l'utente lo incolla.
|
||||
- Fino ad allora l'issue #55 resta aperta.
|
||||
- Le analisi future partono dal rapporto e da tre tabelle: `diagnostic_samples`, `job_runs` e `absences`.
|
||||
- Il costo è una riga ogni 5 minuti e una per esecuzione di lavoro. A un mese sono circa 9.000 campioni e qualche decina di migliaia di esecuzioni, una frazione del database.
|
||||
@@ -0,0 +1,87 @@
|
||||
# 0014 — Scelte della Fase 7: raccolta e collegamento delle notizie
|
||||
|
||||
Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5 e 10.2 (punti 1–4) per le issue #56 e #57. Usa solo i componenti già ammessi dall'ADR 0004
|
||||
|
||||
## Contesto
|
||||
|
||||
La Fase 7 porta le notizie dentro Anubis. Il primo pezzo (#56) le raccoglie dalle fonti di SPEC 4.4, le pulisce, raggruppa gli articoli che raccontano lo stesso fatto e li collega agli strumenti, alla classe o al mercato. La specifica dice che cosa fare, ma non fissa alcune soglie e alcune scelte pratiche: sono qui.
|
||||
|
||||
## Decisione
|
||||
|
||||
**1. Lettura dei feed.**
|
||||
- RSS 2.0, RSS 1.0 (RDF) e Atom si leggono con il lettore XML di .NET, senza pacchetti.
|
||||
- Il lettore ignora le DTD e non apre mai file né indirizzi citati dal documento. Le entità dichiarate nel feed non vengono espanse, per cui un feed ostile non legge il disco e non gonfia la memoria. Lo prova il file `hostile.xml` dei test.
|
||||
- Un documento si legge fino a 5 MB, con un tempo massimo di 30 secondi. Titoli e riassunti perdono i tag HTML e le entità, e il riassunto si ferma a 600 caratteri.
|
||||
- Le date si leggono nei formati che le fonti usano davvero: RFC 822 con `GMT`, `Z`, `+0100` o i fusi americani con nome, e ISO 8601. Una data senza fuso si legge come UTC. Un articolo senza data prende l'ora in cui è stato visto.
|
||||
- Il testo delle notizie è un dato, mai un'istruzione (SPEC 10.4): qui si salva e basta.
|
||||
|
||||
**2. Cortesia verso le fonti.**
|
||||
- Il giro delle fonti è il lavoro pianificato "notizie" e gira ogni 2 minuti.
|
||||
- Ogni fonte riceve una richiesta condizionata (`If-None-Match`, `If-Modified-Since`), e un "non modificato" vale come riuscita. Tra una fonte e l'altra passa un secondo.
|
||||
- Una fonte che fallisce si riprova dopo 2, 4, 8… minuti, mai oltre un'ora. L'errore resta scritto sulla fonte, e la schermata Notizie (#60) lo mostrerà.
|
||||
- Le fonti iniziali sono le 14 di SPEC 4.4 che rispondevano il 9 ottobre 2026. Si scrivono solo al primo avvio: poi l'elenco è dell'utente, e una fonte tolta resta tolta.
|
||||
- Sono affidabili, come dice SPEC 10.2: Federal Reserve, BCE, SEC, CNBC, MarketWatch, CoinDesk, Il Sole 24 Ore, ANSA. Le altre sono aggregatori o testate di settore.
|
||||
- La SEC chiede ai programmi automatici di indicare un contatto. Anubis manda solo `Anubis/<versione>` e non usa mai l'indirizzo dell'utente senza chiederlo. Se la SEC rifiuta, la fonte va in attesa come le altre. Un campo per il contatto arriverà con le Impostazioni delle notizie (#60).
|
||||
|
||||
**3. Doppioni e storie.**
|
||||
- Lo stesso articolo ha un solo indirizzo canonico. Si tolgono `www.`, il frammento, le barre doppie e finali, e i parametri di tracciamento (`utm_*`, `fbclid`, `gclid`, `mod`, `ref`…). Gli altri parametri si ordinano. Un articolo con un indirizzo già visto è un doppione e non si salva.
|
||||
- Due titoli raccontano lo stesso fatto quando le loro parole significative si somigliano almeno al 50% (indice di Jaccard). Vale anche quando il titolo più corto, di almeno 4 parole, sta per l'80% dentro l'altro. Due titoli di meno di 3 parole devono essere uguali.
|
||||
- Una storia raccoglie gli articoli simili usciti entro 48 ore. Gli articoli più vecchi di 3 giorni non entrano: sono storia, non notizie.
|
||||
- Le fonti indipendenti si contano per dominio registrabile: due feed dello stesso editore valgono uno. La storia è "affidabile" quando almeno una fonte è affidabile. Una storia con una sola fonte non affidabile aspetta una seconda fonte prima di contare (SPEC 10.2, punto 2). Il conto resta nella storia per gli usi successivi (#59).
|
||||
|
||||
**4. Collegamento.** Una storia si collega a strumenti, classi o mercato in quest'ordine di forza:
|
||||
1. i simboli che la fonte stessa indica;
|
||||
2. i cashtag (`$NVDA`) e i riferimenti di borsa (`(NASDAQ: TSLA)`);
|
||||
3. le sigle delle crypto scritte in maiuscolo (`BTC`, `ETH`), solo per le monete del catalogo;
|
||||
4. i nomi delle società, tolti "Inc.", "Corporation", "Common Stock" e simili, scritti con la maiuscola. "apple pie" non è Apple;
|
||||
5. i nomi delle monete (Bitcoin, Ethereum, Solana…);
|
||||
6. i temi: banche centrali, inflazione, tassi e dazi vanno al mercato; criptovalute e stablecoin alla classe crypto; Wall Street e i grandi indici alla classe azioni. Un riferimento di borsa come `(NASDAQ: AAPL)` non vale come tema "Nasdaq".
|
||||
|
||||
Inoltre:
|
||||
- Se non si trova niente, vale l'argomento della fonte: il feed della Fed parla di mercato, CoinDesk di crypto.
|
||||
- Un nome che è anche una parola comune (Target, Block, Gap, Visa…) collega solo con il suo ticker.
|
||||
- I fondi (ETF) non si collegano per nome.
|
||||
- Il dizionario dei nomi si ricostruisce dal catalogo degli strumenti al più ogni ora.
|
||||
|
||||
**5. Lingua.** La lingua viene dal feed (`<language>`, `xml:lang`). Se manca, una stima semplice distingue l'italiano dall'inglese. Serve al classificatore (#57), che lavora sull'inglese, e all'analista (#58).
|
||||
|
||||
**6. Database.**
|
||||
- Quattro tabelle, uguali sui due motori (migrazione `0008_news.sql`): `news_sources`, `news_stories`, `news_items`, `news_links`.
|
||||
- L'indirizzo canonico è unico.
|
||||
- Un collegamento è unico per storia, ambito e bersaglio.
|
||||
|
||||
**7. Primo giudizio senza modello linguistico (#57).**
|
||||
- Ogni articolo ha:
|
||||
- un tono da −1 a +1, dato solo per i titoli in inglese;
|
||||
- un eventuale caso grave;
|
||||
- un'importanza da 1 a 4.
|
||||
- Ogni storia tiene il tono medio, il caso grave e l'importanza più alta dei suoi articoli.
|
||||
- I casi gravi si trovano con frasi intere in inglese e in italiano, nell'ordine di 10.2: attacco informatico, sospensione, frode, fallimento, indagine, revoca dalla quotazione. "hackathon" non è "hack".
|
||||
- Le negazioni ("smentisce la frode") contano come il caso. È la scelta prudente: una restrizione in più, mai una in meno.
|
||||
- L'importanza si assegna così: 4 ai casi gravi, 3 a un tono fino a −0,6, 2 agli articoli collegati a uno strumento, 1 al resto. Il 3 per un evento in calendario arriva con #59; il 5 lo dà solo il modello linguistico (#58).
|
||||
|
||||
**8. Classificatore locale (#57).**
|
||||
- Il modello è `onnx/model_quantized.onnx` di `Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`:
|
||||
- revisione `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`;
|
||||
- 82.763.251 byte, SHA-256 `8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec`, lo stesso pubblicato da Hugging Face;
|
||||
- è la versione quantizzata, quattro volte più piccola di `model.onnx`.
|
||||
- Il repository Xenova non dichiara una licenza. Vale quella del modello originale, `mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis`: Apache-2.0.
|
||||
- Il modello non sta nel repository né nello zip. Al primo giro delle notizie, il bot lo scarica in sottofondo nella cartella `models` dei dati, dall'indirizzo con la revisione fissata, e controlla dimensione e hash. Un file che non corrisponde non si usa mai.
|
||||
- Se il download o l'apertura falliscono, si riprova dopo 6 ore. Intanto le notizie arrivano lo stesso e giudicano le sole parole chiave (SPEC 10.3: tutto funziona senza modello).
|
||||
- Nella modalità dimostrativa e con i dati di mercato spenti non si scarica niente.
|
||||
- Il tokenizzatore sta dentro la DLL (`src/Anubis/News/Model/`, hash nel `README.md` della cartella). È il BPE a livello di byte di RoBERTa, letto con `BpeTokenizer` di `Microsoft.ML.Tokenizers` e il pre-tokenizzatore di RoBERTa.
|
||||
- `CodeGenTokenizer.Create` non va bene: aggiunge identificativi per le sequenze di spazi che RoBERTa non ha, e il modello li rifiuta.
|
||||
- Nessun token speciale viene riconosciuto nel testo: un titolo che contiene `<s>` o `<mask>` resta testo.
|
||||
- Il testo si tronca a 128 token: un titolo ci sta sempre.
|
||||
- La prova che gli identificativi coincidono con l'originale: il test li confronta, su 14 titoli con accenti, simboli e spazi, con quelli di una copia indipendente del codificatore di GPT-2 sugli stessi file. "Hello world" dà il noto `0 31414 232 2`.
|
||||
- Il modello gira su un solo thread, per non togliere il processore al motore di trading: 23–24 ms per titolo su questo PC.
|
||||
- È un po' sopra i 10–20 ms di SPEC 4.5, che non dice su quanti thread.
|
||||
- Con un giro ogni 2 minuti e qualche decina di titoli nuovi l'ora, il costo resta trascurabile.
|
||||
- Il test sul modello vero gira dove il file è già scaricato (`ANUBIS_TEST_MODEL_DIR`). In CI risulta ignorato: i test non scaricano 83 MB a ogni esecuzione.
|
||||
- Lo zip per Windows porta in più la libreria nativa di ONNX Runtime per win-x64 (`onnxruntime.dll`, 17 MB) e passa da 3,4 a 10,7 MB. Per questo `Anubis` e `Anubis.Server` dichiarano `win-x64` tra i loro runtime: il file di blocco contiene anche i pacchetti nativi di Windows, e `tasks release-win` non lo modifica più. Che l'immagine Docker carichi la libreria per linux-x64 (SPEC 3, distribuzione Docker) non è ancora provato: si controlla con il primo avvio del classificatore in Docker.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le notizie si accumulano già nel database con il loro primo giudizio. Analista, stato per strumento e schermata arrivano con le issue #58–#60.
|
||||
- Le soglie di somiglianza e di età sono costanti nel codice. Se l'uso reale mostra storie unite o divise male, si cambiano con un nuovo ADR e un test che lo mostra.
|
||||
- I test leggono un archivio sintetico nel formato reale di ogni fonte (`tests/Anubis.Tests/Fixtures/news/`). Non chiamano mai internet.
|
||||
@@ -2,6 +2,11 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
@@ -23,6 +28,14 @@
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
@@ -50,10 +63,17 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
@@ -69,6 +89,24 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -2,6 +2,11 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
@@ -10,17 +15,12 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
@@ -50,10 +50,17 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
@@ -69,14 +76,29 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
|
||||
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
|
||||
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
|
||||
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
|
||||
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
|
||||
+130
-10
@@ -4,7 +4,9 @@ using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Diagnostics;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Supervision;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Server;
|
||||
@@ -38,7 +40,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 +57,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 +71,23 @@ internal sealed partial class AnubisHost(
|
||||
private CancellationTokenSource? _schedulerStop;
|
||||
private MarketDataService? _market;
|
||||
private TradingService? _trading;
|
||||
private TelegramServices? _telegram;
|
||||
private Laboratory? _lab;
|
||||
private DiagnosticSampler? _sampler;
|
||||
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;
|
||||
|
||||
@@ -146,6 +158,10 @@ internal sealed partial class AnubisHost(
|
||||
LogDemo(logger, Config.Data.Root);
|
||||
}
|
||||
|
||||
// From the first moment: every exception and every outbound call of the process is counted (issue #95).
|
||||
ExceptionCounter.Start();
|
||||
_ = HttpCallMeter.Shared;
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
Task wake;
|
||||
@@ -176,6 +192,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 +235,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 +257,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 +296,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 +314,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 +349,41 @@ 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);
|
||||
|
||||
// The data for the analysis of a long run (issue #95, ADR 0013); the demo has nothing to analyse.
|
||||
_sampler = options.Demo ? null : new DiagnosticSampler(_db, clock, HttpCallMeter.Shared);
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
if (_sampler is not null)
|
||||
{
|
||||
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogStepFailed(logger, ex);
|
||||
}
|
||||
|
||||
StartScheduler(scheduler, backups, lastDues);
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
@@ -431,14 +502,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(_sampler is { } sampler ? new[] { sampler.Job() } : []).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 +518,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 +526,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 +538,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 +573,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 +615,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);
|
||||
@@ -536,6 +632,12 @@ internal sealed partial class AnubisHost(
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Every run, for the lateness and the durations in the diagnostics report (issue #95).
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO job_runs (id, job, due_at, started_at, finished_at, outcome, missed, error, created_at) VALUES (@id, @n, @d, @s, @f, @o, @m, @e, @f)",
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("m", run.Missed), ("e", run.Error is null ? null : Redactor.Redact(run.Error))).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
@@ -571,6 +673,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 +686,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 +727,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);
|
||||
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -5,86 +5,159 @@
|
||||
|
||||
<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>
|
||||
<a class="btn" href="/api/diagnostica.md" download><Icon Name="download" Size="18" />Scarica i dati per l'analisi</a>
|
||||
<p class="note">I dati per l'analisi sono un testo da incollare a chi segue lo sviluppo: risorse, lavori, chiamate ed errori, senza chiavi né password.</p>
|
||||
</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>
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Diagnostics;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>The diagnostics report (issue #95, ADR 0013) as the command, the download and the Diario button make it.</summary>
|
||||
internal static class DiagnosticsExport
|
||||
{
|
||||
/// <summary>Thirty days: as long as the samples are kept.</summary>
|
||||
public const double MaxHours = 720;
|
||||
|
||||
/// <summary>
|
||||
/// The report over the last <paramref name="hours"/> hours up to <paramref name="to"/>, or from
|
||||
/// <paramref name="from"/>; without either, from the first sample kept, so a run of a release is covered whole.
|
||||
/// </summary>
|
||||
public static async Task<string> BuildAsync(Database db, StartupConfig config, IReadOnlyDictionary<string, string?> environment, DateTimeOffset now,
|
||||
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
|
||||
{
|
||||
var end = to ?? now;
|
||||
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours ?? MaxHours, 0.25, MaxHours));
|
||||
if (from is null && hours is null)
|
||||
{
|
||||
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(taken_at) AS t FROM diagnostic_samples", r => r.MomentOrNull("t")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (first is { } f && f > start && f < end)
|
||||
{
|
||||
start = f;
|
||||
}
|
||||
}
|
||||
|
||||
var request = new DiagnosticsRequest(start, end, config.TimeZone)
|
||||
{
|
||||
LogsFolder = config.Data.Logs,
|
||||
Setup = Setup(config, environment),
|
||||
GeneratedAt = now,
|
||||
};
|
||||
return await DiagnosticsReporter.BuildAsync(db, request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The startup settings, and which ANUBIS_ variables are set: values only for those that cannot hold a secret.</summary>
|
||||
internal static IReadOnlyList<KeyValuePair<string, string>> Setup(StartupConfig config, IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
var lines = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new("Piattaforma", config.Platform.ToString().ToLowerInvariant()),
|
||||
new("Database", config.Db?.Describe() ?? "non configurato"),
|
||||
new("Cartella dei dati", config.Data.Root),
|
||||
new("Raggiungibile da altri computer", config.AllowNetwork ? "sì" : "no"),
|
||||
new("Ordini reali consentiti", config.AllowLive ? "sì" : "no"),
|
||||
};
|
||||
var variables = environment
|
||||
.Where(e => e.Key.StartsWith(AnubisInfo.EnvironmentPrefix, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(e.Value))
|
||||
.OrderBy(e => e.Key, StringComparer.Ordinal)
|
||||
.Select(e => e.Key + (Secretive(e.Key) ? "" : "=" + e.Value))
|
||||
.ToList();
|
||||
lines.Add(new("Variabili impostate", variables.Count == 0 ? "nessuna" : string.Join(", ", variables)));
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static readonly string[] _secretWords = ["KEY", "SECRET", "PASS", "TOKEN", "URL"];
|
||||
|
||||
private static bool Secretive(string name) => _secretWords.Any(word => name.Contains(word, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public static IReadOnlyDictionary<string, string?> ProcessEnvironment() =>
|
||||
Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "anubis diagnostics": the report to paste back after a long run of a release (issue #95, ADR 0013). It only reads,
|
||||
/// so it runs while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
|
||||
/// </summary>
|
||||
internal static class DiagnosticsCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis diagnostics [--hours 72] [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--out file.md]\n" +
|
||||
" senza --hours né --from copre tutto ciò che è stato raccolto (al massimo 30 giorni).\n" +
|
||||
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
|
||||
/// <summary>0 when the report was made, 1 when it could not be, 2 for the usage.</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 ??= DiagnosticsExport.ProcessEnvironment();
|
||||
try
|
||||
{
|
||||
double? hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : null;
|
||||
DateTimeOffset? to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
|
||||
DateTimeOffset? from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : null;
|
||||
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 text = await DiagnosticsExport.BuildAsync(db, config, environment, clock.UtcNow, hours, from, to, CancellationToken.None).ConfigureAwait(false);
|
||||
if (own.TryGetValue("--out", out var file))
|
||||
{
|
||||
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await output.WriteAsync(text).ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -174,6 +174,24 @@ 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 data collected for the analysis of a long run, as one Markdown report to paste (issue #95, ADR 0013).
|
||||
api.MapGet("/diagnostica.md", async (AnubisHost host, ShellData shell, IClock clock, double? ore, CancellationToken ct) =>
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var text = await DiagnosticsExport.BuildAsync(host.Services!.Db, host.Config, DiagnosticsExport.ProcessEnvironment(), now, ore, null, null, ct).ConfigureAwait(false);
|
||||
var day = TimeZoneInfo.ConvertTime(now, shell.Zone).ToString("yyyy-MM-dd-HHmm", System.Globalization.CultureInfo.InvariantCulture);
|
||||
return Results.File(System.Text.Encoding.UTF8.GetBytes(text), "text/markdown; charset=utf-8", $"anubis-diagnostica-{day}.md");
|
||||
});
|
||||
|
||||
// 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 +213,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 +237,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 +299,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 +324,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 +340,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 +351,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
@@ -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";
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Diagnostics;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
@@ -33,6 +34,7 @@ internal sealed class JsonLogProvider : ILoggerProvider
|
||||
|
||||
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
|
||||
{
|
||||
LogCounter.Record(level);
|
||||
var now = _clock.UtcNow;
|
||||
using var buffer = new MemoryStream();
|
||||
using (var json = new Utf8JsonWriter(buffer))
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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()}.";
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,18 @@ 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);
|
||||
}
|
||||
|
||||
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
|
||||
if (args.Length >= 1 && args[0] == "diagnostics")
|
||||
{
|
||||
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
@@ -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)
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -2,6 +2,11 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
@@ -10,6 +15,14 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
@@ -37,10 +50,17 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
@@ -56,6 +76,24 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
@@ -68,6 +106,22 @@
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
@@ -23,6 +28,14 @@
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
@@ -50,10 +63,17 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
@@ -69,6 +89,24 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis</RootNamespace>
|
||||
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
|
||||
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
|
||||
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
<PackageReference Include="System.Security.Cryptography.ProtectedData" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
|
||||
<PackageReference Include="Microsoft.ML.Tokenizers" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
|
||||
<!-- The tokenizer of the news classifier (ADR 0014); the ONNX model is downloaded at the first start. -->
|
||||
<EmbeddedResource Include="News\Model\*.json;News\Model\*.txt" LogicalName="Anubis.News.Model.%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
||||
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
|
||||
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Anubis;
|
||||
|
||||
/// <summary>Names fixed by ADR 0001, shared by every part of the bot.</summary>
|
||||
@@ -15,4 +17,10 @@ public static class AnubisInfo
|
||||
/// <summary>Version of the running build, for example "0.0.1".</summary>
|
||||
public static string Version { get; } =
|
||||
typeof(AnubisInfo).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
|
||||
/// <summary>The commit the build came from (the SDK appends it to the informational version), when known.</summary>
|
||||
public static string? Commit { get; } =
|
||||
typeof(AnubisInfo).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion is { } full && full.IndexOf('+', StringComparison.Ordinal) is var plus and >= 0
|
||||
? full[(plus + 1)..][..Math.Min(12, full.Length - plus - 1)]
|
||||
: null;
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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>();
|
||||
|
||||
|
||||
@@ -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");
|
||||
@@ -82,6 +82,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_universes = new UniverseStore(db, clock);
|
||||
_builder = new UniverseBuilder(db, clock);
|
||||
_states = new SourceStateStore(db, clock);
|
||||
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") };
|
||||
}
|
||||
|
||||
public OkxClient Okx { get; }
|
||||
@@ -92,6 +93,9 @@ public sealed partial class MarketDataService : IDisposable
|
||||
|
||||
public StoredMarketCalendar UsCalendar { get; }
|
||||
|
||||
/// <summary>The news sources of SPEC 4.4, read every 2 minutes on the same connection pool (issue #56).</summary>
|
||||
public News.NewsCollector News { get; }
|
||||
|
||||
/// <summary>True while the live crypto feed is connected.</summary>
|
||||
public bool LiveConnected => _okxCollector.Connected;
|
||||
|
||||
@@ -105,21 +109,23 @@ 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) },
|
||||
News.Job(),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
@@ -130,7 +136,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()
|
||||
@@ -146,6 +153,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
public void Dispose()
|
||||
{
|
||||
_work.Dispose();
|
||||
News.Dispose();
|
||||
_http.Dispose();
|
||||
}
|
||||
|
||||
@@ -419,7 +427,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 +500,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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -91,6 +91,9 @@ public static class DbValues
|
||||
("bool", DbEngine.Sqlite) => "INTEGER",
|
||||
("bytes", DbEngine.Postgres) => "BYTEA",
|
||||
("bytes", DbEngine.Sqlite) => "BLOB",
|
||||
// A whole number beyond 2^31 (bytes of memory, counters of a long run): SQLite's INTEGER is already 64 bits.
|
||||
("long", DbEngine.Postgres) => "BIGINT",
|
||||
("long", DbEngine.Sqlite) => "INTEGER",
|
||||
("float", DbEngine.Postgres) => "DOUBLE PRECISION",
|
||||
("float", DbEngine.Sqlite) => "REAL",
|
||||
("strict", DbEngine.Postgres) => "",
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,50 @@
|
||||
-- Data collected for the analysis of a long run (issue #95, ADR 0013). Both tables are kept for 30 days.
|
||||
|
||||
-- One sample of the process every 5 minutes, and one at every start. The counters (collections, pauses, processor
|
||||
-- time, lock contentions, exceptions) are totals since the process started: the report takes the differences
|
||||
-- between two samples of the same process. warnings and errors are the log lines since the previous sample.
|
||||
-- calls holds the outbound HTTP calls since the previous sample, by destination, with their duration buckets.
|
||||
CREATE TABLE diagnostic_samples (
|
||||
id {uuid} PRIMARY KEY,
|
||||
taken_at {timestamp} NOT NULL,
|
||||
process_started_at {timestamp} NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
working_set {long} NOT NULL,
|
||||
private_bytes {long} NOT NULL,
|
||||
managed_heap {long} NOT NULL,
|
||||
gc_committed {long} NOT NULL,
|
||||
gc_gen0 {long} NOT NULL,
|
||||
gc_gen1 {long} NOT NULL,
|
||||
gc_gen2 {long} NOT NULL,
|
||||
gc_pause_ms {float} NOT NULL,
|
||||
threads INTEGER NOT NULL,
|
||||
handles INTEGER NOT NULL,
|
||||
cpu_ms {float} NOT NULL,
|
||||
pool_threads INTEGER NOT NULL,
|
||||
pool_pending {long} NOT NULL,
|
||||
lock_contentions {long} NOT NULL,
|
||||
exceptions {long} NOT NULL,
|
||||
db_bytes {long},
|
||||
warnings INTEGER NOT NULL,
|
||||
errors INTEGER NOT NULL,
|
||||
calls {json},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX diagnostic_samples_taken ON diagnostic_samples (taken_at);
|
||||
|
||||
-- Every run of a scheduled job, with its lateness and duration. jobs keeps only the last one.
|
||||
CREATE TABLE job_runs (
|
||||
id {uuid} PRIMARY KEY,
|
||||
job TEXT NOT NULL,
|
||||
due_at {timestamp} NOT NULL,
|
||||
started_at {timestamp} NOT NULL,
|
||||
finished_at {timestamp} NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
missed {bool} NOT NULL,
|
||||
error TEXT,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX job_runs_started ON job_runs (started_at);
|
||||
@@ -0,0 +1,82 @@
|
||||
-- News (SPEC 10.2, issue #56): where they come from, each article, the groups of articles telling the same story,
|
||||
-- and what each story is about.
|
||||
|
||||
-- A feed or an API. trusted is the "affidabile" label of 10.2, editable from the settings. topic is what the whole
|
||||
-- source is about when an article names nothing: 'market' for the central banks, 'crypto' for the crypto press.
|
||||
-- etag and last_modified make the next request conditional; failures counts the requests in a row that went wrong.
|
||||
CREATE TABLE news_sources (
|
||||
id {uuid} PRIMARY KEY,
|
||||
url TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
trusted {bool} NOT NULL,
|
||||
enabled {bool} NOT NULL,
|
||||
topic TEXT,
|
||||
etag TEXT,
|
||||
last_modified TEXT,
|
||||
last_checked_at {timestamp},
|
||||
last_ok_at {timestamp},
|
||||
failures INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
-- One story, told by one or more articles. sources counts the independent publishers (two feeds of the same
|
||||
-- newspaper count once); trusted says whether at least one article came from a trusted source. score, severe and
|
||||
-- importance sum up the first judgement of its articles (10.2 point 4): the mean score, a serious case if any
|
||||
-- article names one, the highest importance.
|
||||
CREATE TABLE news_stories (
|
||||
id {uuid} PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
title_key TEXT NOT NULL,
|
||||
published_at {timestamp} NOT NULL,
|
||||
first_seen_at {timestamp} NOT NULL,
|
||||
last_seen_at {timestamp} NOT NULL,
|
||||
sources INTEGER NOT NULL,
|
||||
trusted {bool} NOT NULL,
|
||||
score {float},
|
||||
severe TEXT,
|
||||
importance INTEGER NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX news_stories_published ON news_stories (published_at);
|
||||
|
||||
-- One article. url_key is the address without tracking parameters, fragments and the other differences that do
|
||||
-- not change the article: the same article is never stored twice. score is the tone of the local classifier, from
|
||||
-- -1 to +1, for English titles only (null otherwise); severe the serious case found by the keywords; importance 1 to 4.
|
||||
CREATE TABLE news_items (
|
||||
id {uuid} PRIMARY KEY,
|
||||
story_id {uuid} NOT NULL REFERENCES news_stories (id),
|
||||
source_id {uuid} NOT NULL REFERENCES news_sources (id),
|
||||
url TEXT NOT NULL,
|
||||
url_key TEXT NOT NULL UNIQUE,
|
||||
publisher TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
summary TEXT,
|
||||
language TEXT NOT NULL,
|
||||
published_at {timestamp} NOT NULL,
|
||||
score {float},
|
||||
severe TEXT,
|
||||
importance INTEGER NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX news_items_story ON news_items (story_id);
|
||||
|
||||
-- What a story is about: an instrument ('venue:symbol'), a class of instruments ('crypto', 'equity') or the market
|
||||
-- in general ('market'). via says how the link was found: the symbols given by the source, a ticker in the text,
|
||||
-- a name of the dictionary, a theme, or the topic of the source.
|
||||
CREATE TABLE news_links (
|
||||
id {uuid} PRIMARY KEY,
|
||||
story_id {uuid} NOT NULL REFERENCES news_stories (id),
|
||||
scope TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
via TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
UNIQUE (story_id, scope, target)
|
||||
){strict};
|
||||
|
||||
CREATE INDEX news_links_target ON news_links (scope, target);
|
||||
@@ -32,7 +32,7 @@ public static partial class Migrations
|
||||
{
|
||||
public const string VersionTable = "schema_versions";
|
||||
|
||||
[GeneratedRegex(@"\{(money|uuid|timestamp|json|bool|bytes|float|strict)\}")]
|
||||
[GeneratedRegex(@"\{(money|uuid|timestamp|json|bool|bytes|float|long|strict)\}")]
|
||||
internal static partial Regex Tokens();
|
||||
|
||||
[GeneratedRegex(@"^(\d{4})_([a-z0-9_]+)\.sql$")]
|
||||
|
||||
@@ -83,9 +83,10 @@ public static partial class Schema
|
||||
"{BOOL}" => ColumnKind.Bool,
|
||||
"{BYTES}" => ColumnKind.Bytes,
|
||||
"{FLOAT}" => ColumnKind.Measure,
|
||||
"{LONG}" => ColumnKind.Number,
|
||||
"TEXT" => ColumnKind.Text,
|
||||
"INTEGER" or "BIGINT" => ColumnKind.Number,
|
||||
var other => throw new InvalidOperationException($"Column type {other} is not portable: use TEXT, INTEGER, BIGINT or a token."),
|
||||
"INTEGER" => ColumnKind.Number,
|
||||
var other => throw new InvalidOperationException($"Column type {other} is not portable: use TEXT, INTEGER or a token."),
|
||||
};
|
||||
var upper = definition.ToUpperInvariant();
|
||||
var nullable = !upper.Contains("NOT NULL", StringComparison.Ordinal) && !upper.Contains("PRIMARY KEY", StringComparison.Ordinal);
|
||||
|
||||
@@ -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" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// The warning and error lines written by the logs since the last look (issue #95). The log writer counts each line;
|
||||
/// the sampler takes the counts every 5 minutes, so the report shows when the troubles came, not only how many.
|
||||
/// </summary>
|
||||
public static class LogCounter
|
||||
{
|
||||
private static long _warnings;
|
||||
private static long _errors;
|
||||
|
||||
public static void Record(LogLevel level)
|
||||
{
|
||||
if (level == LogLevel.Warning)
|
||||
{
|
||||
Interlocked.Increment(ref _warnings);
|
||||
}
|
||||
else if (level >= LogLevel.Error && level != LogLevel.None)
|
||||
{
|
||||
Interlocked.Increment(ref _errors);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The lines since the previous call, and the counts start again from zero.</summary>
|
||||
public static (int Warnings, int Errors) Take() =>
|
||||
((int)Math.Min(int.MaxValue, Interlocked.Exchange(ref _warnings, 0)), (int)Math.Min(int.MaxValue, Interlocked.Exchange(ref _errors, 0)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every exception thrown in the process, caught or not, since the counting started. Many are normal (a cancelled
|
||||
/// wait, a lost connection retried), but a count that keeps climbing points to a loop that fails over and over.
|
||||
/// </summary>
|
||||
public static class ExceptionCounter
|
||||
{
|
||||
private static long _count;
|
||||
private static int _started;
|
||||
|
||||
public static long Count => Interlocked.Read(ref _count);
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) == 0)
|
||||
{
|
||||
AppDomain.CurrentDomain.FirstChanceException += (_, _) => Interlocked.Increment(ref _count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
public static class SampleKinds
|
||||
{
|
||||
/// <summary>The first sample of a process, written as soon as the bot is ready.</summary>
|
||||
public const string Start = "start";
|
||||
|
||||
public const string Periodic = "periodic";
|
||||
}
|
||||
|
||||
/// <summary>One look at the process (issue #95). Counters are totals since the process started.</summary>
|
||||
public sealed record ProcessSample
|
||||
{
|
||||
public required DateTimeOffset TakenAt { get; init; }
|
||||
|
||||
public required DateTimeOffset ProcessStartedAt { get; init; }
|
||||
|
||||
public required string Kind { get; init; }
|
||||
|
||||
public string Version { get; init; } = AnubisInfo.Version;
|
||||
|
||||
public long WorkingSet { get; init; }
|
||||
|
||||
public long PrivateBytes { get; init; }
|
||||
|
||||
public long ManagedHeap { get; init; }
|
||||
|
||||
public long GcCommitted { get; init; }
|
||||
|
||||
public long Gen0 { get; init; }
|
||||
|
||||
public long Gen1 { get; init; }
|
||||
|
||||
public long Gen2 { get; init; }
|
||||
|
||||
public double GcPauseMs { get; init; }
|
||||
|
||||
public int Threads { get; init; }
|
||||
|
||||
public int Handles { get; init; }
|
||||
|
||||
public double CpuMs { get; init; }
|
||||
|
||||
public int PoolThreads { get; init; }
|
||||
|
||||
public long PoolPending { get; init; }
|
||||
|
||||
public long LockContentions { get; init; }
|
||||
|
||||
public long Exceptions { get; init; }
|
||||
|
||||
public long? DbBytes { get; init; }
|
||||
|
||||
public int Warnings { get; init; }
|
||||
|
||||
public int Errors { get; init; }
|
||||
|
||||
public IReadOnlyList<HttpCallStats> Calls { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every 5 minutes, and once at each start, a sample of the process goes to <c>diagnostic_samples</c>, with the log
|
||||
/// warnings and errors and the outbound calls since the previous one (issue #95, ADR 0013). Samples and job runs older
|
||||
/// than 30 days are deleted once a day. It only measures: nothing here changes what the bot does.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticSampler(Database db, IClock clock, HttpCallMeter meter)
|
||||
{
|
||||
public const string JobName = "diagnostica";
|
||||
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(5);
|
||||
|
||||
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
|
||||
|
||||
internal static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private DateTimeOffset? _lastPrune;
|
||||
|
||||
public ScheduledJob Job() => new(JobName, "Raccolta dei dati per l'analisi", Schedule.Every(Interval), ct => TakeAsync(SampleKinds.Periodic, ct))
|
||||
{
|
||||
MaxLateness = Interval,
|
||||
};
|
||||
|
||||
public async Task<ProcessSample> TakeAsync(string kind, CancellationToken cancellationToken)
|
||||
{
|
||||
var (warnings, errors) = LogCounter.Take();
|
||||
var sample = Probe(clock.UtcNow, kind) with
|
||||
{
|
||||
DbBytes = await DatabaseBytesAsync(db, cancellationToken).ConfigureAwait(false),
|
||||
Warnings = warnings,
|
||||
Errors = errors,
|
||||
Calls = meter.Take(),
|
||||
};
|
||||
var prune = _lastPrune is not { } last || sample.TakenAt - last >= TimeSpan.FromDays(1);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await WriteAsync(s, clock, sample, cancellationToken).ConfigureAwait(false);
|
||||
if (prune)
|
||||
{
|
||||
var before = sample.TakenAt - Keep;
|
||||
await s.ExecuteAsync("DELETE FROM diagnostic_samples WHERE taken_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("DELETE FROM job_runs WHERE started_at < @t", cancellationToken, ("t", before)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (prune)
|
||||
{
|
||||
_lastPrune = sample.TakenAt;
|
||||
}
|
||||
|
||||
return sample;
|
||||
}
|
||||
|
||||
/// <summary>The process as it is now. Process times come from the system clock: they measure the machine, not the market.</summary>
|
||||
public static ProcessSample Probe(DateTimeOffset now, string kind)
|
||||
{
|
||||
using var process = Process.GetCurrentProcess();
|
||||
var gc = GC.GetGCMemoryInfo();
|
||||
return new ProcessSample
|
||||
{
|
||||
TakenAt = now,
|
||||
ProcessStartedAt = new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero),
|
||||
Kind = kind,
|
||||
WorkingSet = process.WorkingSet64,
|
||||
PrivateBytes = process.PrivateMemorySize64,
|
||||
ManagedHeap = GC.GetTotalMemory(forceFullCollection: false),
|
||||
GcCommitted = gc.TotalCommittedBytes,
|
||||
Gen0 = GC.CollectionCount(0),
|
||||
Gen1 = GC.CollectionCount(1),
|
||||
Gen2 = GC.CollectionCount(2),
|
||||
GcPauseMs = Math.Round(GC.GetTotalPauseDuration().TotalMilliseconds, 1),
|
||||
Threads = process.Threads.Count,
|
||||
Handles = process.HandleCount,
|
||||
CpuMs = Math.Round(process.TotalProcessorTime.TotalMilliseconds, 1),
|
||||
PoolThreads = ThreadPool.ThreadCount,
|
||||
PoolPending = ThreadPool.PendingWorkItemCount,
|
||||
LockContentions = Monitor.LockContentionCount,
|
||||
Exceptions = ExceptionCounter.Count,
|
||||
};
|
||||
}
|
||||
|
||||
public static async Task WriteAsync(DbSession s, IClock clock, ProcessSample sample, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(s);
|
||||
ArgumentNullException.ThrowIfNull(sample);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO diagnostic_samples (id, taken_at, process_started_at, kind, version, working_set, private_bytes, managed_heap, gc_committed, gc_gen0, gc_gen1, gc_gen2, " +
|
||||
"gc_pause_ms, threads, handles, cpu_ms, pool_threads, pool_pending, lock_contentions, exceptions, db_bytes, warnings, errors, calls, created_at) VALUES " +
|
||||
"(@id, @t, @ps, @k, @v, @ws, @pb, @mh, @gcc, @g0, @g1, @g2, @gp, @th, @h, @cpu, @pt, @pp, @lc, @ex, @db, @w, @e, @calls, @now)",
|
||||
cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("t", sample.TakenAt), ("ps", sample.ProcessStartedAt), ("k", sample.Kind), ("v", sample.Version), ("ws", sample.WorkingSet),
|
||||
("pb", sample.PrivateBytes), ("mh", sample.ManagedHeap), ("gcc", sample.GcCommitted), ("g0", sample.Gen0), ("g1", sample.Gen1), ("g2", sample.Gen2),
|
||||
("gp", sample.GcPauseMs), ("th", sample.Threads), ("h", sample.Handles), ("cpu", sample.CpuMs), ("pt", sample.PoolThreads), ("pp", sample.PoolPending),
|
||||
("lc", sample.LockContentions), ("ex", sample.Exceptions), ("db", sample.DbBytes), ("w", sample.Warnings), ("e", sample.Errors),
|
||||
("calls", sample.Calls.Count == 0 ? null : new DbJson(JsonSerializer.Serialize(sample.Calls, Json))), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The size of the database: its files on SQLite (with the journal), what PostgreSQL reports for it.</summary>
|
||||
public static async Task<long?> DatabaseBytesAsync(Database db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
try
|
||||
{
|
||||
if (db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
return db.SqlitePath is not { } path ? null
|
||||
: new[] { path, path + "-wal", path + "-shm" }.Where(File.Exists).Sum(f => new FileInfo(f).Length);
|
||||
}
|
||||
|
||||
return await db.ReadAsync(s => s.CountAsync("SELECT pg_database_size(current_database())"), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Supervision;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>What the report covers and the facts about the installation that only the caller knows.</summary>
|
||||
public sealed record DiagnosticsRequest(DateTimeOffset From, DateTimeOffset To, TimeZoneInfo Zone)
|
||||
{
|
||||
/// <summary>The folder of the technical logs (<c>anubis-yyyyMMdd.log</c>); without it the report skips them.</summary>
|
||||
public string? LogsFolder { get; init; }
|
||||
|
||||
/// <summary>Startup settings with nothing secret in them, shown as they are.</summary>
|
||||
public IReadOnlyList<KeyValuePair<string, string>> Setup { get; init; } = [];
|
||||
|
||||
public DateTimeOffset GeneratedAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The report the user pastes back after a long run of a release (issue #95, ADR 0013): in Markdown, at most 60 KB,
|
||||
/// with everything passed through <see cref="Redactor"/> and the user's folders masked. It only reads.
|
||||
/// </summary>
|
||||
public static partial class DiagnosticsReporter
|
||||
{
|
||||
public const int MaxBytes = 60 * 1024;
|
||||
|
||||
private const int MaxLogGroups = 40;
|
||||
private const long MaxLogBytes = 256L * 1024 * 1024;
|
||||
|
||||
/// <summary>Two missed samples in a row: the process lived but did not sample (sleep, a stuck scheduler).</summary>
|
||||
private static readonly TimeSpan Silence = DiagnosticSampler.Interval * 2 + TimeSpan.FromMinutes(1);
|
||||
|
||||
private static readonly TimeSpan[] Steps =
|
||||
[TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30), TimeSpan.FromHours(1), TimeSpan.FromHours(2), TimeSpan.FromHours(3),
|
||||
TimeSpan.FromHours(6), TimeSpan.FromHours(12), TimeSpan.FromDays(1)];
|
||||
|
||||
public static async Task<string> BuildAsync(Database db, DiagnosticsRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (request.To <= request.From)
|
||||
{
|
||||
throw new ArgumentException("La fine del periodo deve venire dopo l'inizio.", nameof(request));
|
||||
}
|
||||
|
||||
var zone = request.Zone;
|
||||
var findings = new List<string>();
|
||||
var soak = await SoakReporter.BuildAsync(db, request.From, request.To, request.To - request.From, zone, cancellationToken).ConfigureAwait(false);
|
||||
var data = await db.ReadAsync(async s =>
|
||||
{
|
||||
(string Name, object? Value)[] window = [("from", request.From), ("to", request.To)];
|
||||
var engine = await s.FirstOrDefaultAsync(s.Engine == DbEngine.Sqlite ? "SELECT 'SQLite ' || sqlite_version() AS v" : "SELECT version() AS v", r => r.Text("v")).ConfigureAwait(false);
|
||||
var samples = await s.QueryAsync("SELECT * FROM diagnostic_samples WHERE taken_at >= @from AND taken_at <= @to ORDER BY taken_at", ReadSample, window).ConfigureAwait(false);
|
||||
var runs = await s.QueryAsync("SELECT job, due_at, started_at, finished_at, outcome, missed, error FROM job_runs WHERE started_at >= @from AND started_at <= @to",
|
||||
r => new Run(r.Text("job"), r.Moment("due_at"), r.Moment("started_at"), r.Moment("finished_at"), r.Text("outcome"), r.Bool("missed"), r.TextOrNull("error")), window)
|
||||
.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);
|
||||
return (Engine: engine, Samples: samples, Runs: runs, Absences: absences);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var logs = request.LogsFolder is { } folder ? ReadLogs(folder, request.From, request.To) : null;
|
||||
|
||||
var sections = new List<string>
|
||||
{
|
||||
Setup(request, data.Engine, data.Samples),
|
||||
Soak(soak, findings),
|
||||
Starts(data.Samples, data.Absences, zone, findings),
|
||||
Jobs(data.Runs, findings),
|
||||
Calls(data.Samples, findings),
|
||||
Logs(logs, zone, findings),
|
||||
Resources(data.Samples, request, findings),
|
||||
};
|
||||
|
||||
var text = new StringBuilder()
|
||||
.AppendLine("# Anubis · dati per l'analisi")
|
||||
.AppendLine()
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"Versione {AnubisInfo.Version} (commit {AnubisInfo.Commit ?? "non noto"}). Dal {SoakReport.Moment(request.From, zone)} al " +
|
||||
$"{SoakReport.Moment(request.To, zone)} ({SoakReport.Hours(request.To - request.From)}), ora di {zone.Id}. Fatto il {SoakReport.Moment(request.GeneratedAt, zone)}.")
|
||||
.AppendLine()
|
||||
.AppendLine("## In breve")
|
||||
.AppendLine();
|
||||
foreach (var finding in findings.Count == 0 ? ["Nessun segnale di problema nei dati raccolti."] : findings)
|
||||
{
|
||||
text.AppendLine("- " + finding);
|
||||
}
|
||||
|
||||
foreach (var section in sections)
|
||||
{
|
||||
text.AppendLine().Append(section);
|
||||
}
|
||||
|
||||
return Fit(Mask(text.ToString().ReplaceLineEndings("\n")));
|
||||
}
|
||||
|
||||
/// <summary>The user's folders and name out, the secrets out, and no more than <see cref="MaxBytes"/>.</summary>
|
||||
internal static string Mask(string text)
|
||||
{
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
if (profile.Length > 3)
|
||||
{
|
||||
text = text.Replace(profile, "%USERPROFILE%", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
var user = Environment.UserName;
|
||||
if (user.Length >= 3)
|
||||
{
|
||||
text = text.Replace("\\" + user + "\\", "\\‹utente›\\", StringComparison.OrdinalIgnoreCase)
|
||||
.Replace("/" + user + "/", "/‹utente›/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return Redactor.Redact(text);
|
||||
}
|
||||
|
||||
internal static string Fit(string text)
|
||||
{
|
||||
if (Encoding.UTF8.GetByteCount(text) <= MaxBytes)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
const string note = "\n\n_Rapporto tagliato a 60 KB: le righe più vecchie delle risorse mancano._\n";
|
||||
var limit = MaxBytes - Encoding.UTF8.GetByteCount(note);
|
||||
var cut = text.Length;
|
||||
while (cut > 0 && Encoding.UTF8.GetByteCount(text.AsSpan(0, cut)) > limit)
|
||||
{
|
||||
cut = text.LastIndexOf('\n', cut - 1);
|
||||
}
|
||||
|
||||
return text[..Math.Max(0, cut)] + note;
|
||||
}
|
||||
|
||||
private static string Setup(DiagnosticsRequest request, string? engine, List<ProcessSample> samples)
|
||||
{
|
||||
var text = new StringBuilder("## Installazione\n\n");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- Sistema: {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture}), {Environment.ProcessorCount} processori")
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"- Runtime: {RuntimeInformation.FrameworkDescription}")
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"- Motore del database: {engine ?? "non noto"}");
|
||||
if (samples.LastOrDefault(s => s.DbBytes is not null) is { DbBytes: { } bytes })
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- Dimensione del database: {Mb(bytes)} MB");
|
||||
}
|
||||
|
||||
foreach (var (name, value) in request.Setup)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- {name}: {value}");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Soak(SoakReport soak, List<string> findings)
|
||||
{
|
||||
var failed = soak.Checks.Where(c => !c.Ok).ToList();
|
||||
if (failed.Count > 0)
|
||||
{
|
||||
findings.Add($"Controlli del lavoro da guardare: {failed.Count} (sezione «Controlli del lavoro»).");
|
||||
}
|
||||
|
||||
var text = new StringBuilder("## Controlli del lavoro\n\n");
|
||||
foreach (var check in soak.Checks)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"- {(check.Ok ? "✓" : "✗")} {check.Text}");
|
||||
}
|
||||
|
||||
foreach (var fact in soak.Facts)
|
||||
{
|
||||
text.AppendLine("- " + fact);
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Starts(List<ProcessSample> samples, List<(DateTimeOffset Start, DateTimeOffset End)> absences, TimeZoneInfo zone, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Avvii, spegnimenti e silenzi\n\n");
|
||||
var processes = Processes(samples);
|
||||
if (processes.Count == 0)
|
||||
{
|
||||
findings.Add("Nessun campione nel periodo: la raccolta dei dati non ha girato (versione senza raccolta, o bot spento).");
|
||||
return text.AppendLine("Nessun campione nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Avviato | Versione | Primo campione | Ultimo campione | Campioni |").AppendLine("|---|---|---|---|---|");
|
||||
foreach (var p in processes)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {SoakReport.Moment(p[0].ProcessStartedAt, zone)} | {p[0].Version} | {SoakReport.Moment(p[0].TakenAt, zone)} | {SoakReport.Moment(p[^1].TakenAt, zone)} | {p.Count} |");
|
||||
}
|
||||
|
||||
if (processes.Count > 1)
|
||||
{
|
||||
findings.Add($"Il bot è ripartito {processes.Count - 1} volte nel periodo.");
|
||||
}
|
||||
|
||||
text.AppendLine();
|
||||
if (absences.Count > 0)
|
||||
{
|
||||
var total = absences.Aggregate(TimeSpan.Zero, (sum, a) => sum + (a.End - a.Start));
|
||||
findings.Add($"Spento {absences.Count} volte, in tutto {Duration(total)}.");
|
||||
text.AppendLine("Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Duration(a.End - a.Start)}")) + ".");
|
||||
}
|
||||
else
|
||||
{
|
||||
text.AppendLine("Nessuno spegnimento registrato.");
|
||||
}
|
||||
|
||||
var silences = processes.SelectMany(p => p.Zip(p.Skip(1)).Where(x => x.Second.TakenAt - x.First.TakenAt > Silence)).ToList();
|
||||
if (silences.Count > 0)
|
||||
{
|
||||
var total = silences.Aggregate(TimeSpan.Zero, (sum, x) => sum + (x.Second.TakenAt - x.First.TakenAt));
|
||||
findings.Add($"Silenzi a processo acceso: {silences.Count}, in tutto {Duration(total)} (computer in sospensione, o lavori bloccati).");
|
||||
text.AppendLine().AppendLine("Silenzi a processo acceso (nessun campione per più di 11 minuti): " +
|
||||
string.Join(", ", silences.Take(30).Select(x => $"dal {SoakReport.Moment(x.First.TakenAt, zone)} per {Duration(x.Second.TakenAt - x.First.TakenAt)}")) +
|
||||
(silences.Count > 30 ? $" e altri {silences.Count - 30}" : "") + ".");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Jobs(List<Run> runs, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Lavori pianificati\n\n");
|
||||
if (runs.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessuna esecuzione registrata nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Lavoro | Esecuzioni | Fallite | Saltate | Recuperate | Ritardo medio · massimo | Durata mediana · 95% · massima | Ultimo errore |")
|
||||
.AppendLine("|---|---|---|---|---|---|---|---|");
|
||||
foreach (var job in runs.GroupBy(r => r.Job, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal))
|
||||
{
|
||||
var list = job.OrderBy(r => r.Started).ToList();
|
||||
var failed = list.Count(r => r.Outcome == "failed");
|
||||
var skipped = list.Count(r => r.Outcome == "skipped");
|
||||
var late = list.Where(r => r.Outcome != "skipped" && !r.Missed).Select(r => (r.Started - r.Due).TotalSeconds).DefaultIfEmpty(0).ToList();
|
||||
var took = list.Where(r => r.Outcome != "skipped").Select(r => (r.Finished - r.Started).TotalSeconds).Order().ToList();
|
||||
var error = list.LastOrDefault(r => r.Error is not null)?.Error;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {job.Key} | {list.Count} | {failed} | {skipped} | {list.Count(r => r.Missed)} | {Seconds(late.Average())} · {Seconds(late.Max())} | " +
|
||||
$"{Seconds(Rank(took, 0.5))} · {Seconds(Rank(took, 0.95))} · {Seconds(took.LastOrDefault())} | {Cell(error, 160)} |");
|
||||
if (failed > 0)
|
||||
{
|
||||
findings.Add($"Il lavoro «{job.Key}» è fallito {failed} volte su {list.Count}.");
|
||||
}
|
||||
|
||||
if (skipped > 0)
|
||||
{
|
||||
findings.Add($"Il lavoro «{job.Key}» è stato saltato {skipped} volte (troppo in ritardo).");
|
||||
}
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Calls(List<ProcessSample> samples, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Chiamate esterne\n\n");
|
||||
var calls = HttpCallStats.Merge(samples.SelectMany(s => s.Calls));
|
||||
if (calls.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessuna chiamata registrata nel periodo.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Destinazione | Chiamate | Fallite | Esiti | Media ms | 50% ms | 95% ms | Massimo ms |").AppendLine("|---|---|---|---|---|---|---|---|");
|
||||
foreach (var c in calls)
|
||||
{
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {Cell(c.Host, 80)} | {c.Calls} | {c.Failures} | {Cell(string.Join(", ", c.Outcomes.Select(o => o.Key + "×" + o.Value)), 160)} | {Ms(c.AverageMs)} | " +
|
||||
$"{Ms(c.Percentile(0.5))} | {Ms(c.Percentile(0.95))} | {Ms(c.MaxMs)} |");
|
||||
if (c.Calls >= 20 && c.Failures * 20 > c.Calls)
|
||||
{
|
||||
findings.Add($"Le chiamate a {c.Host} falliscono spesso: {c.Failures} su {c.Calls}.");
|
||||
}
|
||||
|
||||
if (c.Calls >= 20 && c.Percentile(0.95) >= 5000)
|
||||
{
|
||||
findings.Add($"Le chiamate a {c.Host} sono lente: il 95% sta sotto {Ms(c.Percentile(0.95))} ms.");
|
||||
}
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Logs(LogSummary? logs, TimeZoneInfo zone, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Registri tecnici: avvisi ed errori\n\n");
|
||||
if (logs is null)
|
||||
{
|
||||
return text.AppendLine("Cartella dei registri non disponibile.").ToString();
|
||||
}
|
||||
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"Letti {logs.Files} file, {logs.Lines} righe nel periodo: {logs.Warnings} avvisi e {logs.Errors} errori{(logs.Truncated ? " (lettura fermata a 256 MB)" : "")}.").AppendLine();
|
||||
if (logs.Errors > 0)
|
||||
{
|
||||
findings.Add($"Errori nei registri tecnici: {logs.Errors}, di {logs.Groups.Count(g => g.Level != "warning")} tipi.");
|
||||
}
|
||||
|
||||
if (logs.Groups.Count == 0)
|
||||
{
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
text.AppendLine("| Livello | Volte | Prima | Ultima | Origine | Messaggio |").AppendLine("|---|---|---|---|---|---|");
|
||||
foreach (var g in logs.Groups.OrderBy(g => g.Level == "warning" ? 1 : 0).ThenByDescending(g => g.Count).Take(MaxLogGroups))
|
||||
{
|
||||
var message = g.Error is null ? g.Sample : g.Sample + " — " + g.Error;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {g.Level} | {g.Count} | {SoakReport.Moment(g.First, zone)} | {SoakReport.Moment(g.Last, zone)} | {Cell(g.Category, 60)} | {Cell(message, 300)} |");
|
||||
}
|
||||
|
||||
if (logs.Groups.Count > MaxLogGroups)
|
||||
{
|
||||
text.AppendLine().AppendLine(CultureInfo.InvariantCulture, $"Altri {logs.Groups.Count - MaxLogGroups} tipi di messaggio non mostrati.");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Resources(List<ProcessSample> samples, DiagnosticsRequest request, List<string> findings)
|
||||
{
|
||||
var text = new StringBuilder("## Risorse nel tempo\n\n");
|
||||
var processes = Processes(samples);
|
||||
if (processes.Count == 0)
|
||||
{
|
||||
return text.AppendLine("Nessun campione.").ToString();
|
||||
}
|
||||
|
||||
foreach (var p in processes)
|
||||
{
|
||||
var settled = p.Where(s => s.TakenAt - s.ProcessStartedAt >= TimeSpan.FromMinutes(30)).ToList();
|
||||
var line = $"Processo avviato il {SoakReport.Moment(p[0].ProcessStartedAt, request.Zone)}: memoria da {Mb(p[0].WorkingSet)} a {Mb(p[^1].WorkingSet)} MB, " +
|
||||
$"memoria gestita da {Mb(p[0].ManagedHeap)} a {Mb(p[^1].ManagedHeap)} MB, handle da {p[0].Handles} a {p[^1].Handles}, thread da {p[0].Threads} a {p[^1].Threads}";
|
||||
if (settled.Count >= 12 && settled[^1].TakenAt - settled[0].TakenAt >= TimeSpan.FromHours(3))
|
||||
{
|
||||
var ws = Slope(settled, s => s.WorkingSet / 1048576.0);
|
||||
var heap = Slope(settled, s => s.GcCommitted / 1048576.0);
|
||||
var handles = Slope(settled, s => s.Handles);
|
||||
var threads = Slope(settled, s => s.Threads);
|
||||
line += $"; pendenza dopo la prima mezz'ora: memoria {Signed(ws)} MB/ora, memoria del GC {Signed(heap)} MB/ora, handle {Signed(handles)}/ora, thread {Signed(threads)}/ora";
|
||||
var hours = (settled[^1].TakenAt - settled[0].TakenAt).TotalHours;
|
||||
if (ws > 2 && ws * hours > settled[0].WorkingSet / 1048576.0 * 0.2)
|
||||
{
|
||||
findings.Add($"La memoria cresce di {Signed(ws)} MB l'ora da {Duration(TimeSpan.FromHours(hours))}: possibile perdita.");
|
||||
}
|
||||
|
||||
if (handles > 10 && handles * hours > settled[0].Handles * 0.2)
|
||||
{
|
||||
findings.Add($"Gli handle crescono di {Signed(handles)} l'ora: possibile perdita di connessioni o file.");
|
||||
}
|
||||
|
||||
if (threads > 1 && threads * hours > settled[0].Threads * 0.3)
|
||||
{
|
||||
findings.Add($"I thread crescono di {Signed(threads)} l'ora.");
|
||||
}
|
||||
}
|
||||
|
||||
var hoursAlive = (p[^1].TakenAt - p[0].ProcessStartedAt).TotalHours;
|
||||
if (hoursAlive >= 1 && (p[^1].Exceptions / hoursAlive) > 2000)
|
||||
{
|
||||
findings.Add($"Molte eccezioni: {Format.Number((decimal)(p[^1].Exceptions / hoursAlive))} l'ora nel processo avviato il {SoakReport.Moment(p[0].ProcessStartedAt, request.Zone)}.");
|
||||
}
|
||||
|
||||
text.AppendLine(line + ".");
|
||||
}
|
||||
|
||||
var dbFirst = samples.FirstOrDefault(s => s.DbBytes is not null);
|
||||
var dbLast = samples.LastOrDefault(s => s.DbBytes is not null);
|
||||
if (dbFirst is { DbBytes: { } a } && dbLast is { DbBytes: { } b } && dbLast.TakenAt - dbFirst.TakenAt >= TimeSpan.FromHours(6))
|
||||
{
|
||||
var perDay = (b - a) / (dbLast.TakenAt - dbFirst.TakenAt).TotalDays;
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"Il database è passato da {Mb(a)} a {Mb(b)} MB ({Signed(perDay / 1048576.0)} MB al giorno).");
|
||||
}
|
||||
|
||||
var span = request.To - request.From;
|
||||
var step = Steps.FirstOrDefault(s => span / s <= 48, Steps[^1]);
|
||||
text.AppendLine()
|
||||
.AppendLine(CultureInfo.InvariantCulture, $"Un campione ogni {Duration(step)}; i conteggi sono dal campione della riga prima. Memorie in MB, CPU in % di un processore.")
|
||||
.AppendLine()
|
||||
.AppendLine("| Ora | Memoria | Gestita | GC | Thread | Handle | Coda | CPU % | GC2 | Pause ms | Eccezioni | Avvisi | Errori | DB | |")
|
||||
.AppendLine("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|");
|
||||
ProcessSample? previous = null;
|
||||
foreach (var bucket in samples.GroupBy(s => s.TakenAt.UtcTicks / step.Ticks).OrderBy(g => g.Key))
|
||||
{
|
||||
var last = bucket.Last();
|
||||
var same = previous is not null && previous.ProcessStartedAt == last.ProcessStartedAt;
|
||||
var basis = same ? previous! : null;
|
||||
var wall = (last.TakenAt - (basis?.TakenAt ?? last.ProcessStartedAt)).TotalMilliseconds;
|
||||
var cpu = wall <= 0 ? 0 : (last.CpuMs - (basis?.CpuMs ?? 0)) / wall * 100;
|
||||
text.AppendLine(CultureInfo.InvariantCulture,
|
||||
$"| {SoakReport.Moment(last.TakenAt, request.Zone)} | {Mb(last.WorkingSet)} | {Mb(last.ManagedHeap)} | {Mb(last.GcCommitted)} | {last.Threads} | {last.Handles} | " +
|
||||
$"{last.PoolPending} | {Format.Number((decimal)cpu, 1)} | {last.Gen2 - (basis?.Gen2 ?? 0)} | {Format.Number((decimal)(last.GcPauseMs - (basis?.GcPauseMs ?? 0)))} | " +
|
||||
$"{last.Exceptions - (basis?.Exceptions ?? 0)} | {bucket.Sum(s => s.Warnings)} | {bucket.Sum(s => s.Errors)} | {(last.DbBytes is { } db ? Mb(db) : "")} | " +
|
||||
$"{(previous is not null && !same ? "riavvio" : "")} |");
|
||||
previous = last;
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static List<List<ProcessSample>> Processes(List<ProcessSample> samples) =>
|
||||
samples.GroupBy(s => s.ProcessStartedAt).Select(g => g.OrderBy(s => s.TakenAt).ToList()).OrderBy(p => p[0].TakenAt).ToList();
|
||||
|
||||
private static ProcessSample ReadSample(DbRow r) => new()
|
||||
{
|
||||
TakenAt = r.Moment("taken_at"),
|
||||
ProcessStartedAt = r.Moment("process_started_at"),
|
||||
Kind = r.Text("kind"),
|
||||
Version = r.Text("version"),
|
||||
WorkingSet = r.Number("working_set"),
|
||||
PrivateBytes = r.Number("private_bytes"),
|
||||
ManagedHeap = r.Number("managed_heap"),
|
||||
GcCommitted = r.Number("gc_committed"),
|
||||
Gen0 = r.Number("gc_gen0"),
|
||||
Gen1 = r.Number("gc_gen1"),
|
||||
Gen2 = r.Number("gc_gen2"),
|
||||
GcPauseMs = r.Measure("gc_pause_ms"),
|
||||
Threads = (int)r.Number("threads"),
|
||||
Handles = (int)r.Number("handles"),
|
||||
CpuMs = r.Measure("cpu_ms"),
|
||||
PoolThreads = (int)r.Number("pool_threads"),
|
||||
PoolPending = r.Number("pool_pending"),
|
||||
LockContentions = r.Number("lock_contentions"),
|
||||
Exceptions = r.Number("exceptions"),
|
||||
DbBytes = r.IsNull("db_bytes") ? null : r.Number("db_bytes"),
|
||||
Warnings = (int)r.Number("warnings"),
|
||||
Errors = (int)r.Number("errors"),
|
||||
Calls = r.TextOrNull("calls") is { } json ? JsonSerializer.Deserialize<List<HttpCallStats>>(json, DiagnosticSampler.Json) ?? [] : [],
|
||||
};
|
||||
|
||||
/// <summary>The warning and error lines of the technical logs in the window, grouped by what they say.</summary>
|
||||
internal static LogSummary ReadLogs(string folder, DateTimeOffset from, DateTimeOffset to)
|
||||
{
|
||||
var groups = new Dictionary<string, LogGroup>(StringComparer.Ordinal);
|
||||
int files = 0, warnings = 0, errors = 0;
|
||||
long lines = 0, read = 0;
|
||||
var truncated = false;
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
return new LogSummary(0, 0, 0, 0, false, []);
|
||||
}
|
||||
|
||||
var first = DateOnly.FromDateTime(from.UtcDateTime).AddDays(-1);
|
||||
var last = DateOnly.FromDateTime(to.UtcDateTime).AddDays(1);
|
||||
foreach (var file in Directory.EnumerateFiles(folder, "anubis-*.log").Order(StringComparer.Ordinal))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (!DateOnly.TryParseExact(name["anubis-".Length..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) || day < first || day > last)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read >= MaxLogBytes)
|
||||
{
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
|
||||
files++;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
while (reader.ReadLine() is { } line)
|
||||
{
|
||||
read += line.Length + 1;
|
||||
if (read > MaxLogBytes)
|
||||
{
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!TryParse(line, out var entry) || entry.At < from || entry.At > to)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lines++;
|
||||
if (entry.Level is not ("warning" or "error" or "critical"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.Level == "warning")
|
||||
{
|
||||
warnings++;
|
||||
}
|
||||
else
|
||||
{
|
||||
errors++;
|
||||
}
|
||||
|
||||
var category = entry.Category[(entry.Category.LastIndexOf('.') + 1)..];
|
||||
var key = entry.Level + "|" + category + "|" + Normalize(entry.Message);
|
||||
if (groups.TryGetValue(key, out var group))
|
||||
{
|
||||
groups[key] = group with { Count = group.Count + 1, Last = entry.At > group.Last ? entry.At : group.Last, Error = group.Error ?? entry.Error };
|
||||
}
|
||||
else
|
||||
{
|
||||
groups[key] = new LogGroup(entry.Level, category, entry.Message, entry.Error, 1, entry.At, entry.At);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new LogSummary(files, lines, warnings, errors, truncated, [.. groups.Values]);
|
||||
}
|
||||
|
||||
private static bool TryParse(string line, out (DateTimeOffset At, string Level, string Category, string Message, string? Error) entry)
|
||||
{
|
||||
entry = default;
|
||||
try
|
||||
{
|
||||
using var json = JsonDocument.Parse(line);
|
||||
var root = json.RootElement;
|
||||
if (!root.TryGetProperty("at", out var at) || !DateTimeOffset.TryParse(at.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var moment))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
entry = (moment, root.TryGetProperty("level", out var l) ? l.GetString() ?? "" : "", root.TryGetProperty("category", out var c) ? c.GetString() ?? "" : "",
|
||||
root.TryGetProperty("message", out var m) ? m.GetString() ?? "" : "", root.TryGetProperty("error", out var e) ? e.GetString() : null);
|
||||
return true;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The message with ids and numbers taken out, so the same trouble with other values counts once.</summary>
|
||||
internal static string Normalize(string message) => Numbers().Replace(Guids().Replace(message, "‹id›"), "#");
|
||||
|
||||
private static double Slope(List<ProcessSample> samples, Func<ProcessSample, double> value)
|
||||
{
|
||||
var t0 = samples[0].TakenAt;
|
||||
var xs = samples.Select(s => (s.TakenAt - t0).TotalHours).ToList();
|
||||
var ys = samples.Select(value).ToList();
|
||||
var mx = xs.Average();
|
||||
var my = ys.Average();
|
||||
var den = xs.Sum(x => (x - mx) * (x - mx));
|
||||
return den == 0 ? 0 : xs.Zip(ys).Sum(p => (p.First - mx) * (p.Second - my)) / den;
|
||||
}
|
||||
|
||||
private static double Rank(List<double> sorted, double q) => sorted.Count == 0 ? 0 : sorted[Math.Clamp((int)Math.Ceiling(q * sorted.Count) - 1, 0, sorted.Count - 1)];
|
||||
|
||||
private static string Mb(long bytes) => Format.Number((decimal)Math.Round(bytes / 1048576.0, 1), 1);
|
||||
|
||||
private static string Ms(double ms) => Format.Number((decimal)Math.Round(ms));
|
||||
|
||||
private static string Seconds(double seconds) => seconds < 10 ? Format.Number((decimal)Math.Round(seconds, 2), 2) + " s" : Format.Number((decimal)Math.Round(seconds)) + " s";
|
||||
|
||||
private static string Signed(double value) => Format.Number((decimal)Math.Round(value, 2), 2, withSign: true);
|
||||
|
||||
private static string Duration(TimeSpan span) => span.TotalMinutes < 90
|
||||
? Format.Number((decimal)Math.Round(span.TotalMinutes)) + " minuti"
|
||||
: span.TotalHours < 48 ? SoakReport.Hours(TimeSpan.FromHours(Math.Round(span.TotalHours, 1))) : Format.Number((decimal)Math.Round(span.TotalDays, 1), 1) + " giorni";
|
||||
|
||||
private static string Cell(string? text, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
var flat = text.ReplaceLineEndings(" ").Replace("|", "\\|", StringComparison.Ordinal);
|
||||
return flat.Length <= max ? flat : flat[..max] + "…";
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")]
|
||||
private static partial Regex Guids();
|
||||
|
||||
[GeneratedRegex(@"\d+(?:[.,:]\d+)*")]
|
||||
private static partial Regex Numbers();
|
||||
|
||||
private sealed record Run(string Job, DateTimeOffset Due, DateTimeOffset Started, DateTimeOffset Finished, string Outcome, bool Missed, string? Error);
|
||||
|
||||
internal sealed record LogGroup(string Level, string Category, string Sample, string? Error, int Count, DateTimeOffset First, DateTimeOffset Last);
|
||||
|
||||
internal sealed record LogSummary(int Files, long Lines, int Warnings, int Errors, bool Truncated, IReadOnlyList<LogGroup> Groups);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Diagnostics.Metrics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// The outbound HTTP calls of one destination over a stretch of time (issue #95): how many, how many failed and how,
|
||||
/// and how long they took, in fixed buckets so that stretches can be added together without keeping every call.
|
||||
/// </summary>
|
||||
public sealed record HttpCallStats(string Host, long Calls, long Failures, IReadOnlyDictionary<string, long> Outcomes, long[] Buckets, double MaxMs, double TotalMs)
|
||||
{
|
||||
/// <summary>Upper bounds in milliseconds of the duration buckets; one more bucket holds everything slower.</summary>
|
||||
public static IReadOnlyList<double> Bounds { get; } = [5, 10, 20, 30, 50, 75, 100, 150, 200, 250, 300, 400, 500, 750, 1000, 1500, 2000, 3000, 5000, 10000, 20000, 30000, 60000];
|
||||
|
||||
public double AverageMs => Calls == 0 ? 0 : TotalMs / Calls;
|
||||
|
||||
/// <summary>
|
||||
/// The duration under which a share <paramref name="q"/> of the calls finished, read from the buckets: the upper
|
||||
/// bound of the bucket where that share is reached, never more than the slowest call.
|
||||
/// </summary>
|
||||
public double Percentile(double q)
|
||||
{
|
||||
var total = Buckets.Sum();
|
||||
if (total == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var rank = Math.Max(1, (long)Math.Ceiling(q * total));
|
||||
long seen = 0;
|
||||
for (var i = 0; i < Buckets.Length; i++)
|
||||
{
|
||||
seen += Buckets[i];
|
||||
if (seen >= rank)
|
||||
{
|
||||
return i < Bounds.Count ? Math.Min(Bounds[i], MaxMs) : MaxMs;
|
||||
}
|
||||
}
|
||||
|
||||
return MaxMs;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<HttpCallStats> Merge(IEnumerable<HttpCallStats> stats)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stats);
|
||||
return stats.GroupBy(s => s.Host, StringComparer.Ordinal).Select(g =>
|
||||
{
|
||||
var buckets = new long[Bounds.Count + 1];
|
||||
var outcomes = new SortedDictionary<string, long>(StringComparer.Ordinal);
|
||||
foreach (var s in g)
|
||||
{
|
||||
for (var i = 0; i < Math.Min(buckets.Length, s.Buckets.Length); i++)
|
||||
{
|
||||
buckets[i] += s.Buckets[i];
|
||||
}
|
||||
|
||||
foreach (var (outcome, count) in s.Outcomes)
|
||||
{
|
||||
outcomes[outcome] = outcomes.GetValueOrDefault(outcome) + count;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpCallStats(g.Key, g.Sum(s => s.Calls), g.Sum(s => s.Failures), outcomes, buckets, g.Max(s => s.MaxMs), g.Sum(s => s.TotalMs));
|
||||
}).OrderByDescending(s => s.Calls).ThenBy(s => s.Host, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
internal static int Bucket(double milliseconds)
|
||||
{
|
||||
for (var i = 0; i < Bounds.Count; i++)
|
||||
{
|
||||
if (milliseconds <= Bounds[i])
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return Bounds.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Listens to the duration that .NET records for every outbound HTTP request (meter <c>System.Net.Http</c>,
|
||||
/// instrument <c>http.client.request.duration</c>) and adds it up by destination until <see cref="Take"/>. No
|
||||
/// package and no change to the brokers' clients: every <see cref="HttpClient"/> of the process is measured.
|
||||
/// </summary>
|
||||
public sealed class HttpCallMeter : IDisposable
|
||||
{
|
||||
public const string MeterName = "System.Net.Http";
|
||||
public const string InstrumentName = "http.client.request.duration";
|
||||
|
||||
private static readonly Lazy<HttpCallMeter> _shared = new(() => new HttpCallMeter());
|
||||
|
||||
private readonly MeterListener _listener = new();
|
||||
private readonly Lock _gate = new();
|
||||
private Dictionary<string, Tally> _tallies = new(StringComparer.Ordinal);
|
||||
|
||||
public HttpCallMeter()
|
||||
{
|
||||
_listener.InstrumentPublished = (instrument, listener) =>
|
||||
{
|
||||
if (instrument.Meter.Name == MeterName && instrument.Name == InstrumentName)
|
||||
{
|
||||
listener.EnableMeasurementEvents(instrument);
|
||||
}
|
||||
};
|
||||
_listener.SetMeasurementEventCallback<double>(OnMeasurement);
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
/// <summary>The one meter of the running bot, started at the first use.</summary>
|
||||
public static HttpCallMeter Shared => _shared.Value;
|
||||
|
||||
/// <summary>The calls since the previous call to this method, by destination; the counts start again from zero.</summary>
|
||||
public IReadOnlyList<HttpCallStats> Take()
|
||||
{
|
||||
Dictionary<string, Tally> taken;
|
||||
lock (_gate)
|
||||
{
|
||||
taken = _tallies;
|
||||
_tallies = new Dictionary<string, Tally>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
return taken.Select(t => t.Value.Stats(t.Key)).OrderBy(s => s.Host, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
public void Dispose() => _listener.Dispose();
|
||||
|
||||
private void OnMeasurement(Instrument instrument, double seconds, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
|
||||
{
|
||||
string? host = null;
|
||||
int? port = null;
|
||||
int? status = null;
|
||||
string? error = null;
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
switch (tag.Key)
|
||||
{
|
||||
case "server.address":
|
||||
host = tag.Value?.ToString();
|
||||
break;
|
||||
case "server.port":
|
||||
port = tag.Value is null ? null : Convert.ToInt32(tag.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case "http.response.status_code":
|
||||
status = tag.Value is null ? null : Convert.ToInt32(tag.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case "error.type":
|
||||
error = tag.Value?.ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var key = (host ?? "?") + (port is { } p and not (80 or 443) ? ":" + p.ToString(CultureInfo.InvariantCulture) : "");
|
||||
var outcome = status?.ToString(CultureInfo.InvariantCulture) ?? error ?? "?";
|
||||
// 101 is the answer that opens a WebSocket: a success like 2xx and 3xx.
|
||||
var failed = status is not (>= 100 and < 400);
|
||||
var milliseconds = Math.Max(0, seconds * 1000);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_tallies.TryGetValue(key, out var tally))
|
||||
{
|
||||
tally = new Tally();
|
||||
_tallies[key] = tally;
|
||||
}
|
||||
|
||||
tally.Add(outcome, failed, milliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
private readonly long[] _buckets = new long[HttpCallStats.Bounds.Count + 1];
|
||||
private readonly SortedDictionary<string, long> _outcomes = new(StringComparer.Ordinal);
|
||||
private long _calls;
|
||||
private long _failures;
|
||||
private double _max;
|
||||
private double _total;
|
||||
|
||||
public void Add(string outcome, bool failed, double milliseconds)
|
||||
{
|
||||
_calls++;
|
||||
if (failed)
|
||||
{
|
||||
_failures++;
|
||||
}
|
||||
|
||||
_outcomes[outcome] = _outcomes.GetValueOrDefault(outcome) + 1;
|
||||
_buckets[HttpCallStats.Bucket(milliseconds)]++;
|
||||
_max = Math.Max(_max, milliseconds);
|
||||
_total += milliseconds;
|
||||
}
|
||||
|
||||
public HttpCallStats Stats(string host) => new(host, _calls, _failures, new SortedDictionary<string, long>(_outcomes, StringComparer.Ordinal),
|
||||
(long[])_buckets.Clone(), Math.Round(_max, 1), Math.Round(_total, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>One article as a feed gives it, before cleaning and grouping (SPEC 10.2, point 1).</summary>
|
||||
public sealed record FeedItem(string Title, string Link)
|
||||
{
|
||||
public string? Summary { get; init; }
|
||||
|
||||
public DateTimeOffset? PublishedAt { get; init; }
|
||||
|
||||
/// <summary>The language of the feed (<c>en</c>, <c>it</c>), when it says.</summary>
|
||||
public string? Language { get; init; }
|
||||
|
||||
/// <summary>Symbols the source attaches to the article (Alpaca News does; feeds do not).</summary>
|
||||
public IReadOnlyList<string> Symbols { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads RSS 2.0, RSS 1.0 and Atom with the framework's XML reader, without external components. A document type
|
||||
/// declaration is ignored and nothing is ever downloaded from inside a feed: its text is untrusted data.
|
||||
/// </summary>
|
||||
public static partial class FeedParser
|
||||
{
|
||||
public const int MaxSummary = 600;
|
||||
|
||||
private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom";
|
||||
private static readonly XNamespace Rss1 = "http://purl.org/rss/1.0/";
|
||||
private static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/";
|
||||
|
||||
/// <summary>The articles of a feed; a document that is not a feed gives a <see cref="FormatException"/>.</summary>
|
||||
public static IReadOnlyList<FeedItem> Parse(Stream content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var settings = new XmlReaderSettings
|
||||
{
|
||||
DtdProcessing = DtdProcessing.Ignore,
|
||||
XmlResolver = null,
|
||||
MaxCharactersFromEntities = 1024,
|
||||
MaxCharactersInDocument = 20_000_000,
|
||||
IgnoreComments = true,
|
||||
};
|
||||
XDocument document;
|
||||
try
|
||||
{
|
||||
using var reader = XmlReader.Create(content, settings);
|
||||
document = XDocument.Load(reader);
|
||||
}
|
||||
catch (XmlException ex)
|
||||
{
|
||||
throw new FormatException("Il feed non è XML valido: " + ex.Message, ex);
|
||||
}
|
||||
|
||||
var root = document.Root ?? throw new FormatException("Il feed è vuoto.");
|
||||
var language = Language(root.Element("channel")?.Element("language")?.Value ?? root.Attribute(XNamespace.Xml + "lang")?.Value
|
||||
?? root.Element(Rss1 + "channel")?.Element(Dc + "language")?.Value);
|
||||
IEnumerable<FeedItem?> items = root.Name.LocalName switch
|
||||
{
|
||||
"rss" => root.Element("channel")?.Elements("item").Select(Rss) ?? [],
|
||||
"RDF" => root.Elements(Rss1 + "item").Select(RdfItem),
|
||||
"feed" when root.Name.Namespace == Atom => root.Elements(Atom + "entry").Select(AtomEntry),
|
||||
_ => throw new FormatException("Formato di feed sconosciuto: " + root.Name.LocalName),
|
||||
};
|
||||
return items.OfType<FeedItem>().Select(i => i with { Language = i.Language ?? language }).ToList();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<FeedItem> Parse(byte[] content) => Parse(new MemoryStream(content ?? throw new ArgumentNullException(nameof(content))));
|
||||
|
||||
private static FeedItem? Rss(XElement item)
|
||||
{
|
||||
var link = item.Element("link")?.Value.Trim();
|
||||
if (string.IsNullOrEmpty(link) && item.Element("guid") is { } guid && guid.Attribute("isPermaLink")?.Value != "false")
|
||||
{
|
||||
link = guid.Value.Trim();
|
||||
}
|
||||
|
||||
return Make(item.Element("title")?.Value, link, item.Element("description")?.Value,
|
||||
item.Element("pubDate")?.Value ?? item.Element(Dc + "date")?.Value, item.Element(Dc + "language")?.Value);
|
||||
}
|
||||
|
||||
private static FeedItem? RdfItem(XElement item) =>
|
||||
Make(item.Element(Rss1 + "title")?.Value, item.Element(Rss1 + "link")?.Value ?? item.Attribute(XName.Get("about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))?.Value,
|
||||
item.Element(Rss1 + "description")?.Value, item.Element(Dc + "date")?.Value, item.Element(Dc + "language")?.Value);
|
||||
|
||||
private static FeedItem? AtomEntry(XElement entry)
|
||||
{
|
||||
var links = entry.Elements(Atom + "link").ToList();
|
||||
var link = links.FirstOrDefault(l => (l.Attribute("rel")?.Value ?? "alternate") == "alternate") ?? links.FirstOrDefault();
|
||||
return Make(entry.Element(Atom + "title")?.Value, link?.Attribute("href")?.Value, entry.Element(Atom + "summary")?.Value ?? entry.Element(Atom + "content")?.Value,
|
||||
entry.Element(Atom + "published")?.Value ?? entry.Element(Atom + "updated")?.Value, entry.Attribute(XNamespace.Xml + "lang")?.Value);
|
||||
}
|
||||
|
||||
private static FeedItem? Make(string? title, string? link, string? summary, string? published, string? language)
|
||||
{
|
||||
var cleanTitle = Text(title, 300);
|
||||
if (cleanTitle is null || string.IsNullOrWhiteSpace(link) || !Uri.TryCreate(link.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FeedItem(cleanTitle, uri.AbsoluteUri)
|
||||
{
|
||||
Summary = Text(summary, MaxSummary),
|
||||
PublishedAt = NewsDates.TryParse(published, out var at) ? at : null,
|
||||
Language = Language(language),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Plain text from a feed field: tags out, entities decoded (twice, some feeds encode them twice), spaces collapsed.</summary>
|
||||
public static string? Text(string? html, int max)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(html))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var text = WebUtility.HtmlDecode(Tags().Replace(WebUtility.HtmlDecode(Tags().Replace(html, " ")), " "));
|
||||
text = Spaces().Replace(text, " ").Trim();
|
||||
if (text.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return text.Length <= max ? text : text[..(max - 1)].TrimEnd() + "…";
|
||||
}
|
||||
|
||||
private static string? Language(string? code) =>
|
||||
string.IsNullOrWhiteSpace(code) ? null : code.Trim()[..Math.Min(2, code.Trim().Length)].ToLowerInvariant();
|
||||
|
||||
[GeneratedRegex("<[^>]*>")]
|
||||
private static partial Regex Tags();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Spaces();
|
||||
}
|
||||
|
||||
/// <summary>The dates of the feeds: RFC 822 with any zone form (GMT, Z, +0100, EST), ISO 8601, or a bare time taken as UTC.</summary>
|
||||
public static partial class NewsDates
|
||||
{
|
||||
private static readonly string[] Formats =
|
||||
[
|
||||
"ddd, d MMM yyyy HH:mm:ss zzz", "ddd, d MMM yyyy HH:mm zzz", "d MMM yyyy HH:mm:ss zzz", "d MMM yyyy HH:mm zzz",
|
||||
"ddd, dd MMM yyyy HH:mm:ss zzz", "dddd, d MMMM yyyy HH:mm:ss zzz",
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, string> Zones = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["GMT"] = "+00:00",
|
||||
["UT"] = "+00:00",
|
||||
["UTC"] = "+00:00",
|
||||
["Z"] = "+00:00",
|
||||
["EST"] = "-05:00",
|
||||
["EDT"] = "-04:00",
|
||||
["CST"] = "-06:00",
|
||||
["CDT"] = "-05:00",
|
||||
["MST"] = "-07:00",
|
||||
["MDT"] = "-06:00",
|
||||
["PST"] = "-08:00",
|
||||
["PDT"] = "-07:00",
|
||||
["CET"] = "+01:00",
|
||||
["CEST"] = "+02:00",
|
||||
["BST"] = "+01:00",
|
||||
};
|
||||
|
||||
public static bool TryParse(string? text, out DateTimeOffset moment)
|
||||
{
|
||||
moment = default;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var value = Spaces().Replace(text.Trim(), " ");
|
||||
var rfc = ZoneAtEnd().Match(value);
|
||||
if (rfc.Success)
|
||||
{
|
||||
var zone = rfc.Groups["zone"].Value;
|
||||
var offset = Zones.TryGetValue(zone, out var named) ? named
|
||||
: zone.Length == 5 ? zone[..3] + ":" + zone[3..] : zone;
|
||||
if (DateTimeOffset.TryParseExact(value[..rfc.Index] + " " + offset, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out moment))
|
||||
{
|
||||
moment = moment.ToUniversalTime();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out moment))
|
||||
{
|
||||
moment = moment.ToUniversalTime();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\s(?<zone>[+-]\d{2}:?\d{2}|[A-Za-z]{1,4})$")]
|
||||
private static partial Regex ZoneAtEnd();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Spaces();
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>The serious cases of SPEC 10.2 point 4, found by keywords in English and in Italian.</summary>
|
||||
public static class SevereKinds
|
||||
{
|
||||
public const string Cyberattack = "cyberattack";
|
||||
public const string Suspension = "suspension";
|
||||
public const string Fraud = "fraud";
|
||||
public const string Bankruptcy = "bankruptcy";
|
||||
public const string Investigation = "investigation";
|
||||
public const string Delisting = "delisting";
|
||||
}
|
||||
|
||||
/// <summary>The five grades of tone of SPEC 10.2 point 4.</summary>
|
||||
public enum Tone
|
||||
{
|
||||
Negative = -2,
|
||||
SlightlyNegative = -1,
|
||||
Neutral = 0,
|
||||
SlightlyPositive = 1,
|
||||
Positive = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the local classifier says of an English text: the probabilities of its three classes.</summary>
|
||||
public sealed record ToneScore(double Positive, double Negative, double Neutral)
|
||||
{
|
||||
/// <summary>The score of 10.2: probability of positive minus probability of negative, from −1 to +1.</summary>
|
||||
public double Score => Positive - Negative;
|
||||
}
|
||||
|
||||
/// <summary>The local classifier of SPEC 4.5. It reads only English; for other texts the caller does not ask.</summary>
|
||||
public interface IToneClassifier
|
||||
{
|
||||
ToneScore Classify(string text);
|
||||
}
|
||||
|
||||
/// <summary>The first judgement of an article: tone, serious case and importance, all without a language model.</summary>
|
||||
public sealed record NewsJudgement(double? Score, string? Severe, int Importance)
|
||||
{
|
||||
public Tone? Tone => Score is { } s ? NewsJudge.Grade(s) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first judgement of SPEC 10.2 point 4, local and free. The tone comes from the classifier for English texts;
|
||||
/// the serious cases from keywords in two languages, so an Italian title of a fraud is still a serious case.
|
||||
/// Importance: 4 to the serious cases, 3 to a negative article (score up to −0.6), 2 to the others linked to an
|
||||
/// instrument, 1 to the rest. The 5 is given only by the language model (#58); a calendar event (3) arrives with #59.
|
||||
/// </summary>
|
||||
public static partial class NewsJudge
|
||||
{
|
||||
// Lower case, words separated by single spaces. A phrase matches whole words only: "hacked" is not "hack".
|
||||
private static readonly (string Kind, string[] Phrases)[] Keywords =
|
||||
[
|
||||
(SevereKinds.Cyberattack,
|
||||
[
|
||||
"hack", "hacked", "hacker", "hackers", "hacking", "cyberattack", "cyber attack", "cyberattacks", "ransomware", "data breach", "security breach",
|
||||
"exploit", "exploited", "drained", "attacco informatico", "attacchi informatici", "attacco hacker", "violazione dei dati",
|
||||
]),
|
||||
(SevereKinds.Suspension,
|
||||
[
|
||||
"trading halt", "trading halted", "halts trading", "halted trading", "suspends trading", "trading suspended", "suspended from trading",
|
||||
"halts withdrawals", "halted withdrawals", "suspends withdrawals", "withdrawals halted", "withdrawals suspended", "pauses withdrawals",
|
||||
"sospeso dalle negoziazioni", "sospensione delle negoziazioni", "sospende le negoziazioni", "titolo sospeso", "sospende i prelievi",
|
||||
"sospensione dei prelievi", "blocca i prelievi",
|
||||
]),
|
||||
(SevereKinds.Fraud,
|
||||
[
|
||||
"fraud", "frauds", "fraudulent", "ponzi", "embezzlement", "accounting irregularities", "frode", "frodi", "truffa", "falso in bilancio",
|
||||
"irregolarità contabili",
|
||||
]),
|
||||
(SevereKinds.Bankruptcy,
|
||||
[
|
||||
"bankruptcy", "bankrupt", "chapter 11", "insolvency", "insolvent", "files for bankruptcy", "fallimento", "bancarotta", "insolvenza",
|
||||
"insolvente", "concordato preventivo", "amministrazione straordinaria",
|
||||
]),
|
||||
(SevereKinds.Investigation,
|
||||
[
|
||||
"investigation", "investigations", "probe", "probes", "subpoena", "subpoenaed", "indicted", "indictment", "charged with", "sec charges",
|
||||
"raided", "indagine", "indagini", "indagato", "indagati", "inchiesta", "perquisizione", "perquisizioni",
|
||||
]),
|
||||
(SevereKinds.Delisting,
|
||||
[
|
||||
"delist", "delisted", "delisting", "delistings", "revoca dalla quotazione", "esclusione dalle negoziazioni",
|
||||
]),
|
||||
];
|
||||
|
||||
/// <summary>The grade of a score, with the bounds of 10.2: up to −0.6, −0.2, +0.2, +0.6, then positive.</summary>
|
||||
public static Tone Grade(double score) => score switch
|
||||
{
|
||||
<= -0.6 => Tone.Negative,
|
||||
<= -0.2 => Tone.SlightlyNegative,
|
||||
<= 0.2 => Tone.Neutral,
|
||||
<= 0.6 => Tone.SlightlyPositive,
|
||||
_ => Tone.Positive,
|
||||
};
|
||||
|
||||
/// <summary>The first serious case named by the text, in the order of 10.2, or null.</summary>
|
||||
public static string? Severe(string title, string? summary)
|
||||
{
|
||||
var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant().Replace('’', '\''), " "), " ") + " ";
|
||||
foreach (var (kind, phrases) in Keywords)
|
||||
{
|
||||
if (phrases.Any(p => text.Contains(" " + p + " ", StringComparison.Ordinal)))
|
||||
{
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The judgement of one article. The classifier is asked only for English and only when it exists.</summary>
|
||||
public static NewsJudgement Judge(string title, string? summary, string language, bool linkedToInstrument, IToneClassifier? classifier)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(title);
|
||||
double? score = classifier is not null && language == "en" ? Math.Clamp(classifier.Classify(title).Score, -1, 1) : null;
|
||||
var severe = Severe(title, summary);
|
||||
var importance = severe is not null ? 4 : score <= -0.6 ? 3 : linkedToInstrument ? 2 : 1;
|
||||
return new NewsJudgement(score, severe, importance);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}']+")]
|
||||
private static partial Regex NonWord();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Spaces();
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
public static class LinkScopes
|
||||
{
|
||||
/// <summary>One instrument, as <c>venue:symbol</c>.</summary>
|
||||
public const string Instrument = "instrument";
|
||||
|
||||
/// <summary>A class of instruments: <see cref="AssetClasses.Crypto"/> or <see cref="AssetClasses.Equity"/>.</summary>
|
||||
public const string Class = "class";
|
||||
|
||||
/// <summary>The market in general: central banks, inflation, rates.</summary>
|
||||
public const string Market = "market";
|
||||
}
|
||||
|
||||
public static class LinkVia
|
||||
{
|
||||
public const string Source = "source";
|
||||
public const string Ticker = "ticker";
|
||||
public const string Name = "name";
|
||||
public const string Theme = "theme";
|
||||
public const string Topic = "topic";
|
||||
}
|
||||
|
||||
/// <summary>What a story is about (SPEC 10.2, point 3).</summary>
|
||||
public sealed record NewsLink(string Scope, string Target, string Via);
|
||||
|
||||
/// <summary>
|
||||
/// The dictionary of 10.2, point 3: tickers and names of the instruments in the catalogue, names of the coins, and the
|
||||
/// themes that concern a whole class or the market. A name is matched only where the text writes it with a capital
|
||||
/// letter, and a name that is also a common word (Target, Block, Gap) needs its ticker: a wrong link would block an
|
||||
/// instrument for nothing.
|
||||
/// </summary>
|
||||
public sealed partial class NewsLinker
|
||||
{
|
||||
private static readonly Dictionary<string, string> CoinNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Bitcoin"] = "BTC",
|
||||
["Ether"] = "ETH",
|
||||
["Ethereum"] = "ETH",
|
||||
["Solana"] = "SOL",
|
||||
["XRP"] = "XRP",
|
||||
["Ripple"] = "XRP",
|
||||
["Cardano"] = "ADA",
|
||||
["Dogecoin"] = "DOGE",
|
||||
["Polkadot"] = "DOT",
|
||||
["Chainlink"] = "LINK",
|
||||
["Litecoin"] = "LTC",
|
||||
["Avalanche"] = "AVAX",
|
||||
["Tron"] = "TRX",
|
||||
["Toncoin"] = "TON",
|
||||
["Stellar"] = "XLM",
|
||||
["Uniswap"] = "UNI",
|
||||
["Polygon"] = "POL",
|
||||
["Aave"] = "AAVE",
|
||||
["Tether"] = "USDT",
|
||||
["USDC"] = "USDC",
|
||||
["Shiba Inu"] = "SHIB",
|
||||
["Sui"] = "SUI",
|
||||
["Hedera"] = "HBAR",
|
||||
["Near Protocol"] = "NEAR",
|
||||
["Cosmos"] = "ATOM",
|
||||
["Arbitrum"] = "ARB",
|
||||
};
|
||||
|
||||
// Words of a theme, lower case: one of them in a title or summary links the story to the class or to the market.
|
||||
private static readonly (string Scope, string Target, string[] Words)[] Themes =
|
||||
[
|
||||
(LinkScopes.Market, LinkScopes.Market,
|
||||
[
|
||||
"federal reserve", "fed", "fomc", "powell", "ecb", "bce", "banca centrale europea", "lagarde", "inflation", "inflazione", "cpi", "pce",
|
||||
"payrolls", "nonfarm", "jobs report", "interest rate", "interest rates", "rate cut", "rate hike", "tassi", "recession", "recessione", "tariffs",
|
||||
"tariff", "dazi", "treasury yields", "bond yields", "gdp", "pil",
|
||||
]),
|
||||
(LinkScopes.Class, AssetClasses.Crypto,
|
||||
[
|
||||
"crypto", "cryptocurrency", "cryptocurrencies", "criptovalute", "criptovaluta", "stablecoin", "stablecoins", "defi", "blockchain", "altcoin", "altcoins",
|
||||
]),
|
||||
(LinkScopes.Class, AssetClasses.Equity, ["wall street", "s&p 500", "nasdaq", "dow jones", "stock market", "borsa di new york", "russell 2000"]),
|
||||
];
|
||||
|
||||
// Names that are also ordinary words: without a ticker they say nothing.
|
||||
private static readonly HashSet<string> Ambiguous = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Target", "Block", "Gap", "Match", "Shift", "Live", "Snap", "Square", "Sea", "Box", "Zoom", "Open", "Best", "General", "First", "United",
|
||||
"American", "National", "International", "Global", "Digital", "Energy", "Public", "Real", "Apple Hospitality", "Visa", "Ford", "Delta",
|
||||
"Southern", "Dominion", "Progressive", "Equity", "Union", "Pioneer", "Alliance", "Carrier", "Discovery", "Hub", "Fox", "Coach", "Ball", "Cars",
|
||||
"Opendoor", "Strategy", "Bank", "Group", "Holdings", "Trust", "Capital", "Partners", "Fund", "Index", "Arm", "Unity", "Nu", "Rent", "Lumen",
|
||||
};
|
||||
|
||||
private static readonly string[] NameEndings =
|
||||
[
|
||||
" Common Stock", " Class A", " Class B", " Class C", " Ordinary Shares", " American Depositary", " Depositary", " ADS", " ADR", " Units", " Warrant",
|
||||
];
|
||||
|
||||
private static readonly string[] Suffixes =
|
||||
[
|
||||
", Inc.", " Inc.", " Inc", ", Inc", " Incorporated", " Corporation", " Corp.", " Corp", " Company", " Co.", " Holdings", " Holding", " Group",
|
||||
" Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com",
|
||||
];
|
||||
|
||||
private readonly Dictionary<string, string> _equityTickers = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, List<string>> _coins = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, List<(string[] Words, string Target)>> _names = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private NewsLinker()
|
||||
{
|
||||
}
|
||||
|
||||
public int Names => _names.Sum(n => n.Value.Count);
|
||||
|
||||
/// <summary>The dictionary of the instruments the bot knows: stocks of Alpaca and coins of OKX.</summary>
|
||||
public static NewsLinker Build(IEnumerable<InstrumentSpec> instruments)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instruments);
|
||||
var dictionary = new NewsLinker();
|
||||
foreach (var spec in instruments)
|
||||
{
|
||||
var target = spec.Venue + ":" + spec.Symbol;
|
||||
if (spec.AssetClass == AssetClasses.Crypto)
|
||||
{
|
||||
var coin = (spec.BaseCurrency ?? spec.Symbol.Split('-', '/')[0]).ToUpperInvariant();
|
||||
if (!dictionary._coins.TryGetValue(coin, out var list))
|
||||
{
|
||||
dictionary._coins[coin] = list = [];
|
||||
}
|
||||
|
||||
list.Add(target);
|
||||
}
|
||||
else if (spec.AssetClass == AssetClasses.Equity && spec.IsFund != true)
|
||||
{
|
||||
dictionary._equityTickers.TryAdd(spec.Symbol.ToUpperInvariant(), target);
|
||||
if (CompanyName(spec.Name) is { } name)
|
||||
{
|
||||
dictionary.AddName(name, target);
|
||||
if (name.EndsWith(".com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
dictionary.AddName(name[..^4], target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (name, coin) in CoinNames)
|
||||
{
|
||||
if (dictionary._coins.TryGetValue(coin, out var targets))
|
||||
{
|
||||
foreach (var target in targets)
|
||||
{
|
||||
dictionary.AddName(name, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
/// <summary>"Apple Inc. Common Stock" → "Apple"; null when what remains is too short or an ordinary word.</summary>
|
||||
public static string? CompanyName(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var clean = name.Trim();
|
||||
foreach (var ending in NameEndings)
|
||||
{
|
||||
var at = clean.IndexOf(ending, StringComparison.OrdinalIgnoreCase);
|
||||
if (at > 0)
|
||||
{
|
||||
clean = clean[..at];
|
||||
}
|
||||
}
|
||||
|
||||
for (var changed = true; changed;)
|
||||
{
|
||||
changed = false;
|
||||
foreach (var suffix in Suffixes)
|
||||
{
|
||||
if (suffix != ".com" && clean.EndsWith(suffix, StringComparison.Ordinal) && clean.Length > suffix.Length + 1)
|
||||
{
|
||||
clean = clean[..^suffix.Length].TrimEnd();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return clean.Length < 3 || Ambiguous.Contains(clean) ? null : clean;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The links of one article. Without any link to an instrument, a class or the market, the topic of the source
|
||||
/// (if it has one) stands for the article.
|
||||
/// </summary>
|
||||
public IReadOnlyList<NewsLink> Link(string title, string? summary, IEnumerable<string>? sourceSymbols = null, string? topic = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(title);
|
||||
var links = new List<NewsLink>();
|
||||
void Add(string scope, string target, string via)
|
||||
{
|
||||
if (!links.Any(l => l.Scope == scope && l.Target == target))
|
||||
{
|
||||
links.Add(new NewsLink(scope, target, via));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var symbol in sourceSymbols ?? [])
|
||||
{
|
||||
var upper = symbol.Trim().ToUpperInvariant();
|
||||
if (_equityTickers.TryGetValue(upper, out var stock))
|
||||
{
|
||||
Add(LinkScopes.Instrument, stock, LinkVia.Source);
|
||||
}
|
||||
else if (_coins.TryGetValue(upper.Split('-', '/')[0].Replace("USD", "", StringComparison.Ordinal), out var coins))
|
||||
{
|
||||
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Source));
|
||||
}
|
||||
}
|
||||
|
||||
var text = title + " " + (summary ?? "");
|
||||
foreach (Match match in Cashtag().Matches(text).Concat(ExchangeTicker().Matches(text)))
|
||||
{
|
||||
var ticker = match.Groups["t"].Value;
|
||||
if (_equityTickers.TryGetValue(ticker, out var stock))
|
||||
{
|
||||
Add(LinkScopes.Instrument, stock, LinkVia.Ticker);
|
||||
}
|
||||
else if (_coins.TryGetValue(ticker, out var coins))
|
||||
{
|
||||
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
|
||||
}
|
||||
}
|
||||
|
||||
var words = Words().Matches(text).Select(m => Possessive().Replace(m.Value, "").TrimEnd('.')).Where(w => w.Length > 0).ToList();
|
||||
for (var i = 0; i < words.Count; i++)
|
||||
{
|
||||
// A coin's ticker in capitals (BTC, ETH, SOL) is a link: news write them that way.
|
||||
if (words[i].Length >= 3 && words[i].All(char.IsUpper) && _coins.TryGetValue(words[i], out var coins))
|
||||
{
|
||||
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
|
||||
}
|
||||
|
||||
if (!char.IsUpper(words[i][0]) || !_names.TryGetValue(words[i], out var candidates))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var (nameWords, target) in candidates.OrderByDescending(c => c.Words.Length))
|
||||
{
|
||||
if (i + nameWords.Length <= words.Count
|
||||
&& nameWords.Select((w, k) => string.Equals(w, words[i + k], StringComparison.OrdinalIgnoreCase)).All(x => x))
|
||||
{
|
||||
Add(LinkScopes.Instrument, target, LinkVia.Name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "(NASDAQ: AAPL)" names the listing of one company, not the stock market as a whole.
|
||||
var themed = ExchangeTicker().Replace(text, " ");
|
||||
var lower = " " + Spaces().Replace(NonWord().Replace(themed.ToLowerInvariant(), " "), " ") + " ";
|
||||
foreach (var (scope, target, themeWords) in Themes)
|
||||
{
|
||||
if (themeWords.Any(w => lower.Contains(" " + w + " ", StringComparison.Ordinal)))
|
||||
{
|
||||
Add(scope, target, LinkVia.Theme);
|
||||
}
|
||||
}
|
||||
|
||||
if (links.Count == 0 && topic is { Length: > 0 })
|
||||
{
|
||||
links.Add(topic == LinkScopes.Market ? new NewsLink(LinkScopes.Market, LinkScopes.Market, LinkVia.Topic) : new NewsLink(LinkScopes.Class, topic, LinkVia.Topic));
|
||||
}
|
||||
|
||||
return links;
|
||||
}
|
||||
|
||||
private void AddName(string name, string target)
|
||||
{
|
||||
var words = Words().Matches(name).Select(m => m.Value.TrimEnd('.')).Where(w => w.Length > 0).ToArray();
|
||||
if (words.Length == 0 || (words.Length == 1 && (words[0].Length < 3 || Ambiguous.Contains(words[0]))))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_names.TryGetValue(words[0], out var list))
|
||||
{
|
||||
_names[words[0]] = list = [];
|
||||
}
|
||||
|
||||
if (!list.Any(l => l.Target == target && l.Words.SequenceEqual(words, StringComparer.OrdinalIgnoreCase)))
|
||||
{
|
||||
list.Add((words, target));
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\$(?<t>[A-Z]{1,6})\b")]
|
||||
private static partial Regex Cashtag();
|
||||
|
||||
[GeneratedRegex(@"\((?:NASDAQ|Nasdaq|NYSE|NYSE American|NYSE Arca|AMEX|Cboe|OTC)\s*:\s*(?<t>[A-Z][A-Z.]{0,5})\)")]
|
||||
private static partial Regex ExchangeTicker();
|
||||
|
||||
[GeneratedRegex(@"[\p{L}\p{N}][\p{L}\p{N}&'.\-]*")]
|
||||
private static partial Regex Words();
|
||||
|
||||
[GeneratedRegex(@"['’]s$")]
|
||||
private static partial Regex Possessive();
|
||||
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}&]+")]
|
||||
private static partial Regex NonWord();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Spaces();
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>
|
||||
/// The cleaning and grouping of 10.2, point 2: the same article is recognised by its address, the same story told by
|
||||
/// two newspapers by the words of the titles, and two feeds of the same newspaper are one publisher, not two.
|
||||
/// </summary>
|
||||
public static class NewsMatching
|
||||
{
|
||||
/// <summary>Two titles share at least this part of their words (Jaccard): the same story.</summary>
|
||||
public const double SameStory = 0.5;
|
||||
|
||||
/// <summary>Or the shorter title is almost all inside the longer one.</summary>
|
||||
public const double Contained = 0.8;
|
||||
|
||||
/// <summary>Retellings of a story arrive within two days of the first article; later ones are a new story.</summary>
|
||||
public static readonly TimeSpan StoryWindow = TimeSpan.FromHours(48);
|
||||
|
||||
// Parameters that only say where the reader came from: they never change the article.
|
||||
private static readonly string[] TrackingPrefixes = ["utm_", "mc_", "at_", "pk_", "ga_"];
|
||||
|
||||
private static readonly HashSet<string> TrackingNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"ref", "src", "source", "cmpid", "mod", "fbclid", "gclid", "dclid", "msclkid", "ito", "taid", "mbid", "trk", "partnerid", "yptr", "guccounter",
|
||||
"rss", "feed", "output", "cid",
|
||||
};
|
||||
|
||||
// Short words of English and Italian that say nothing about which story it is.
|
||||
private static readonly HashSet<string> StopWords = new(StringComparer.Ordinal)
|
||||
{
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "have", "in", "into", "is", "it", "its", "of", "on", "or", "over",
|
||||
"says", "say", "said", "the", "to", "up", "was", "were", "will", "with", "after", "amid", "new", "this", "that", "what", "why", "how",
|
||||
"il", "lo", "la", "i", "gli", "le", "un", "uno", "una", "di", "del", "della", "dei", "delle", "da", "dal", "dalla", "in", "nel", "nella", "su",
|
||||
"sul", "sulla", "per", "con", "tra", "fra", "e", "ed", "o", "che", "non", "si", "al", "alla", "ai", "alle", "come", "piu", "anche", "ma",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> SecondLevel = new(StringComparer.Ordinal) { "co", "com", "org", "net", "gov", "ac", "edu" };
|
||||
|
||||
/// <summary>
|
||||
/// The address without what does not change the article: scheme, <c>www.</c>, fragment, double slashes, a final
|
||||
/// slash and the tracking parameters. The remaining parameters are sorted.
|
||||
/// </summary>
|
||||
public static string UrlKey(string url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
if (!Uri.TryCreate(url.Trim(), UriKind.Absolute, out var uri))
|
||||
{
|
||||
return url.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
var host = Host(uri);
|
||||
var path = uri.AbsolutePath;
|
||||
while (path.Contains("//", StringComparison.Ordinal))
|
||||
{
|
||||
path = path.Replace("//", "/", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
if (path.Length > 1)
|
||||
{
|
||||
path = path.TrimEnd('/');
|
||||
}
|
||||
|
||||
var query = uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Where(p => p.Split('=', 2)[0] is var name && !TrackingNames.Contains(name) && !TrackingPrefixes.Any(t => name.StartsWith(t, StringComparison.OrdinalIgnoreCase)))
|
||||
.Order(StringComparer.Ordinal)
|
||||
.ToList();
|
||||
return host + path + (query.Count == 0 ? "" : "?" + string.Join('&', query));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Who published the article, from its address: the registrable domain, so <c>feeds.content.dowjones.io</c> giving
|
||||
/// an article of <c>www.marketwatch.com</c> is MarketWatch, and <c>news.example.co.uk</c> is <c>example.co.uk</c>.
|
||||
/// </summary>
|
||||
public static string Publisher(string url)
|
||||
{
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
return "?";
|
||||
}
|
||||
|
||||
var labels = Host(uri).Split('.');
|
||||
var take = labels.Length >= 3 && labels[^1].Length == 2 && SecondLevel.Contains(labels[^2]) ? 3 : 2;
|
||||
return string.Join('.', labels.TakeLast(Math.Min(take, labels.Length)));
|
||||
}
|
||||
|
||||
/// <summary>The words that tell the story: lower case, without accents and punctuation, without short common words.</summary>
|
||||
public static IReadOnlySet<string> Words(string title)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(title);
|
||||
var plain = new StringBuilder(title.Length);
|
||||
foreach (var c in title.Normalize(NormalizationForm.FormD))
|
||||
{
|
||||
var category = CharUnicodeInfo.GetUnicodeCategory(c);
|
||||
if (category == UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
plain.Append(char.IsLetterOrDigit(c) ? char.ToLowerInvariant(c) : ' ');
|
||||
}
|
||||
|
||||
return plain.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(w => w.Length > 3 && w.EndsWith('s') && !w.EndsWith("ss", StringComparison.Ordinal) ? w[..^1] : w)
|
||||
.Where(w => !StopWords.Contains(w) && (w.Length >= 2 || char.IsDigit(w[0])))
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The words of a title as stored: sorted and joined, so a story can be compared without the original title.</summary>
|
||||
public static string TitleKey(string title) => string.Join(' ', Words(title).Order(StringComparer.Ordinal));
|
||||
|
||||
public static IReadOnlySet<string> KeyWords(string titleKey) =>
|
||||
(titleKey ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Whether two titles tell the same story. Titles of fewer than three words must be equal: too few words make
|
||||
/// any two titles look alike.
|
||||
/// </summary>
|
||||
public static bool Similar(IReadOnlySet<string> a, IReadOnlySet<string> b)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(a);
|
||||
ArgumentNullException.ThrowIfNull(b);
|
||||
if (a.Count == 0 || b.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var common = a.Count(b.Contains);
|
||||
if (Math.Min(a.Count, b.Count) < 3)
|
||||
{
|
||||
return common == a.Count && common == b.Count;
|
||||
}
|
||||
|
||||
var jaccard = (double)common / (a.Count + b.Count - common);
|
||||
var contained = (double)common / Math.Min(a.Count, b.Count);
|
||||
return jaccard >= SameStory || (Math.Min(a.Count, b.Count) >= 4 && contained >= Contained);
|
||||
}
|
||||
|
||||
public static double Score(IReadOnlySet<string> a, IReadOnlySet<string> b)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(a);
|
||||
ArgumentNullException.ThrowIfNull(b);
|
||||
var common = a.Count(b.Contains);
|
||||
return a.Count + b.Count - common == 0 ? 0 : (double)common / (a.Count + b.Count - common);
|
||||
}
|
||||
|
||||
private static string Host(Uri uri)
|
||||
{
|
||||
var host = uri.Host.ToLowerInvariant();
|
||||
return host.StartsWith("www.", StringComparison.Ordinal) ? host[4..] : host;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# Tokenizer of the local news classifier
|
||||
|
||||
`vocab.json` and `merges.txt` are the byte-level BPE tokenizer of RoBERTa. They are used by the model
|
||||
`mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis` (Apache-2.0), as exported to ONNX in
|
||||
`Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`.
|
||||
|
||||
- Revision: `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`.
|
||||
- Downloaded on 2026-11-15 with the user's permission (SPEC 4.5, ADR 0004, ADR 0014).
|
||||
- SHA-256:
|
||||
- `vocab.json`: `ed19656ea1707df69134c4af35c8ceda2cc9860bf2c3495026153a133670ab5e`
|
||||
- `merges.txt`: `1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5`
|
||||
|
||||
They travel inside the DLL. The ONNX model itself, `onnx/model_quantized.onnx` (82,763,251 bytes, SHA-256
|
||||
`8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec`), is too large for the repository. The
|
||||
application downloads it once into the `models` folder of the data directory and checks its hash (`ToneModel`).
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
{"<s>":0,"<pad>":1,"</s>":2,"<unk>":3,".":4,"Ġthe":5,",":6,"Ġto":7,"Ġand":8,"Ġof":9,"Ġa":10,"Ġin":11,"-":12,"Ġfor":13,"Ġthat":14,"Ġon":15,"Ġis":16,"âĢ":17,"'s":18,"Ġwith":19,"ĠThe":20,"Ġwas":21,"Ġ\"":22,"Ġat":23,"Ġit":24,"Ġas":25,"Ġsaid":26,"Ļ":27,"Ġbe":28,"s":29,"Ġby":30,"Ġfrom":31,"Ġare":32,"Ġhave":33,"Ġhas":34,":":35,"Ġ(":36,"Ġhe":37,"ĠI":38,"Ġhis":39,"Ġwill":40,"Ġan":41,"Ġthis":42,")":43,"ĠâĢ":44,"Ġnot":45,"Ŀ":46,"Ġyou":47,"ľ":48,"Ġtheir":49,"Ġor":50,"Ġthey":51,"Ġwe":52,"Ġbut":53,"Ġwho":54,"Ġmore":55,"Ġhad":56,"Ġbeen":57,"Ġwere":58,"Ġabout":59,",\"":60,"Ġwhich":61,"Ġup":62,"Ġits":63,"Ġcan":64,"Ġone":65,"Ġout":66,"Ġalso":67,"Ġ$":68,"Ġher":69,"Ġall":70,"Ġafter":71,".\"":72,"/":73,"Ġwould":74,"'t":75,"Ġyear":76,"Ġwhen":77,"Ġfirst":78,"Ġshe":79,"Ġtwo":80,"Ġover":81,"Ġpeople":82,"ĠA":83,"Ġour":84,"ĠIt":85,"Ġtime":86,"Ġthan":87,"Ġinto":88,"Ġthere":89,"t":90,"ĠHe":91,"Ġnew":92,"ĠâĢĶ":93,"Ġlast":94,"Ġjust":95,"ĠIn":96,"Ġother":97,"Ġso":98,"Ġwhat":99,"I":100,"Ġlike":101,"a":102,"Ġsome":103,"S":104,"ë":105,"Ġthem":106,"Ġyears":107,"'":108,"Ġdo":109,"Ġyour":110,"Ġ-":111,"Ġ1":112,"\"":113,"Ġif":114,"Ġcould":115,"?":116,"Ġno":117,"i":118,"m":119,"Ġget":120,"ĠU":121,"Ġnow":122,"Ġhim":123,"Ġback":124,"ĠBut":125,"ĠâĢĵ":126,"Ġmy":127,"Ġ'":128,"Ġonly":129,"Ġthree":130,";":131,"Ġ2":132,"The":133,"1":134,"Ġpercent":135,"Ġagainst":136,"Ġbefore":137,"Ġcompany":138,"o":139,"ĠTrump":140,"Ġhow":141,"Ġbecause":142,"Ġany":143,"Ġmost":144,"Ġbeing":145,"Ġmake":146,"Ġwhere":147,"Ġduring":148,"Ġthrough":149,"Ġwhile":150,"000":151,"ĠThis":152,"Ġmillion":153,"ing":154,"Ġ3":155,"Ġmade":156,"Ġwell":157,"Ġ10":158,"Ġdown":159,"Ġoff":160,"Ġsays":161,"Ġme":162,"ĠB":163,"Ġgoing":164,"Ġteam":165,"ĠWe":166,"Ġthose":167,"Ġgovernment":168,"Ġway":169,"We":170,"Ġmany":171,"Ġthen":172,"Ġwork":173,"Ġtold":174,"com":175,"2":176,"Ġgame":177,"ĠAnd":178,"in":179,"year":180,"Ġp":181,"Ġvery":182,"Ġday":183,"Ġhome":184,"Ġtake":185,"Ġweek":186,"Ġsince":187,"ĠNew":188,"Ġmay":189,"Ġeven":190,"Ġseason":191,"Ġsee":192,"Ġ2017":193,"Ġstate":194,"Ġ5":195,"ed":196,"Ġshould":197,"Ġaround":198,"Ġ2018":199,"Ġsecond":200,"Ġus":201,"Ġstill":202,"Ġmuch":203,"Ġ4":204,"Ġgood":205,"Ġthink":206,"%":207,"ĠS":208,"Ġthese":209,"Ġmarket":210,"ĠD":211,"th":212,"Ġgo":213,"'re":214,"Ġsuch":215,"Ġknow":216,"Ġincluding":217,"Ġdon":218,"y":219,"Ġnext":220,"ĠP":221,"Ġdid":222,"Ġunder":223,"Ġsay":224,"en":225,"ĠL":226,"Ġbetween":227,"Ġper":228,"ĠK":229,"ĠC":230,"Ġ6":231,"Ġworld":232,"Ġpart":233,"ĠN":234,"Ġright":235,"Ġwant":236,"Ġfour":237,"),":238,"Ġhigh":239,"Ġneed":240,"re":241,"e":242,"It":243,"Ġhelp":244,"5":245,"3":246,"Ġcountry":247,"ĠR":248,"Ġpolice":249,"A":250,"Ġlong":251,"ĠThey":252,"Ġend":253,"er":254,"ĠT":255,"ĠM":256,"u":257,"Ġboth":258,"Ġhere":259,"an":260,"on":261,"Ġ7":262,"Ġde":263,"ĠShe":264,"Ġbusiness":265,"Ġreport":266,"j":267,"ers":268,"Ġreally":269,"ĠPresident":270,"ar":271,"ĠG":272,"ĠFriday":273,"ĠF":274,"Ġbest":275,"Ġsame":276,"Ġanother":277,"Ġset":278,"old":279,"ĠThat":280,"as":281,"n":282,"Ġcome":283,"Ġfamily":284,"Ġpublic":285,"ĠFor":286,"ĠAs":287,"0":288,"ĠH":289,"Ġ8":290,"Ġ20":291,"Ġfive":292,"es":293,"ĠTuesday":294,"Ġn":295,"ĠThursday":296,"Ġquarter":297,"h":298,"Ġtop":299,"Ġgot":300,"Ġlife":301,"ĠMonday":302,"Ġfound":303,"Ġuse":304,"ĠW":305,"4":306,"ĠWednesday":307,"Ġown":308,"Ġaccording":309,"Ġplay":310,"Ġshow":311,"ĠSt":312,"Ġman":313,"Ġleft":314,"ĠUnited":315,"Ġ12":316,"Ġplace":317,"ĠIf":318,"Ġlot":319,"Ġformer":320,"Ġ0":321,").":322,"Ġsupport":323,"ie":324,"Ġbillion":325,"Ġt":326,"Ġshares":327,"!":328,"z":329,"k":330,"ĠState":331,"Ġpoints":332,"Ġgroup":333,"Ġschool":334,"Ġinformation":335,"Ġ2016":336,"al":337,"r":338,"Ġwin":339,"Ġnews":340,"Ġused":341,"Ġput":342,"Ġcity":343,"ĠJ":344,"ĠThere":345,"Ġnumber":346,"C":347,"'ve":348,"Ġeach":349,"Ġtoo":350,"Ġwon":351,"ly":352,"Ġmonth":353,"is":354,"Ġadded":355,"Ġlook":356,"Ġbetter":357,"Ġevery":358,"Ġ&":359,"Ġdays":360,"Ġ9":361,"Ġtook":362,"Ġnight":363,"Ġe":364,"Ġ11":365,"os":366,"Ġfew":367,"or":368,"ĠNorth":369,"ĠYou":370,"Ġthird":371,"Ġgreat":372,"Ġcalled":373,"ĠOn":374,"Ġpast":375,"Ġcame":376,"Ġmonths":377,"ĠSaturday":378,"Ġ15":379,"Ġbig":380,"ĠE":381,"ĠUS":382,"Ġthings":383,"ĠO":384,"Ġd":385,"Ġstart":386,"B":387,"Ġstock":388,"Ġ30":389,"Ġwomen":390,"ĠSouth":391,"ĠMay":392,"Ġnever":393,"Ġpresident":394,"ĠSunday":395,"Ġwithout":396,"man":397,"8":398,"Ġdidn":399,"Ġlocal":400,"6":401,"Ġsomething":402,"Ġcase":403,"ĠAll":404,"it":405,"7":406,"ĠSo":407,"Ġchildren":408,"Ġaway":409,"Ġlittle":410,"Ġsix":411,"ĠCity":412,"ĠCounty":413,"Ġdata":414,"at":415,"Ġalready":416,"d":417,"Ġmoney":418,"Ġearly":419,"Ġacross":420,"Ġexpected":421,"Ġrun":422,"Ġlater":423,"am":424,"ĠpricLine truncated
|
||||
@@ -0,0 +1,232 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the news sources every 2 minutes (SPEC 4.4, 10.2 point 1): one request at a time with a pause between two,
|
||||
/// conditional on what the source said the last time (ETag, Last-Modified), and spaced out more and more for a source
|
||||
/// that keeps failing. The text it reads is untrusted data: it is parsed, never followed.
|
||||
/// </summary>
|
||||
public sealed partial class NewsCollector(HttpClient http, Database db, IClock clock, ILogger? logger = null) : IDisposable
|
||||
{
|
||||
public const string JobName = "notizie";
|
||||
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>A failing source is tried again after 2, 4, 8… minutes, at most every hour.</summary>
|
||||
public static readonly TimeSpan MaxBackoff = TimeSpan.FromHours(1);
|
||||
|
||||
/// <summary>The longest answer read from a source.</summary>
|
||||
public const int MaxBytes = 5 * 1024 * 1024;
|
||||
|
||||
private readonly ILogger _logger = logger ?? NullLogger.Instance;
|
||||
private readonly NewsStore _store = new(db, clock);
|
||||
private readonly InstrumentCatalog _catalog = new(db, clock);
|
||||
private (DateTimeOffset At, NewsLinker Dictionary)? _dictionary;
|
||||
|
||||
/// <summary>The pause between two requests: politeness towards the sources, zero in the tests.</summary>
|
||||
public TimeSpan Pause { get; init; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
public NewsStore Store => _store;
|
||||
|
||||
/// <summary>A model that could not be downloaded or opened is tried again after this long.</summary>
|
||||
public static readonly TimeSpan ModelRetry = TimeSpan.FromHours(6);
|
||||
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private IToneClassifier? _classifier;
|
||||
private Task? _loading;
|
||||
private DateTimeOffset _nextModelTry = DateTimeOffset.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// The local classifier of SPEC 4.5. Without it the tone is unknown and only the keywords judge: the news keep
|
||||
/// coming while the model downloads, and the articles read meanwhile simply have no score.
|
||||
/// </summary>
|
||||
public IToneClassifier? Classifier
|
||||
{
|
||||
get => Volatile.Read(ref _classifier);
|
||||
init => _classifier = value;
|
||||
}
|
||||
|
||||
/// <summary>Where the model is kept (the <c>models</c> folder of the data directory); null: no model, as in the tests.</summary>
|
||||
public string? ModelFolder { get; init; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stopping.Cancel();
|
||||
_stopping.Dispose();
|
||||
(Volatile.Read(ref _classifier) as IDisposable)?.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Starts, in the background, the download and the opening of the model, once and then every 6 hours if it fails.</summary>
|
||||
private void StartModel()
|
||||
{
|
||||
if (Classifier is not null || ModelFolder is not { } folder || _loading is { IsCompleted: false } || clock.UtcNow < _nextModelTry)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_nextModelTry = clock.UtcNow + ModelRetry;
|
||||
var stopping = _stopping.Token;
|
||||
_loading = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = await ToneModel.EnsureAsync(http, folder, stopping).ConfigureAwait(false);
|
||||
Volatile.Write(ref _classifier, new OnnxToneClassifier(path));
|
||||
LogModelReady(_logger, ToneModel.Revision[..8]);
|
||||
}
|
||||
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception e) when (e is HttpRequestException or IOException or InvalidDataException or OperationCanceledException or OnnxRuntimeException
|
||||
or UnauthorizedAccessException)
|
||||
{
|
||||
LogModelFailed(_logger, e.Message);
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
|
||||
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval };
|
||||
|
||||
/// <summary>One round over the sources that are due.</summary>
|
||||
public async Task RunOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
StartModel();
|
||||
await _store.EnsureDefaultsAsync(cancellationToken).ConfigureAwait(false);
|
||||
var dictionary = await DictionaryAsync(cancellationToken).ConfigureAwait(false);
|
||||
var first = true;
|
||||
foreach (var source in await _store.ListSourcesAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!source.Enabled || source.Kind != NewsSourceKinds.Rss || !Due(source, clock.UtcNow))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!first && Pause > TimeSpan.Zero)
|
||||
{
|
||||
await clock.WaitUntilAsync(clock.UtcNow + Pause, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
first = false;
|
||||
await ReadAsync(source, dictionary, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether a source is due: always while it answers, later and later while it fails.</summary>
|
||||
public static bool Due(NewsSource source, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
if (source.Failures == 0 || source.LastCheckedAt is not { } last)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var wait = TimeSpan.FromTicks(Math.Min(MaxBackoff.Ticks, Interval.Ticks << Math.Min(source.Failures - 1, 10)));
|
||||
return now - last >= wait - TimeSpan.FromSeconds(5);
|
||||
}
|
||||
|
||||
public async Task<IngestResult?> ReadAsync(NewsSource source, NewsLinker dictionary, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, source.Url);
|
||||
request.Headers.Accept.ParseAdd("application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.8, */*;q=0.1");
|
||||
if (source.ETag is { } etag && EntityTagHeaderValue.TryParse(etag, out var tag))
|
||||
{
|
||||
request.Headers.IfNoneMatch.Add(tag);
|
||||
}
|
||||
|
||||
if (source.LastModified is { } modified && DateTimeOffset.TryParse(modified, System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.AssumeUniversal, out var since))
|
||||
{
|
||||
request.Headers.IfModifiedSince = since;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
|
||||
if (response.StatusCode == HttpStatusCode.NotModified)
|
||||
{
|
||||
await _store.RecordCheckAsync(source, ok: true, source.ETag, source.LastModified, null, cancellationToken).ConfigureAwait(false);
|
||||
return new IngestResult(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new HttpRequestException($"La fonte ha risposto {(int)response.StatusCode}.");
|
||||
}
|
||||
|
||||
var content = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
|
||||
var items = FeedParser.Parse(content);
|
||||
var result = await _store.IngestAsync(source, items, dictionary, cancellationToken, Classifier).ConfigureAwait(false);
|
||||
await _store.RecordCheckAsync(source, ok: true, response.Headers.ETag?.ToString(), response.Content.Headers.LastModified?.ToString("R"), null, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (result.Added > 0)
|
||||
{
|
||||
LogRead(_logger, source.Name, result.Added, result.Stories);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or FormatException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
LogFailed(_logger, source.Name, ex.Message);
|
||||
await _store.RecordCheckAsync(source, ok: false, null, null, ex is OperationCanceledException ? "Nessuna risposta in 30 secondi." : ex.Message, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The dictionary of names, built from the catalogue once an hour: the catalogue changes once a day.</summary>
|
||||
public async Task<NewsLinker> DictionaryAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_dictionary is { } cached && clock.UtcNow - cached.At < TimeSpan.FromHours(1))
|
||||
{
|
||||
return cached.Dictionary;
|
||||
}
|
||||
|
||||
var instruments = await _catalog.ListAsync(null, cancellationToken).ConfigureAwait(false);
|
||||
var dictionary = NewsLinker.Build(instruments.Where(i => i.Venue is Venues.Okx or Venues.Alpaca && i.IsLive).Select(i => i.Spec));
|
||||
_dictionary = (clock.UtcNow, dictionary);
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadLimitedAsync(HttpContent content, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[81920];
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
if (buffer.Length + read > MaxBytes)
|
||||
{
|
||||
throw new FormatException("La risposta supera 5 MB.");
|
||||
}
|
||||
|
||||
buffer.Write(chunk, 0, read);
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "News from {Source}: {Added} new articles in {Stories} stories")]
|
||||
private static partial void LogRead(ILogger logger, string source, int added, int stories);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "News source {Source} failed: {Error}")]
|
||||
private static partial void LogFailed(ILogger logger, string source, string error);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "News classifier ready (model revision {Revision})")]
|
||||
private static partial void LogModelReady(ILogger logger, string revision);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "News classifier not available, keywords only until the next try: {Error}")]
|
||||
private static partial void LogModelFailed(ILogger logger, string error);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
public static class NewsSourceKinds
|
||||
{
|
||||
public const string Rss = "rss";
|
||||
public const string Alpaca = "alpaca";
|
||||
public const string Sec = "sec";
|
||||
}
|
||||
|
||||
/// <summary>A source of news as stored; <see cref="Trusted"/> is the "affidabile" label of 10.2.</summary>
|
||||
public sealed record NewsSource(Guid Id, string Url, string Name, string Kind, bool Trusted, bool Enabled, string? Topic)
|
||||
{
|
||||
public string? ETag { get; init; }
|
||||
|
||||
public string? LastModified { get; init; }
|
||||
|
||||
public DateTimeOffset? LastCheckedAt { get; init; }
|
||||
|
||||
public DateTimeOffset? LastOkAt { get; init; }
|
||||
|
||||
public int Failures { get; init; }
|
||||
|
||||
public string? LastError { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What one round of ingestion did.</summary>
|
||||
public sealed record IngestResult(int Added, int Duplicates, int Stories, int Old);
|
||||
|
||||
/// <summary>
|
||||
/// The news of SPEC 10.2, points 1–3, in the database: the sources with their state, and each article grouped with
|
||||
/// the other articles of the same story and linked to what it is about.
|
||||
/// </summary>
|
||||
public sealed class NewsStore(Database db, IClock clock)
|
||||
{
|
||||
/// <summary>Articles older than this when they first arrive are history, not news: they are not stored.</summary>
|
||||
public static readonly TimeSpan MaxAge = TimeSpan.FromDays(3);
|
||||
|
||||
/// <summary>The feeds of SPEC 4.4 that answered on 9 October 2026, trusted as 10.2 says.</summary>
|
||||
public static IReadOnlyList<NewsSource> Defaults { get; } =
|
||||
[
|
||||
Rss("https://www.federalreserve.gov/feeds/press_all.xml", "Federal Reserve", trusted: true, LinkScopes.Market),
|
||||
Rss("https://www.ecb.europa.eu/rss/press.html", "BCE", trusted: true, LinkScopes.Market),
|
||||
Rss("https://www.sec.gov/news/pressreleases.rss", "SEC", trusted: true, null),
|
||||
Rss("https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "CNBC", trusted: true, null),
|
||||
Rss("https://feeds.content.dowjones.io/public/rss/mw_topstories", "MarketWatch", trusted: true, null),
|
||||
Rss("https://www.investing.com/rss/news.rss", "Investing.com", trusted: false, null),
|
||||
Rss("https://xml.fxstreet.com/news/forex-news/index.xml", "FXStreet", trusted: false, null),
|
||||
Rss("https://investinglive.com/feed/news", "investingLive", trusted: false, null),
|
||||
Rss("https://www.coindesk.com/arc/outboundfeeds/rss/", "CoinDesk", trusted: true, Data.AssetClasses.Crypto),
|
||||
Rss("https://cointelegraph.com/rss", "Cointelegraph", trusted: false, Data.AssetClasses.Crypto),
|
||||
Rss("https://www.theblock.co/rss.xml", "The Block", trusted: false, Data.AssetClasses.Crypto),
|
||||
Rss("https://decrypt.co/feed", "Decrypt", trusted: false, Data.AssetClasses.Crypto),
|
||||
Rss("https://www.ilsole24ore.com/rss/finanza.xml", "Il Sole 24 Ore", trusted: true, null),
|
||||
Rss("https://www.ansa.it/sito/notizie/economia/economia_rss.xml", "ANSA", trusted: true, null),
|
||||
];
|
||||
|
||||
private const string SourceColumns = "id, url, name, kind, trusted, enabled, topic, etag, last_modified, last_checked_at, last_ok_at, failures, last_error";
|
||||
|
||||
/// <summary>The first time: the default sources. Later the list is the user's, and a removed default stays removed.</summary>
|
||||
public async Task EnsureDefaultsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM news_sources").ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var source in Defaults)
|
||||
{
|
||||
await AddAsync(s, source, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<NewsSource> AddSourceAsync(string url, string name, string kind, bool trusted, string? topic, CancellationToken cancellationToken)
|
||||
{
|
||||
var source = new NewsSource(Guid.Empty, url, name, kind, trusted, Enabled: true, topic);
|
||||
var id = await db.WriteAsync(s => AddAsync(s, source, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
return source with { Id = id };
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<NewsSource>> ListSourcesAsync(CancellationToken cancellationToken) =>
|
||||
await db.ReadAsync(s => s.QueryAsync($"SELECT {SourceColumns} FROM news_sources ORDER BY name", ReadSource), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>How the last request to a source went: on success the validators for the next conditional request.</summary>
|
||||
public Task RecordCheckAsync(NewsSource source, bool ok, string? etag, string? lastModified, string? error, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
var now = clock.UtcNow;
|
||||
return db.WriteAsync(s => ok
|
||||
? s.ExecuteAsync("UPDATE news_sources SET etag = @e, last_modified = @m, last_checked_at = @t, last_ok_at = @t, failures = 0, last_error = NULL, updated_at = @t WHERE id = @id",
|
||||
cancellationToken, ("e", etag), ("m", lastModified), ("t", now), ("id", source.Id))
|
||||
: s.ExecuteAsync("UPDATE news_sources SET last_checked_at = @t, failures = failures + 1, last_error = @err, updated_at = @t WHERE id = @id",
|
||||
cancellationToken, ("t", now), ("err", error is null ? null : Redactor.Redact(error)[..Math.Min(300, Redactor.Redact(error).Length)]), ("id", source.Id)),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the new articles of a source. An article already stored (same address) is skipped; a new one joins the
|
||||
/// story whose title it retells, within two days, or starts a new one. The story counts again its independent
|
||||
/// publishers and whether a trusted source told it.
|
||||
/// </summary>
|
||||
public async Task<IngestResult> IngestAsync(
|
||||
NewsSource source, IReadOnlyList<FeedItem> items, NewsLinker dictionary, CancellationToken cancellationToken, IToneClassifier? classifier = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
ArgumentNullException.ThrowIfNull(dictionary);
|
||||
var now = clock.UtcNow;
|
||||
return await db.WriteAsync(async s =>
|
||||
{
|
||||
int added = 0, duplicates = 0, old = 0;
|
||||
var touched = new HashSet<Guid>();
|
||||
var stories = await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t",
|
||||
r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")),
|
||||
("t", now - MaxAge - NewsMatching.StoryWindow)).ConfigureAwait(false);
|
||||
foreach (var item in items.OrderBy(i => i.PublishedAt ?? now))
|
||||
{
|
||||
var published = item.PublishedAt is { } p && p <= now ? p : now;
|
||||
if (now - published > MaxAge)
|
||||
{
|
||||
old++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = NewsMatching.UrlKey(item.Link);
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)).ConfigureAwait(false) > 0)
|
||||
{
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var words = NewsMatching.Words(item.Title);
|
||||
var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words))
|
||||
.OrderByDescending(st => NewsMatching.Score(words, st.Words)).Select(st => (Guid?)st.Id).FirstOrDefault();
|
||||
if (story is null)
|
||||
{
|
||||
story = Ids.NewId(clock);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, importance, created_at, updated_at) " +
|
||||
"VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, 1, @now, @now)", cancellationToken,
|
||||
("id", story), ("title", item.Title), ("key", NewsMatching.TitleKey(item.Title)), ("p", published), ("now", now), ("trusted", source.Trusted))
|
||||
.ConfigureAwait(false);
|
||||
stories.Add((story.Value, words, published));
|
||||
}
|
||||
|
||||
var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary);
|
||||
var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic);
|
||||
var judgement = NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, score, severe, importance, created_at) " +
|
||||
"VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @score, @severe, @importance, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("story", story), ("source", source.Id), ("url", item.Link), ("key", key), ("pub", NewsMatching.Publisher(item.Link)),
|
||||
("title", item.Title), ("summary", item.Summary), ("lang", language), ("p", published), ("score", judgement.Score), ("severe", judgement.Severe),
|
||||
("importance", judgement.Importance), ("now", now)).ConfigureAwait(false);
|
||||
foreach (var link in links)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @story, @scope, @target, @via, @now) " +
|
||||
"ON CONFLICT (story_id, scope, target) DO NOTHING", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("story", story), ("scope", link.Scope), ("target", link.Target), ("via", link.Via), ("now", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
touched.Add(story.Value);
|
||||
added++;
|
||||
}
|
||||
|
||||
foreach (var id in touched)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"UPDATE news_stories SET last_seen_at = @now, updated_at = @now, " +
|
||||
"sources = (SELECT COUNT(DISTINCT publisher) FROM news_items WHERE story_id = @id), " +
|
||||
"trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0, " +
|
||||
"score = (SELECT AVG(score) FROM news_items WHERE story_id = @id), " +
|
||||
"severe = (SELECT MIN(severe) FROM news_items WHERE story_id = @id), " +
|
||||
"importance = (SELECT MAX(importance) FROM news_items WHERE story_id = @id) " +
|
||||
"WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new IngestResult(added, duplicates, touched.Count, old);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static NewsSource Rss(string url, string name, bool trusted, string? topic) =>
|
||||
new(Guid.Empty, url, name, NewsSourceKinds.Rss, trusted, Enabled: true, topic);
|
||||
|
||||
private async Task<Guid> AddAsync(DbSession s, NewsSource source, CancellationToken cancellationToken)
|
||||
{
|
||||
var id = Ids.NewId(clock);
|
||||
var now = clock.UtcNow;
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_sources (id, url, name, kind, trusted, enabled, topic, failures, created_at, updated_at) VALUES (@id, @url, @name, @kind, @trusted, @enabled, @topic, 0, @now, @now)",
|
||||
cancellationToken, ("id", id), ("url", source.Url), ("name", source.Name), ("kind", source.Kind), ("trusted", source.Trusted), ("enabled", source.Enabled),
|
||||
("topic", source.Topic), ("now", now)).ConfigureAwait(false);
|
||||
return id;
|
||||
}
|
||||
|
||||
private static NewsSource ReadSource(DbRow r) => new(r.Id("id"), r.Text("url"), r.Text("name"), r.Text("kind"), r.Bool("trusted"), r.Bool("enabled"), r.TextOrNull("topic"))
|
||||
{
|
||||
ETag = r.TextOrNull("etag"),
|
||||
LastModified = r.TextOrNull("last_modified"),
|
||||
LastCheckedAt = r.MomentOrNull("last_checked_at"),
|
||||
LastOkAt = r.MomentOrNull("last_ok_at"),
|
||||
Failures = (int)r.Number("failures"),
|
||||
LastError = r.TextOrNull("last_error"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Italian or English, for a text whose feed does not say: the classifier of 10.2 reads only English.</summary>
|
||||
public static class Languages
|
||||
{
|
||||
private static readonly HashSet<string> Italian = new(StringComparer.Ordinal)
|
||||
{
|
||||
"il", "lo", "gli", "della", "delle", "dei", "degli", "nel", "nella", "sul", "sulla", "per", "con", "che", "non", "una", "alla", "anche", "sono", "più", "dopo",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> English = new(StringComparer.Ordinal)
|
||||
{
|
||||
"the", "of", "and", "to", "in", "for", "with", "on", "is", "are", "as", "after", "from", "by", "its", "will", "has", "says",
|
||||
};
|
||||
|
||||
public static string Guess(string text)
|
||||
{
|
||||
var words = (text ?? "").ToLowerInvariant().Split((char[])[' ', ',', '.', ':', ';', '\'', '"', '(', ')'], StringSplitOptions.RemoveEmptyEntries);
|
||||
return words.Count(Italian.Contains) > words.Count(English.Contains) ? "it" : "en";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.Tokenizers;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>
|
||||
/// The model of SPEC 4.5: <c>mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis</c> (Apache-2.0) in its
|
||||
/// ONNX export by Xenova, at a fixed revision and with its hash checked (ADR 0004, ADR 0014). The tokenizer travels in
|
||||
/// the DLL; the model, 83 MB, is downloaded once into the <c>models</c> folder of the data directory.
|
||||
/// </summary>
|
||||
public static class ToneModel
|
||||
{
|
||||
public const string Repository = "Xenova/distilroberta-finetuned-financial-news-sentiment-analysis";
|
||||
public const string Revision = "e6953e30167c7fc3d1ad62f3df31617dd712fbc1";
|
||||
public const string RemotePath = "onnx/model_quantized.onnx";
|
||||
public const string FileName = "distilroberta-financial-news-sentiment-e6953e30-quantized.onnx";
|
||||
public const long Size = 82_763_251;
|
||||
public const string Sha256 = "8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec";
|
||||
|
||||
public static readonly Uri Url = new($"https://huggingface.co/{Repository}/resolve/{Revision}/{RemotePath}");
|
||||
|
||||
/// <summary>The longest download allowed: slow connections get there, a stuck one does not hold the job forever.</summary>
|
||||
public static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(30);
|
||||
|
||||
/// <summary>
|
||||
/// The path of the model in <paramref name="folder"/>, downloaded and checked if it is not there yet. A file of the
|
||||
/// wrong size or hash is never used: it is replaced. Throws when the download fails or does not match.
|
||||
/// </summary>
|
||||
public static async Task<string> EnsureAsync(HttpClient http, string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(http);
|
||||
Directory.CreateDirectory(folder);
|
||||
var path = Path.Combine(folder, FileName);
|
||||
if (File.Exists(path) && new FileInfo(path).Length == Size && await HashAsync(path, cancellationToken).ConfigureAwait(false) == Sha256)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
|
||||
var part = path + ".part";
|
||||
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
|
||||
{
|
||||
timeout.CancelAfter(DownloadTimeout);
|
||||
using var response = await http.GetAsync(Url, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var target = new FileStream(part, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true);
|
||||
await using (target.ConfigureAwait(false))
|
||||
{
|
||||
var source = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false);
|
||||
await using (source.ConfigureAwait(false))
|
||||
{
|
||||
var buffer = new byte[1 << 16];
|
||||
long total = 0;
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, timeout.Token).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
total += read;
|
||||
if (total > Size)
|
||||
{
|
||||
throw new InvalidDataException($"The model is larger than the {Size} bytes expected.");
|
||||
}
|
||||
|
||||
await target.WriteAsync(buffer.AsMemory(0, read), timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var hash = await HashAsync(part, cancellationToken).ConfigureAwait(false);
|
||||
if (new FileInfo(part).Length != Size || hash != Sha256)
|
||||
{
|
||||
File.Delete(part);
|
||||
throw new InvalidDataException($"The downloaded model does not match: SHA-256 {hash}, expected {Sha256}.");
|
||||
}
|
||||
|
||||
File.Move(part, path, overwrite: true);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static async Task<string> HashAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
var file = File.OpenRead(path);
|
||||
await using (file.ConfigureAwait(false))
|
||||
{
|
||||
return Convert.ToHexStringLower(await SHA256.HashDataAsync(file, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The local classifier of SPEC 4.5 on ONNX Runtime. The tokenizer is RoBERTa's byte-level BPE, the one of GPT-2 with
|
||||
/// <c><s></c> and <c></s></c> around the text; the test compares its ids with the original. One thread, so the
|
||||
/// classifier never takes the processor away from the trading engine; 10–20 ms per title.
|
||||
/// </summary>
|
||||
public sealed class OnnxToneClassifier : IToneClassifier, IDisposable
|
||||
{
|
||||
/// <summary>Titles are short: 128 tokens hold any of them, and the model's limit is 512.</summary>
|
||||
public const int MaxTokens = 128;
|
||||
|
||||
private const int Start = 0;
|
||||
private const int End = 2;
|
||||
|
||||
// Classes of the model (config.json): 0 negative, 1 neutral, 2 positive.
|
||||
private const int NegativeClass = 0;
|
||||
private const int NeutralClass = 1;
|
||||
private const int PositiveClass = 2;
|
||||
|
||||
private static readonly Lazy<BpeTokenizer> Tokenizer = new(LoadTokenizer);
|
||||
|
||||
private readonly InferenceSession _session;
|
||||
private readonly string[] _inputs;
|
||||
private readonly string[] _output;
|
||||
|
||||
public OnnxToneClassifier(string modelPath)
|
||||
{
|
||||
using var options = new SessionOptions
|
||||
{
|
||||
IntraOpNumThreads = 1,
|
||||
InterOpNumThreads = 1,
|
||||
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
|
||||
};
|
||||
_session = new InferenceSession(modelPath, options);
|
||||
_inputs = [.. _session.InputMetadata.Keys];
|
||||
_output = [_session.OutputMetadata.Keys.First()];
|
||||
if (!_inputs.Contains("input_ids"))
|
||||
{
|
||||
_session.Dispose();
|
||||
throw new InvalidDataException("The model has no input_ids input.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The token ids the model reads, as the original RoBERTa tokenizer gives them.</summary>
|
||||
public static IReadOnlyList<int> Ids(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var body = Tokenizer.Value.EncodeToIds(text);
|
||||
var ids = new List<int>(Math.Min(body.Count, MaxTokens - 2) + 2) { Start };
|
||||
ids.AddRange(body.Take(MaxTokens - 2));
|
||||
ids.Add(End);
|
||||
return ids;
|
||||
}
|
||||
|
||||
public ToneScore Classify(string text)
|
||||
{
|
||||
var ids = Ids(text);
|
||||
var shape = new long[] { 1, ids.Count };
|
||||
var values = new List<OrtValue>(_inputs.Length);
|
||||
try
|
||||
{
|
||||
foreach (var name in _inputs)
|
||||
{
|
||||
var data = name switch
|
||||
{
|
||||
"input_ids" => ids.Select(i => (long)i).ToArray(),
|
||||
"attention_mask" => Enumerable.Repeat(1L, ids.Count).ToArray(),
|
||||
_ => new long[ids.Count],
|
||||
};
|
||||
values.Add(OrtValue.CreateTensorValueFromMemory(data, shape));
|
||||
}
|
||||
|
||||
using var run = new RunOptions();
|
||||
using var outputs = _session.Run(run, _inputs, values, _output);
|
||||
var logits = outputs[0].GetTensorDataAsSpan<float>();
|
||||
var max = Math.Max(logits[NegativeClass], Math.Max(logits[NeutralClass], logits[PositiveClass]));
|
||||
double negative = Math.Exp(logits[NegativeClass] - max), neutral = Math.Exp(logits[NeutralClass] - max), positive = Math.Exp(logits[PositiveClass] - max);
|
||||
var sum = negative + neutral + positive;
|
||||
return new ToneScore(positive / sum, negative / sum, neutral / sum);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var value in values)
|
||||
{
|
||||
value.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _session.Dispose();
|
||||
|
||||
private static BpeTokenizer LoadTokenizer()
|
||||
{
|
||||
var assembly = typeof(OnnxToneClassifier).Assembly;
|
||||
using var vocab = assembly.GetManifestResourceStream("Anubis.News.Model.vocab.json") ?? throw new InvalidOperationException("vocab.json is missing.");
|
||||
using var merges = assembly.GetManifestResourceStream("Anubis.News.Model.merges.txt") ?? throw new InvalidOperationException("merges.txt is missing.");
|
||||
var vocabulary = JsonSerializer.Deserialize<Dictionary<string, int>>(vocab) ?? throw new InvalidDataException("vocab.json is empty.");
|
||||
using var reader = new StreamReader(merges);
|
||||
var pairs = reader.ReadToEnd().Split('\n').Where(l => l.Length > 0 && !l.StartsWith("#version", StringComparison.Ordinal)).ToList();
|
||||
|
||||
// Not CodeGenTokenizer.Create: it adds CodeGen's own tokens for runs of spaces, ids RoBERTa does not have. No special
|
||||
// tokens either: a headline that contains "<s>" or "<mask>" is read as text, never as a mark for the model.
|
||||
return BpeTokenizer.Create(new BpeOptions(vocabulary)
|
||||
{
|
||||
Merges = pairs,
|
||||
PreTokenizer = RobertaPreTokenizer.Instance,
|
||||
ByteLevel = true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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..];
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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&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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -13,6 +13,24 @@
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.Tokenizers": {
|
||||
"type": "Direct",
|
||||
"requested": "[2.0.1, )",
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "3.30.2"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.3, )",
|
||||
@@ -28,6 +46,11 @@
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
},
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.30.2",
|
||||
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
@@ -49,6 +72,14 @@
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.ML.OnnxRuntime.Managed": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
|
||||
"dependencies": {
|
||||
"System.Numerics.Tensors": "9.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
@@ -75,6 +106,27 @@
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"System.Numerics.Tensors": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {
|
||||
"Microsoft.ML.OnnxRuntime": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.31.1, )",
|
||||
"resolved": "1.31.1",
|
||||
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
|
||||
"dependencies": {
|
||||
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -35,6 +35,9 @@ public sealed class DependencyPolicyTests
|
||||
"SQLitePCLRaw.core",
|
||||
"SQLitePCLRaw.lib.e_sqlite3",
|
||||
"SQLitePCLRaw.provider.e_sqlite3",
|
||||
|
||||
// Protocol buffers, brought by Microsoft.ML.Tokenizers (phase 7).
|
||||
"Google.Protobuf",
|
||||
};
|
||||
|
||||
private static readonly string[] _packageElements = ["PackageReference", "GlobalPackageReference", "PackageDownload"];
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user