Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8b3500db6 | ||
|
|
3da9b00f44 | ||
|
|
3eabc7713e | ||
|
|
c7e462b6f4 | ||
|
|
0b0f4a5e75 | ||
|
|
f69943f70a | ||
|
|
14e8a872dc | ||
|
|
df21962da3 | ||
|
|
99ff2d9402 | ||
|
|
9cd1357e9b | ||
|
|
632252f95c | ||
|
|
a3ff8ea6b7 | ||
|
|
61878c2023 | ||
|
|
ae4ae4ed92 | ||
|
|
a7ff173771 | ||
|
|
974ebd863f | ||
|
|
b49e3c2899 | ||
|
|
181b329303 | ||
|
|
dcebfb61e1 | ||
|
|
4449ec7a0a | ||
|
|
959fe6ccba | ||
|
|
f4f10a46dd | ||
|
|
b087dd215b | ||
|
|
a5a6918dae | ||
|
|
4e0711c988 | ||
|
|
a77aa1b7eb | ||
|
|
63ae9d580a | ||
|
|
a66e3439d8 | ||
|
|
74809068af | ||
|
|
73f2345047 | ||
|
|
6ea303e1dc | ||
|
|
1aede2fc1c | ||
|
|
72f4cbe0a5 | ||
|
|
78e77818eb | ||
|
|
0a9a8a38ec | ||
|
|
5f0ce6b172 | ||
|
|
9ee2367693 | ||
|
|
f1ba452aba | ||
|
|
25e71b679f | ||
|
|
9cf386d08b | ||
|
|
6e365673b8 | ||
|
|
32673007a2 | ||
|
|
e561245d4e | ||
|
|
829fbd2eba | ||
|
|
f59eee8632 | ||
|
|
7291f5d15b | ||
|
|
9a4e31aa48 | ||
|
|
1c7205024f | ||
|
|
be6d5fb91f | ||
|
|
2185a0b36b | ||
|
|
3d174931e9 | ||
|
|
9ae107000b | ||
|
|
e96ca70a1a | ||
|
|
84c540786c | ||
|
|
d00dfbd32f | ||
|
|
680cab4bb6 | ||
|
|
41e067e7d1 | ||
|
|
98ee504dab | ||
|
|
e3c9eae65b | ||
|
|
fc5df0146e | ||
|
|
dc1ba4e701 | ||
|
|
9ac159a7db | ||
|
|
17d6b8db38 | ||
|
|
13f9c42f61 | ||
|
|
7041533ce2 | ||
|
|
8def84e122 | ||
|
|
2409e74b26 | ||
|
|
a6227793c3 | ||
|
|
9db95ea79a | ||
|
|
f278ff4f67 | ||
|
|
af7528560f | ||
|
|
953ffe5e9b | ||
|
|
5efb149fd6 | ||
|
|
ccb9602950 | ||
|
|
d97304d7b9 | ||
|
|
6d3ef8e7b5 | ||
|
|
16be51e175 | ||
|
|
1a0912e436 | ||
|
|
60d5ebbc05 | ||
|
|
4c4f848d80 | ||
|
|
d2441df592 | ||
|
|
e3caa26207 | ||
|
|
1419457fe4 | ||
|
|
74d4c4fa6f | ||
|
|
1a8d48212f | ||
|
|
094a527ba2 | ||
|
|
de2cc0eedf | ||
|
|
68fdd0baee | ||
|
|
aa2766f3ed | ||
|
|
4a65d4060f | ||
|
|
1e71038209 | ||
|
|
49ed73e6f6 | ||
|
|
b3fb69e696 | ||
|
|
956306a8fa | ||
|
|
3b13a4258d | ||
|
|
67350f091e | ||
|
|
992467ff04 | ||
|
|
cf6d0536aa | ||
|
|
101dcbb152 | ||
|
|
f9d71559e8 | ||
|
|
53ca01b7c3 |
No files matched your search
@@ -6,6 +6,9 @@
|
|||||||
artifacts/
|
artifacts/
|
||||||
TestResults/
|
TestResults/
|
||||||
docs/
|
docs/
|
||||||
|
!docs/design/logo/
|
||||||
|
!docs/backtests/*.outcome.json
|
||||||
|
!docs/learning/first-model.json
|
||||||
**/*.md
|
**/*.md
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
@@ -24,3 +24,7 @@ csharp_using_directive_placement = outside_namespace:warning
|
|||||||
dotnet_style_qualification_for_field = false:warning
|
dotnet_style_qualification_for_field = false:warning
|
||||||
dotnet_style_qualification_for_property = false:warning
|
dotnet_style_qualification_for_property = false:warning
|
||||||
dotnet_style_qualification_for_method = false:warning
|
dotnet_style_qualification_for_method = false:warning
|
||||||
|
|
||||||
|
# Tests: literal arrays in assertions read better than static fields.
|
||||||
|
[tests/**.cs]
|
||||||
|
dotnet_diagnostic.CA1861.severity = none
|
||||||
@@ -3,5 +3,14 @@
|
|||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
.githooks/* text eol=lf
|
.githooks/* text eol=lf
|
||||||
Dockerfile 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
|
*.png binary
|
||||||
*.ico 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
|
||||||
+21
-3
@@ -12,6 +12,8 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||||
|
# The databases of the tests live in memory: the disk of the runner stops for seconds under load (ADR 0019).
|
||||||
|
options: --tmpfs /test-tmp:size=4g
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -23,15 +25,22 @@ jobs:
|
|||||||
POSTGRES_DB: anubis
|
POSTGRES_DB: anubis
|
||||||
POSTGRES_USER: anubis
|
POSTGRES_USER: anubis
|
||||||
POSTGRES_PASSWORD: anubis-ci
|
POSTGRES_PASSWORD: anubis-ci
|
||||||
|
# A throwaway server on a slow disk: without syncs to disk, the checkpoint that every DROP DATABASE of the
|
||||||
|
# tests forces takes milliseconds instead of up to 37 seconds (ADR 0015). Never for a real database.
|
||||||
|
POSTGRES_INITDB_ARGS: "--no-sync -c fsync=off -c synchronous_commit=off -c full_page_writes=off"
|
||||||
|
# --init and a pg_isready that gives up before Docker does (ADR 0015, issue #98). Without them a health
|
||||||
|
# check that outlives its timeout leaves pg_isready to PostgreSQL as PID 1, and its exit restarts the server.
|
||||||
options: >-
|
options: >-
|
||||||
--health-cmd "pg_isready -U anubis -d anubis"
|
--init
|
||||||
|
--health-cmd "pg_isready -U anubis -d anubis -t 5"
|
||||||
--health-interval 3s
|
--health-interval 3s
|
||||||
--health-timeout 3s
|
--health-timeout 15s
|
||||||
--health-retries 20
|
--health-retries 20
|
||||||
env:
|
env:
|
||||||
ANUBIS_TEST_DB: ${{ matrix.db }}
|
ANUBIS_TEST_DB: ${{ matrix.db }}
|
||||||
ANUBIS_TEST_PG_HOST: postgres
|
ANUBIS_TEST_PG_HOST: postgres
|
||||||
ANUBIS_TEST_PG_PORT: "5432"
|
ANUBIS_TEST_PG_PORT: "5432"
|
||||||
|
ANUBIS_TEST_PG_PASSWORD: anubis-ci
|
||||||
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
||||||
DOTNET_NOLOGO: "1"
|
DOTNET_NOLOGO: "1"
|
||||||
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
|
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
|
||||||
@@ -43,7 +52,13 @@ jobs:
|
|||||||
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
||||||
git checkout -q FETCH_HEAD
|
git checkout -q FETCH_HEAD
|
||||||
- name: Check
|
- name: Check
|
||||||
run: sh ./tasks.sh check
|
run: |
|
||||||
|
df -h /test-tmp
|
||||||
|
TMPDIR=/test-tmp sh ./tasks.sh check
|
||||||
|
# The log of the PostgreSQL service, read through the Docker socket the runner mounts in the job (issue #98).
|
||||||
|
- name: PostgreSQL log
|
||||||
|
if: always() && matrix.db == 'postgres'
|
||||||
|
run: sh ./tasks.sh ci-service-log postgres
|
||||||
|
|
||||||
image:
|
image:
|
||||||
needs: test
|
needs: test
|
||||||
@@ -62,3 +77,6 @@ jobs:
|
|||||||
git checkout -q FETCH_HEAD
|
git checkout -q FETCH_HEAD
|
||||||
- name: Build image (no publish)
|
- name: Build image (no publish)
|
||||||
run: docker build -f deploy/docker/Dockerfile -t anubis:ci .
|
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
|
||||||
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
// The C# extension provides the "coreclr" debugger used by launch.json.
|
||||||
|
"recommendations": ["ms-dotnettools.csharp"]
|
||||||
|
}
|
||||||
Vendored
+70
@@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
// Debugging Anubis from VS Code (needs the C# extension, ms-dotnettools.csharp).
|
||||||
|
// Each configuration builds the server in Debug first and opens the browser once it listens.
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Anubis: server, dati di prova",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "build-server",
|
||||||
|
"program": "${workspaceFolder}/src/Anubis.Server/bin/Debug/net10.0/Anubis.Server.dll",
|
||||||
|
// A data folder of its own, ignored by git: the real one in %APPDATA%\Anubis stays untouched.
|
||||||
|
"args": ["--data-dir", "${workspaceFolder}/artifacts/debug-data"],
|
||||||
|
"cwd": "${workspaceFolder}/src/Anubis.Server",
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
},
|
||||||
|
"console": "internalConsole",
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"serverReadyAction": {
|
||||||
|
"action": "openExternally",
|
||||||
|
"pattern": "Now listening on: (https?://[^\\s\"]+)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Anubis: modalità dimostrativa",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "build-server",
|
||||||
|
"program": "${workspaceFolder}/src/Anubis.Server/bin/Debug/net10.0/Anubis.Server.dll",
|
||||||
|
// The data of SPEC appendix F, in a folder and a database apart (the same as "tasks seed-demo").
|
||||||
|
"args": ["--demo"],
|
||||||
|
"cwd": "${workspaceFolder}/src/Anubis.Server",
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
},
|
||||||
|
"console": "internalConsole",
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"serverReadyAction": {
|
||||||
|
"action": "openExternally",
|
||||||
|
"pattern": "Now listening on: (https?://[^\\s\"]+)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Anubis: server, dati dell'utente",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "build-server",
|
||||||
|
"program": "${workspaceFolder}/src/Anubis.Server/bin/Debug/net10.0/Anubis.Server.dll",
|
||||||
|
// The desktop data folder (%APPDATA%\Anubis), the same one "tasks dev" uses.
|
||||||
|
"args": [],
|
||||||
|
"cwd": "${workspaceFolder}/src/Anubis.Server",
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
},
|
||||||
|
"console": "internalConsole",
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"serverReadyAction": {
|
||||||
|
"action": "openExternally",
|
||||||
|
"pattern": "Now listening on: (https?://[^\\s\"]+)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Anubis: aggancia a un processo",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "attach",
|
||||||
|
"processId": "${command:pickProcess}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+45
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
// The build the debugger needs, plus the commands of tasks.ps1 (Terminal > Run Task).
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"label": "build-server",
|
||||||
|
"type": "process",
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": ["build", "${workspaceFolder}/src/Anubis.Server", "-c", "Debug", "-nologo", "-consoleLoggerParameters:NoSummary"],
|
||||||
|
"group": { "kind": "build", "isDefault": true },
|
||||||
|
"presentation": { "reveal": "silent", "clear": true },
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "check",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./tasks.ps1 check",
|
||||||
|
"windows": { "command": "./tasks.ps1 check" },
|
||||||
|
"linux": { "command": "sh ./tasks.sh check" },
|
||||||
|
"osx": { "command": "sh ./tasks.sh check" },
|
||||||
|
"group": "test",
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "test",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./tasks.ps1 test",
|
||||||
|
"windows": { "command": "./tasks.ps1 test" },
|
||||||
|
"linux": { "command": "sh ./tasks.sh test" },
|
||||||
|
"osx": { "command": "sh ./tasks.sh test" },
|
||||||
|
"group": { "kind": "test", "isDefault": true },
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "dev",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./tasks.ps1 dev",
|
||||||
|
"windows": { "command": "./tasks.ps1 dev" },
|
||||||
|
"linux": { "command": "sh ./tasks.sh dev" },
|
||||||
|
"osx": { "command": "sh ./tasks.sh dev" },
|
||||||
|
"isBackground": true,
|
||||||
|
"problemMatcher": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -11,15 +11,18 @@ Bot di trading personale: azioni USA su Alpaca, crypto spot su OKX Europe, senza
|
|||||||
|
|
||||||
## Comandi
|
## Comandi
|
||||||
|
|
||||||
Da `tools/Anubis.Tasks`, tramite `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh <comando>` (Linux). Niente `make`.
|
Dalla radice del repository: `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh <comando>` (Linux); il codice sta in `tools/Anubis.Tasks`. Niente `make`.
|
||||||
- `check`: ripristino con `--locked-mode`, `dotnet format --verify-no-changes`, build Release con gli analizzatori, test. Va verde prima di ogni commit.
|
- `check`: ripristino con `--locked-mode`, `dotnet format --verify-no-changes`, build Release con gli analizzatori, test. Va verde prima di ogni commit.
|
||||||
- `test`: solo i test; il motore viene da `ANUBIS_TEST_DB` (`sqlite` o `postgres`). Esclude la categoria `LiveDemo`.
|
- `test`: solo i test; il motore viene da `ANUBIS_TEST_DB` (`sqlite` o `postgres`). Esclude la categoria `LiveDemo`.
|
||||||
- `dev`: il server con `dotnet watch` su http://localhost:5000 (o `--urls`).
|
- `dev`: il server con `dotnet watch` su http://localhost:8787 (o `--urls`). Fuori da Docker usa la configurazione desktop e la cartella dei dati dell'utente (`%APPDATA%\Anubis`): per provare senza toccarla c'è `seed-demo`.
|
||||||
- `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`.
|
- `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`.
|
||||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||||
- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili.
|
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
||||||
- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`.
|
- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie, Apprendimento 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.
|
||||||
|
|
||||||
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006).
|
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006).
|
||||||
|
|
||||||
@@ -42,6 +45,7 @@ Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR
|
|||||||
- `docs/SPEC.md` — specifica completa
|
- `docs/SPEC.md` — specifica completa
|
||||||
- `docs/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti
|
- `docs/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti
|
||||||
- `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri
|
- `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri
|
||||||
|
- `docs/adr/0007-scelte-fase-1.md` — schema per i due motori, interfaccia statica, immagine Docker
|
||||||
- `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo
|
- `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo
|
||||||
- `docs/ROADMAP.md` — fasi, issue, criteri di accettazione
|
- `docs/ROADMAP.md` — fasi, issue, criteri di accettazione
|
||||||
- `docs/STATE.md` — stato corrente
|
- `docs/STATE.md` — stato corrente
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||||
<Company>BalboSoft</Company>
|
<Company>BalboSoft</Company>
|
||||||
<Product>Anubis</Product>
|
<Product>Anubis</Product>
|
||||||
<Version>0.0.1</Version>
|
<Version>0.7.0</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
|
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
|
||||||
|
|||||||
@@ -9,4 +9,16 @@
|
|||||||
<PackageVersion Include="MSTest.TestAdapter" Version="4.5.2" />
|
<PackageVersion Include="MSTest.TestAdapter" Version="4.5.2" />
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- Databases (ADR 0003): ADO.NET drivers for PostgreSQL and SQLite. -->
|
||||||
|
<PackageVersion Include="Npgsql" Version="10.0.3" />
|
||||||
|
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.14" />
|
||||||
|
<!-- 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>
|
</Project>
|
||||||
@@ -1,22 +1,41 @@
|
|||||||
# Anubis image (ADR 0003). Phase 0: minimal server with /health.
|
# Anubis image (ADR 0003, SPEC 15.2). Build from the repository root:
|
||||||
# Phase 1 adds the entrypoint (PUID/PGID, data folder) and the HEALTHCHECK (issue #16).
|
# docker build -f deploy/docker/Dockerfile -t gitea.encke-hake.ts.net/balbosoft/anubis:dev .
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY global.json Directory.Build.props Directory.Packages.props ./
|
COPY global.json Directory.Build.props Directory.Packages.props ./
|
||||||
COPY src/Anubis/Anubis.csproj src/Anubis/packages.lock.json src/Anubis/
|
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/
|
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/ src/Anubis/
|
||||||
COPY src/Anubis.Server/ src/Anubis.Server/
|
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/
|
||||||
|
COPY docs/learning/ docs/learning/
|
||||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
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
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app ./
|
COPY --from=build /app ./
|
||||||
ENV ASPNETCORE_HTTP_PORTS=8787 \
|
COPY --chmod=755 deploy/docker/entrypoint.sh /usr/local/bin/anubis-entrypoint
|
||||||
TZ=Europe/Rome
|
# The port comes from PORT (8787 by default), read by the app; the base image's own port setting is cleared.
|
||||||
|
ENV ANUBIS_PLATFORM=docker \
|
||||||
|
ASPNETCORE_HTTP_PORTS= \
|
||||||
|
TZ=Europe/Rome \
|
||||||
|
PUID=99 \
|
||||||
|
PGID=100
|
||||||
EXPOSE 8787
|
EXPOSE 8787
|
||||||
VOLUME /data
|
VOLUME /data
|
||||||
USER $APP_UID
|
# Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts
|
||||||
ENTRYPOINT ["dotnet", "Anubis.Server.dll"]
|
# 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 '"]
|
||||||
|
ENTRYPOINT ["anubis-entrypoint"]
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#!/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.Guard.dll"
|
||||||
|
|
||||||
|
if [ "$(id -u)" != "0" ]; then
|
||||||
|
exec dotnet "$app" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
uid="${PUID:-99}"
|
||||||
|
gid="${PGID:-100}"
|
||||||
|
case "$uid$gid" in
|
||||||
|
*[!0-9]*|"")
|
||||||
|
echo "PUID e PGID devono essere numeri (adesso: PUID=$uid PGID=$gid)." >&2
|
||||||
|
exit 64
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
mkdir -p /data
|
||||||
|
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.
|
||||||
|
find /data -xdev \( ! -user "$uid" -o ! -group "$gid" \) -exec chown -h "$uid:$gid" {} +
|
||||||
|
chmod 700 /data
|
||||||
|
|
||||||
|
export HOME=/tmp
|
||||||
|
exec setpriv --reuid="$uid" --regid="$gid" --clear-groups -- dotnet "$app" "$@"
|
||||||
@@ -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"
|
||||||
+11
-2
@@ -1,11 +1,14 @@
|
|||||||
# Development only (SPEC 3): the app plus a local PostgreSQL. Never used in production.
|
# Development only (SPEC 3): the app plus a local PostgreSQL. Never used in production.
|
||||||
# Start: docker compose up --build Health: curl http://localhost:8787/health
|
# Start: docker compose up --build Health: curl http://localhost:8787/health
|
||||||
|
# First access at http://localhost:8787 with ANUBIS_ADMIN_PASSWORD, then choose a new password.
|
||||||
services:
|
services:
|
||||||
anubis:
|
anubis:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: deploy/docker/Dockerfile
|
dockerfile: deploy/docker/Dockerfile
|
||||||
image: gitea.encke-hake.ts.net/balbosoft/anubis:dev
|
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:
|
ports:
|
||||||
- "8787:8787"
|
- "8787:8787"
|
||||||
environment:
|
environment:
|
||||||
@@ -15,6 +18,9 @@ services:
|
|||||||
ANUBIS_DB_NAME: anubis
|
ANUBIS_DB_NAME: anubis
|
||||||
ANUBIS_DB_USER: anubis
|
ANUBIS_DB_USER: anubis
|
||||||
ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}
|
ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}
|
||||||
|
# Development values only: a real installation chooses its own (deploy/unraid/anubis.xml).
|
||||||
|
ANUBIS_SECRET_KEY: ${ANUBIS_SECRET_KEY:-dev-only-secret-key-change-me-0123456789}
|
||||||
|
ANUBIS_ADMIN_PASSWORD: ${ANUBIS_ADMIN_PASSWORD:-dev-only-change-me}
|
||||||
ANUBIS_ALLOW_LIVE: "0"
|
ANUBIS_ALLOW_LIVE: "0"
|
||||||
TZ: Europe/Rome
|
TZ: Europe/Rome
|
||||||
volumes:
|
volumes:
|
||||||
@@ -25,6 +31,9 @@ services:
|
|||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:18
|
image: postgres:18
|
||||||
|
# An init as PID 1 and a pg_isready that gives up before Docker does (ADR 0015): otherwise a slow health check
|
||||||
|
# leaves pg_isready to PostgreSQL, and its exit makes the server restart every connection.
|
||||||
|
init: true
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_DB: anubis
|
POSTGRES_DB: anubis
|
||||||
POSTGRES_USER: anubis
|
POSTGRES_USER: anubis
|
||||||
@@ -32,9 +41,9 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:55432:5432"
|
- "127.0.0.1:55432:5432"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U anubis -d anubis"]
|
test: ["CMD-SHELL", "pg_isready -U anubis -d anubis -t 5"]
|
||||||
interval: 3s
|
interval: 3s
|
||||||
timeout: 3s
|
timeout: 15s
|
||||||
retries: 20
|
retries: 20
|
||||||
volumes:
|
volumes:
|
||||||
- postgres-data:/var/lib/postgresql
|
- postgres-data:/var/lib/postgresql
|
||||||
|
|||||||
+79
-10
@@ -128,9 +128,10 @@ 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing |
|
||||||
|
| M6 | API Messages di Anthropic: intestazioni `x-api-key` e `anthropic-version` | confermato | Anubis manda `anthropic-version: 2026-10-21`, la più recente alla verifica del 01/12/2026. Questa versione rifiuta `temperature`, `top_p` e `top_k`: Anubis non li manda ad Anthropic. Non è stata provata con una chiave vera: i test usano risposte d'esempio. | https://platform.claude.com/docs/en/api/versioning |
|
||||||
|
|
||||||
L'identificativo del modello resta una voce di configurazione, mai una costante nel codice (SPEC 4.5).
|
L'identificativo del modello resta una voce di configurazione, mai una costante nel codice (SPEC 4.5).
|
||||||
|
|
||||||
@@ -151,12 +152,72 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio
|
|||||||
| A2 conto reale italiano | Anubis funziona tutto in paper. L'apertura del conto reale è una voce di `GO-LIVE.md`. | 2, 9 |
|
| A2 conto reale italiano | Anubis funziona tutto in paper. L'apertura del conto reale è una voce di `GO-LIVE.md`. | 2, 9 |
|
||||||
| A3 crypto su Alpaca | L'adapter Alpaca non espone la crypto. | 2 |
|
| A3 crypto su Alpaca | L'adapter Alpaca non espone la crypto. | 2 |
|
||||||
| A5 notizie Alpaca nel piano gratuito | Fonte facoltativa (`news.alpaca.enabled`): si spegne da sola se risponde 401/403; restano le fonti della sezione 4.4. | 7 |
|
| A5 notizie Alpaca nel piano gratuito | Fonte facoltativa (`news.alpaca.enabled`): si spegne da sola se risponde 401/403; restano le fonti della sezione 4.4. | 7 |
|
||||||
| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo. | 3 |
|
| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo (in attesa dell'utente). | 3 |
|
||||||
| O7 liquidità | Elenco fisso di coppie ammesse e filtro sullo spread prima di ogni ordine. | 3, 5 |
|
| O7 liquidità | Elenco fisso di coppie ammesse (Fase 2); il filtro sullo spread prima di ogni ordine arriva con le strategie. | 5 |
|
||||||
|
| Permessi delle chiavi Alpaca | Alpaca non ha permessi per chiave né un modo di leggerli: Anubis tratta ogni chiave come capace di ordinare e mai di prelevare, e usa solo il conto paper. | 3 |
|
||||||
|
| Riuso dell'id d'ordine dopo la chiusura | Anubis non lo riusa mai: ogni ordine ha un id nuovo e deterministico (ADR 0001). | 3 |
|
||||||
|
| Attività `FEE` e dividendi di Alpaca | Il conto paper non li simula: si confrontano con la riconciliazione quando ci saranno le chiavi (ADR 0009). | 3, 6 |
|
||||||
| F3b limite del calendario | Una richiesta all'ora, al massimo una ogni 5 minuti anche ai riavvii; la pagina di blocco conta come errore. | 2 |
|
| F3b limite del calendario | Una richiesta all'ora, al massimo una ogni 5 minuti anche ai riavvii; la pagina di blocco conta come errore. | 2 |
|
||||||
| M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 |
|
| M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 |
|
||||||
| V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 |
|
| V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 |
|
||||||
| V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 |
|
| V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 |
|
||||||
|
| Storia dei flag ETF e frazionabile | Gli universi passati usano i flag di oggi; il limite è scritto nel rapporto della prova storica. | 4 |
|
||||||
|
| Barre dei titoli tolti dalla borsa su Alpaca | Da controllare con le chiavi del conto di prova; fino ad allora gli universi passati vanno letti come ottimisti. | 2, 4 |
|
||||||
|
| Minuti senza scambi su OKX | Il buco si riscarica una volta, poi resta segnato come non recuperabile e non blocca nulla. | 2 |
|
||||||
|
|
||||||
|
## Verifiche della Fase 2 (dati di mercato)
|
||||||
|
|
||||||
|
Fatti controllati scrivendo gli adapter dei dati, il 10/11/2026. Le risposte registrate stanno in `tests/Anubis.Tests/Fixtures` e i test le leggono senza rete.
|
||||||
|
|
||||||
|
| Fonte | Fatto | Come è stato verificato |
|
||||||
|
|---|---|---|
|
||||||
|
| OKX | `history-candles` con `1Dutc` dà lo storico giornaliero intero di BTC-EUR, ETH-EUR e SOL-EUR dal 21/11/2023: 1.085 giorni ciascuna, senza buchi né anomalie. | Prova reale `RealHistoryProof` (categoria LiveDemo) |
|
||||||
|
| OKX | Una candela con `confirm` = 0 è ancora aperta: lo storico la scarta e il flusso dal vivo la salva solo quando si chiude. | Risposte registrate di `candles` e del WebSocket |
|
||||||
|
| OKX | Finanziamento e open interest di BTC-USDT-SWAP rispondono senza chiave su eea.okx.com. | Risposte registrate |
|
||||||
|
| Alpaca | Con il piano gratuito una richiesta `feed=sip` che arriva a meno di 15 minuti fa risponde `{"code":42210000,"message":"subscription does not permit querying recent SIP data"}`. | Esempio della FAQ di Alpaca (`errors.md` nei fixture) |
|
||||||
|
| Alpaca | Le barre giornaliere hanno l'orario della mezzanotte di New York: il giorno della barra è la data di New York. `adjustment=raw` e `adjustment=all` si chiedono separatamente. | Esempi della documentazione |
|
||||||
|
| Alpaca | Le chiavi si leggono solo da `ALPACA_API_KEY_DEMO` e `ALPACA_API_SECRET_DEMO`, quelle del conto di prova. Senza chiavi nessuna chiamata parte verso Alpaca. | Test `ServerCollectsWithoutAlpacaKeysAndSaysWhatIsOff` |
|
||||||
|
| BCE | Lo storico completo è nello zip `eurofxref-hist.zip` (CSV dal più recente, virgola finale su ogni riga, `N/A` dove manca); poi basta il file a 90 giorni o quello giornaliero. | Risposte registrate |
|
||||||
|
| Forex Factory | Se al posto del JSON arriva una pagina di blocco, la lettura fallisce e conta come errore della fonte; il calendario già salvato resta. | Test |
|
||||||
|
| Fed e BCE | Calendari 2026–2027 letti dalle pagine ufficiali; la Fed avverte che ogni data è provvisoria fino alla riunione precedente. Per questo l'elenco è un'impostazione modificabile in Impostazioni → Dati. | `central-banks.md` nei fixture |
|
||||||
|
| alternative.me | Valori giornalieri con timestamp Unix in secondi. Anubis chiede 400 giorni la prima volta e poi solo gli ultimi 2. | Risposte registrate |
|
||||||
|
| nasdaqtraded.txt | La colonna ETF non segna molti ETN e nessun fondo chiuso: Anubis legge anche il nome del titolo. I codici delle borse comprendono ora anche `F` (Texas Stock Exchange) e `M` (NYSE Texas). | File del 10/11/2026 |
|
||||||
|
| Binance | Ogni zip mensile ha accanto un file `.CHECKSUM` con lo SHA-256; i timestamp passano dai millisecondi ai microsecondi da gennaio 2025. Il primo giorno di BTCUSDT è il 17/08/2017; il mese in corso non è ancora pubblicato. | Prova reale: 3.363 giorni dal 17/08/2017 al 31/10/2026 |
|
||||||
|
|
||||||
|
**Distorsioni che restano negli universi a una data passata**
|
||||||
|
- I flag di oggi (frazionabile su Alpaca, ETF in `nasdaqtraded.txt`) valgono anche per le date passate: le fonti gratuite non hanno la storia di questi flag.
|
||||||
|
- Un titolo che ha cambiato simbolo è riconosciuto come fondo solo se il nome lo dice.
|
||||||
|
- Non è verificato che Alpaca dia le barre dei titoli tolti dalla borsa: se mancano, gli universi passati sono un po' troppo ottimisti (distorsione dei sopravvissuti). Si controlla con le chiavi del conto di prova.
|
||||||
|
|
||||||
|
**Non verificabile senza scambi reali**
|
||||||
|
- Se OKX ometta i minuti senza scambi o li dia a volume zero. Il collector tratta un minuto mancante come buco, lo riscarica una volta e poi lo segna "non recuperabile, forse minuti senza scambi".
|
||||||
|
|
||||||
|
## Verifiche della Fase 3 (conti e ordini)
|
||||||
|
|
||||||
|
Fatti controllati sulla documentazione ufficiale il 10/11/2026, scrivendo la parte conti degli adapter. Nessuna chiave, nessun ordine: le risposte d'esempio della documentazione stanno in `tests/Anubis.Tests/Fixtures/alpaca-trading` e `okx-trading`, e la batteria di conformità (`BrokerConformanceTests`) le usa senza rete.
|
||||||
|
|
||||||
|
| Fonte | Fatto | Cosa fa Anubis |
|
||||||
|
|---|---|---|
|
||||||
|
| Alpaca | Gli ordini su frazioni di azione accettano solo la validità `day`, stop compresi; con `gtc` la risposta è 422 "fractional orders must be DAY orders". | Stop `gtc` sulle azioni intere; sulla parte frazionaria uno stop `day` rimesso a ogni seduta (ADR 0009, punto 8). |
|
||||||
|
| Alpaca | `client_order_id` fino a 128 caratteri; un id già usato da un ordine attivo dà 422 con codice 40010001. Non è scritto se si possa riusare dopo la chiusura. | Id deterministici `ANU…`, mai riusati; un 422 di id doppio significa che l'invio precedente è arrivato, e l'ordine si rilegge con `orders:by_client_order_id`. |
|
||||||
|
| Alpaca | Prezzi limite e stop: 2 decimali da 1 $ in su, 4 sotto; altrimenti 422 42210000 "sub-penny increment". | I prezzi si arrotondano prima dell'invio, verso il lato prudente. |
|
||||||
|
| Alpaca | Nessuna commissione. Tasse dal listino del 12/10/2026: SEC 0,0000206 sul controvalore delle vendite, FINRA TAF a zero, CAT 0,000003 $ per azione su acquisti e vendite, arrotondate per eccesso al centesimo una volta al giorno. | Il simulatore le arrotonda per eccesso a ogni esecuzione (più prudente). |
|
||||||
|
| Alpaca | Il conto paper non simula tasse né dividendi; il 10% delle esecuzioni è parziale a caso. | Le attività `FEE` e `DIV` si leggono ma si confrontano con il registro solo con le chiavi. |
|
||||||
|
| Alpaca | Le chiavi non hanno permessi né un modo per leggerli; l'unico segnale è `transfers_blocked` del conto. | Una chiave Alpaca vale "ordina, non preleva". Anubis la usa solo verso il conto paper. |
|
||||||
|
| Alpaca | Gli ordini `gtc` si annullano da soli dopo 90 giorni (`expires_at`). | Il gestore rimette lo stop quando lo vede chiuso. |
|
||||||
|
| Alpaca | Il flusso `trade_updates` ha due eventi in più (`order_replace_rejected`, `order_cancel_rejected`) e lo stato `held`. | Lo stato si prende dall'ordine dentro il messaggio; uno stato sconosciuto conta come "inviato" e le esecuzioni arrivano comunque dalla richiesta REST. |
|
||||||
|
| OKX | `clOrdId` è unico solo tra gli ordini aperti; il doppione dà 51016 ("Client order ID already exists"), 51065 per gli algoritmici. | 51016 e 51065 vogliono dire "l'invio precedente è arrivato": si rilegge l'ordine invece di rimandarlo. |
|
||||||
|
| OKX | Un ordine annullato senza esecuzioni sparisce dallo storico dopo 2 ore. | Un ordine OKX sconosciuto al broker da più di 2 ore si considera annullato (ADR 0009). |
|
||||||
|
| OKX | Le esecuzioni non hanno un `fillId`: la chiave è `tradeId`, unica per strumento. | Ogni esecuzione si registra una volta come `instId:tradeId`. |
|
||||||
|
| OKX | Un ordine market spot che supera il saldo viene ridotto e eseguito, non rifiutato. | Il registro prende la quantità eseguita davvero, non quella chiesta. |
|
||||||
|
| OKX | Gli ordini trigger (stop) non bloccano le monete: se allo scatto il saldo è minore, OKX vende quello che c'è. | Gli stop seguono la quantità della posizione dopo ogni esecuzione. |
|
||||||
|
| OKX | `account/config` dà `perm` con `read_only`, `trade`, `withdraw`, e `feeType` (0 commissione nella moneta ricevuta, 1 nella valuta di quotazione). La chiave d'esempio della documentazione ha `withdraw`. | La chiave d'esempio è rifiutata (test `KeysAreAskedToTheBrokerBeforeTheyAreKept`); una chiave con `withdraw` tiene il conto in modalità prudente. |
|
||||||
|
| OKX | Il canale `orders` è su `/ws/v5/private` e non manda lo stato iniziale; `orders-algo` è su `/ws/v5/business`. | Il flusso serve solo ad accorgersi prima: ordini ed esecuzioni si rileggono comunque via REST a intervalli regolari, che coprono anche i buchi del flusso. |
|
||||||
|
| OKX | La pagina delle tariffe e l'esempio di `trade-fee` mostrano ancora 0,08% maker e 0,10% taker; l'avviso per l'Europa dice 0,10% e 0,20% dal 25/09/2026 (O5). | Il simulatore usa la tariffa più alta; con le chiavi vale `trade-fee` del conto. |
|
||||||
|
|
||||||
|
**In attesa delle chiavi dei conti di prova**
|
||||||
|
- Le classi `AlpacaPaperConformance` e `OkxDemoConformance` (categoria `LiveDemo`) eseguono la stessa batteria sui veri conti di prova. Senza chiavi risultano "in attesa dell'utente".
|
||||||
|
- Da controllare con le chiavi: l'elenco delle coppie del demo europeo (O3b), se OKX chieda `tradeQuoteCcy` ai conti europei, i caratteri ammessi in `client_order_id` su Alpaca.
|
||||||
|
|
||||||
## Versioni di .NET e dei pacchetti ammessi
|
## Versioni di .NET e dei pacchetti ammessi
|
||||||
|
|
||||||
@@ -170,9 +231,9 @@ Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già
|
|||||||
| `Microsoft.NET.Test.Sdk` | 18.11.0 | MIT | Fase 0 | https://www.nuget.org/packages/Microsoft.NET.Test.Sdk |
|
| `Microsoft.NET.Test.Sdk` | 18.11.0 | MIT | Fase 0 | https://www.nuget.org/packages/Microsoft.NET.Test.Sdk |
|
||||||
| `Microsoft.Data.Sqlite` | 10.0.14 | MIT | Fase 1 | https://www.nuget.org/packages/Microsoft.Data.Sqlite/10.0.14 |
|
| `Microsoft.Data.Sqlite` | 10.0.14 | MIT | Fase 1 | https://www.nuget.org/packages/Microsoft.Data.Sqlite/10.0.14 |
|
||||||
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
||||||
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 10 | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 1 (la custodia della chiave dei segreti su desktop nasce con lo strato di piattaforma) | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
||||||
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
||||||
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Fase 8 | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Autorizzati ma non usati: i modelli sono scritti in casa (ADR 0018) | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
||||||
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
||||||
| `Microsoft.ML.Tokenizers` | 2.0.1 | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.Tokenizers/2.0.1 |
|
| `Microsoft.ML.Tokenizers` | 2.0.1 | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.Tokenizers/2.0.1 |
|
||||||
|
|
||||||
@@ -202,14 +263,22 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
|
|||||||
|
|
||||||
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 | Contiene la libreria nativa di SQLite. |
|
| `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 | — |
|
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | — | Non entra: Microsoft.ML non si usa (ADR 0018) |
|
||||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | — | Non entra: LightGBM non si usa (ADR 0018). |
|
||||||
| `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. |
|
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||||
|
|
||||||
## Immagini Docker
|
## Immagini Docker
|
||||||
|
|
||||||
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
||||||
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Si aggiunge nella Fase 8, insieme a LightGBM.
|
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Non serve: LightGBM non si usa (ADR 0018).
|
||||||
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
||||||
|
|
||||||
|
## Carattere
|
||||||
|
|
||||||
|
- **Instrument Sans**, di Rodrigo Fuenzalida e Jordan Egstad, licenza SIL OFL 1.1 (ammesso dall'ADR 0004). Scaricato il 10/11/2026 con il permesso dell'utente, dalla raccolta ufficiale di Google Fonts.
|
||||||
|
- File: `InstrumentSans[wdth,wght].ttf`, 194.336 byte, SHA-256 `b24f1812584816958afcf22e22d08e44318c5e51651e25d2438efdde389b33b1`. È un solo file variabile con pesi da 400 a 700. Nel repository si chiama `src/Anubis.Server/Assets/InstrumentSans.ttf`.
|
||||||
|
- La licenza è accanto al file, in `InstrumentSans-OFL.txt`, e l'applicazione la serve su `/assets/InstrumentSans-OFL.txt`.
|
||||||
|
- La versione corsiva non è inclusa: l'interfaccia quasi non la usa, e il browser la ricava dal carattere normale.
|
||||||
|
- Fonte: https://github.com/google/fonts/tree/main/ofl/instrumentsans
|
||||||
+118
-117
@@ -10,12 +10,12 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
|
|||||||
| Fase | Titolo | Stato |
|
| Fase | Titolo | Stato |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Completata |
|
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Completata |
|
||||||
| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Da fare |
|
| 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) | Da fare |
|
| 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) | Da fare |
|
| 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 |
|
| 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) | Da fare |
|
| 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) | Da fare |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Da fare |
|
||||||
@@ -53,30 +53,30 @@ Le basi su cui si appoggia tutto: piattaforma, database, sicurezza, guscio dell'
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione
|
- [x] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione
|
||||||
- [ ] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL
|
- [x] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL
|
||||||
- [ ] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni
|
- [x] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni
|
||||||
- [ ] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati
|
- [x] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati
|
||||||
- [ ] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP
|
- [x] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP
|
||||||
- [ ] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket
|
- [x] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket
|
||||||
- [ ] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani
|
- [x] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani
|
||||||
- [ ] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni
|
- [x] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni
|
||||||
- [ ] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`)
|
- [x] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`)
|
||||||
- [ ] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck)
|
- [x] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck)
|
||||||
- [ ] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1`
|
- [x] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Accesso funzionante
|
- [x] Accesso funzionante
|
||||||
- [ ] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati)
|
- [x] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati)
|
||||||
- [ ] I formati numerici superano i test
|
- [x] I formati numerici superano i test
|
||||||
- [ ] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres`
|
- [x] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres`
|
||||||
- [ ] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database
|
- [x] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database
|
||||||
- [ ] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola
|
- [x] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola
|
||||||
- [ ] La stessa batteria di test passa su entrambi i motori
|
- [x] La stessa batteria di test passa su entrambi i motori
|
||||||
- [ ] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi
|
- [x] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi
|
||||||
- [ ] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml`
|
- [x] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml`
|
||||||
- [ ] La modalità dimostrativa non tocca il database configurato (test)
|
- [x] La modalità dimostrativa non tocca il database configurato (test)
|
||||||
|
|
||||||
## Fase 2 — Dati di mercato
|
## Fase 2 — Dati di mercato
|
||||||
|
|
||||||
@@ -86,22 +86,22 @@ Storico e dati dal vivo affidabili, controllati e senza sguardi in avanti.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#18](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/18) Catalogo degli strumenti e parte dati dell'adapter OKX Europe
|
- [x] [#18](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/18) Catalogo degli strumenti e parte dati dell'adapter OKX Europe
|
||||||
- [ ] [#19](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/19) Parte dati dell'adapter Alpaca (piano gratuito)
|
- [x] [#19](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/19) Parte dati dell'adapter Alpaca (piano gratuito)
|
||||||
- [ ] [#20](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/20) Collector storico e dal vivo, recupero dei buchi, controlli di qualità, freschezza
|
- [x] [#20](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/20) Collector storico e dal vivo, recupero dei buchi, controlli di qualità, freschezza
|
||||||
- [ ] [#21](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/21) Importatori: archivi Binance e CSV dell'utente verso lo storico di ricerca
|
- [x] [#21](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/21) Importatori: archivi Binance e CSV dell'utente verso lo storico di ricerca
|
||||||
- [ ] [#22](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/22) Calendari e cambi: calendario di borsa, EUR/USD BCE, calendario economico, trimestrali, umore
|
- [x] [#22](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/22) Calendari e cambi: calendario di borsa, EUR/USD BCE, calendario economico, trimestrali, umore
|
||||||
- [ ] [#23](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/23) Azioni societarie e serie rettificate ancorate al giorno della decisione
|
- [x] [#23](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/23) Azioni societarie e serie rettificate ancorate al giorno della decisione
|
||||||
- [ ] [#24](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/24) Universi "a una certa data" con esclusione degli ETF
|
- [x] [#24](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/24) Universi "a una certa data" con esclusione degli ETF
|
||||||
- [ ] [#25](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/25) Chiusura della fase, revisione indipendente e tag `fase-2`
|
- [x] [#25](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/25) Chiusura della fase, revisione indipendente e tag `fase-2`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Storico giornaliero delle crypto dall'inizio disponibile (coppie in EUR di OKX, più gli archivi Binance dal 2017) e delle azioni dal 2016
|
- [ ] Storico giornaliero delle crypto dall'inizio disponibile (coppie in EUR di OKX, più gli archivi Binance dal 2017) e delle azioni dal 2016 — **crypto fatto** (BTC, ETH e SOL in EUR dal 21/11/2023, BTCUSDT dal 17/08/2017); **azioni in attesa dell'utente** (chiavi del conto di prova Alpaca)
|
||||||
- [ ] Senza chiavi Alpaca la parte azionaria si prova su dati sintetici e risposte d'esempio, e il criterio resta in attesa dell'utente
|
- [x] Senza chiavi Alpaca la parte azionaria si prova su dati sintetici e risposte d'esempio, e il criterio resta in attesa dell'utente
|
||||||
- [ ] Un test stacca il flusso per 10 minuti e verifica che il buco venga recuperato
|
- [x] Un test stacca il flusso per 10 minuti e verifica che il buco venga recuperato
|
||||||
- [ ] Rapporto di qualità dei dati
|
- [x] Rapporto di qualità dei dati
|
||||||
- [ ] L'elenco dell'universo azionario a tre date passate non contiene ETF
|
- [x] L'elenco dell'universo azionario a tre date passate non contiene ETF
|
||||||
|
|
||||||
## Fase 3 — Conti, ordini, contabilità
|
## Fase 3 — Conti, ordini, contabilità
|
||||||
|
|
||||||
@@ -111,22 +111,22 @@ Ordini sicuri e ogni euro tracciato.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#26](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/26) Conti e ordini nell'interfaccia BrokerAdapter e simulatore interno (PaperBroker)
|
- [x] [#26](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/26) Conti e ordini nell'interfaccia BrokerAdapter e simulatore interno (PaperBroker)
|
||||||
- [ ] [#27](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/27) OMS: macchina a stati, identificativi deterministici, limite che insegue, ritmo degli invii
|
- [x] [#27](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/27) OMS: macchina a stati, identificativi deterministici, limite che insegue, ritmo degli invii
|
||||||
- [ ] [#28](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/28) Stop di protezione: stop sul broker, stop che seguono la quantità, stop già superato, residui invendibili
|
- [x] [#28](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/28) Stop di protezione: stop sul broker, stop che seguono la quantità, stop già superato, residui invendibili
|
||||||
- [ ] [#29](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/29) Ambienti, capitale affidato e contabilità: registro, lotti, patrimonio, rendimento corretto
|
- [x] [#29](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/29) Ambienti, capitale affidato e contabilità: registro, lotti, patrimonio, rendimento corretto
|
||||||
- [ ] [#30](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/30) Riconciliazione con i conti e modalità prudente
|
- [x] [#30](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/30) Riconciliazione con i conti e modalità prudente
|
||||||
- [ ] [#31](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/31) Adapter Alpaca (paper) e OKX (demo) e batteria di conformità `live_demo`
|
- [x] [#31](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/31) Adapter Alpaca (paper) e OKX (demo) e batteria di conformità `live_demo`
|
||||||
- [ ] [#32](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/32) Schermata Conti e posizioni; conti in Impostazioni e nel primo avvio
|
- [x] [#32](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/32) Schermata Conti e posizioni; conti in Impostazioni e nel primo avvio
|
||||||
- [ ] [#33](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/33) Chiusura della fase, revisione indipendente e tag `fase-3`
|
- [x] [#33](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/33) Chiusura della fase, revisione indipendente e tag `fase-3`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] I test di proprietà contabili passano
|
- [x] I test di proprietà contabili passano (`RandomFillsNeverBreakTheBooks`: esecuzioni casuali a seme fisso, registro, lotti e liquidità sempre in pari)
|
||||||
- [ ] La batteria di conformità passa sul simulatore e, se le chiavi demo ci sono, sui due conti di prova (altrimenti su risposte d'esempio, criterio in attesa dell'utente)
|
- [ ] La batteria di conformità passa sul simulatore e, se le chiavi demo ci sono, sui due conti di prova (altrimenti su risposte d'esempio, criterio in attesa dell'utente) — **simulatore e risposte d'esempio fatti** (`PaperBrokerConformance`, `AlpacaDocConformance`, `OkxDocConformance`); **conti di prova in attesa dell'utente** (`AlpacaPaperConformance`, `OkxDemoConformance`)
|
||||||
- [ ] I test con guasti di questa parte passano
|
- [x] I test con guasti di questa parte passano (risposta persa e mai rimandata, esecuzioni doppie, broker che non risponde, stop scattato senza avviso, differenze non spiegate: `OrderManagerTests`, `ReconcilerTests`)
|
||||||
- [ ] Un test dimostra che gli adapter rifiutano un ambiente reale senza il consenso della configurazione d'avvio, in Docker e su desktop
|
- [x] Un test dimostra che gli adapter rifiutano un ambiente reale senza il consenso della configurazione d'avvio, in Docker e su desktop (`RealAccountsAreRefusedWithoutTheStartupConsent`, `BrokerAdaptersRefuseARealAccountBeforeAnyRequest`)
|
||||||
- [ ] La schermata Conti e posizioni corrisponde al mockup
|
- [x] La schermata Conti e posizioni corrisponde al mockup (`TheDemoShowsTheFiguresOfTheMockup` e screenshot a 1440 e 390 px, chiaro e scuro)
|
||||||
|
|
||||||
## Fase 4 — Backtest e laboratorio
|
## Fase 4 — Backtest e laboratorio
|
||||||
|
|
||||||
@@ -136,17 +136,17 @@ Un motore di prova onesto, riproducibile e protetto dall'auto-inganno.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#34](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/34) Motore di backtest a eventi, modelli di costo e metriche
|
- [x] [#34](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/34) Motore di backtest a eventi, modelli di costo e metriche
|
||||||
- [ ] [#35](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/35) Convalide: finestre che avanzano, K-fold purgato combinatorio, DSR, PBO; registro delle prove
|
- [x] [#35](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/35) Convalide: finestre che avanzano, K-fold purgato combinatorio, DSR, PBO; registro delle prove
|
||||||
- [ ] [#36](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/36) Rapporto di backtest e schermata Laboratorio
|
- [x] [#36](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/36) Rapporto di backtest e schermata Laboratorio
|
||||||
- [ ] [#37](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/37) Chiusura della fase, revisione indipendente e tag `fase-4`
|
- [x] [#37](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/37) Chiusura della fase, revisione indipendente e tag `fase-4`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Una strategia giocattolo con risultato noto dà esattamente il risultato atteso
|
- [x] Una strategia giocattolo con risultato noto dà esattamente il risultato atteso (`AToyStrategyGivesExactlyTheResultComputedByHand`, `TheMetricsOfTheToyRunAreThoseComputedByHand`: patrimonio, commissioni ed esecuzioni calcolati a mano, al centesimo)
|
||||||
- [ ] Il test anti-sguardo-avanti esiste e fallisce su una strategia volutamente scorretta
|
- [x] Il test anti-sguardo-avanti esiste e fallisce su una strategia volutamente scorretta (`TheLookAheadTestCatchesAStrategyThatReadsTomorrow`)
|
||||||
- [ ] DSR e PBO riproducono i casi noti di 12.2
|
- [x] DSR e PBO riproducono i casi noti di 12.2 (`TheDeflatedSharpeRatioReproducesTheExampleOfTheArticle`: DSR 0,9004 dell'articolo; PBO circa 0,5 sul rumore, 0 con una variante dominante, 1 quando la migliore perde sempre fuori campione)
|
||||||
- [ ] Il rapporto si apre dall'interfaccia
|
- [x] Il rapporto si apre dall'interfaccia (`TheReportOpensFromTheLaboratory`: test pianificato dal modulo, eseguito, rapporto e confronto aperti)
|
||||||
|
|
||||||
## Fase 5 — Strategie, portafoglio, rischio
|
## Fase 5 — Strategie, portafoglio, rischio
|
||||||
|
|
||||||
@@ -156,25 +156,25 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
|
- [x] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
|
||||||
- [ ] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum`
|
- [x] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum`
|
||||||
- [ ] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev`
|
- [x] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev`
|
||||||
- [ ] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento
|
- [x] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento
|
||||||
- [ ] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza
|
- [x] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza
|
||||||
- [ ] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri
|
- [x] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri
|
||||||
- [ ] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
|
- [x] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
|
||||||
- [ ] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari
|
- [x] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari
|
||||||
- [ ] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
|
- [x] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Ogni regola di 9.1 e 9.2 ha il suo test
|
- [x] Ogni regola di 9.1 e 9.2 ha il suo test (`RiskTests` e `RiskEngineTests`: perdita del giorno, della settimana, calo dal massimo a 10 e 15%, capitale investito, posizione singola, quota crypto, rischio della singola operazione, controlli tecnici, niente vendite allo scoperto, protezione per le operazioni in giornata, avviso all'80%, ordini al minuto, file STOP; più `NoRuleEverEnlargesWhatTheStrategyAsked` e `AfterALossNoPurchaseIsLarger` come test di proprietà)
|
||||||
- [ ] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale
|
- [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`)
|
||||||
- [ ] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero
|
- [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`)
|
||||||
- [ ] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio
|
- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 32,8% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome`
|
||||||
- [ ] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione
|
- [x] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione (`AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome`; i due rapporti azionari dicono cosa manca)
|
||||||
- [ ] I test anti-sguardo-avanti passano
|
- [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`)
|
||||||
- [ ] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup
|
- [x] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup (`TheDemoShowsTradesStrategiesAndRiskAsInTheMockups` e confronto a 1440 e 375 px con i mockup 03, 04 e 07)
|
||||||
|
|
||||||
## Fase 6 — Motore dal vivo in simulazione
|
## Fase 6 — Motore dal vivo in simulazione
|
||||||
|
|
||||||
@@ -184,25 +184,25 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione
|
- [x] [#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
|
- [x] [#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)
|
- [x] [#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"
|
- [x] [#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
|
- [x] [#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
|
- [x] [#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] [#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`
|
- [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi
|
- [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`)
|
||||||
- [ ] 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
|
- [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)
|
||||||
- [ ] 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
|
- [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)
|
||||||
- [ ] 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
|
- [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`)
|
||||||
- [ ] 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)
|
- [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)
|
||||||
- [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px)
|
- [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)
|
||||||
- [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale
|
- [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=…`)
|
||||||
- [ ] I comandi Telegram funzionano (o, senza token, superano i test con un finto server)
|
- [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
|
## Fase 7 — Notizie
|
||||||
|
|
||||||
@@ -212,23 +212,24 @@ Le notizie usate per evitare guai, mai per comprare.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata
|
- [x] [#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)
|
||||||
- [ ] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
|
- [ ] [#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) — **in attesa dell'utente**
|
||||||
- [ ] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
|
- [x] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
|
||||||
- [ ] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
|
- [x] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
|
||||||
- [ ] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza
|
- [x] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
|
||||||
- [ ] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario
|
- [x] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza
|
||||||
- [ ] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7`
|
- [x] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario
|
||||||
|
- [x] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**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) — **in attesa dell'utente** (#55)
|
||||||
- [ ] Su un archivio di notizie registrate la deduplica e il collegamento superano i test
|
- [x] Su un archivio di notizie registrate la deduplica e il collegamento superano i test (`TheRecordedArchiveIsGroupedAndLinkedOnBothEngines`, `NamesAreFoundInTheWaysNewspapersWriteThem`, `StoriesAboutDifferentInstrumentsAreNotOne`)
|
||||||
- [ ] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (test dedicato)
|
- [x] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (`MaliciousInstructionsInTheNewsHaveNoEffectOutsideTheSchema`, `BrokenUnicodeInAnAnswerIsRefusedNotThrown`, `AServiceAnswerOfAnyShapeNeverThrows`, `TheSummaryHasNoAddressAndNoInvisibleCharacter`)
|
||||||
- [ ] Senza chiave del modello linguistico tutto funziona
|
- [x] Senza chiave del modello linguistico tutto funziona (`WithoutAKeyNothingIsAskedAndEverythingWorks`)
|
||||||
- [ ] Il tetto di spesa viene rispettato
|
- [x] Il tetto di spesa viene rispettato (`TheDailyCapIsNeverExceeded`, `ABrokenAnswerIsPaidOnceAndNeverStopsTheDiary`, `AStopDuringARequestKeepsItsCost`)
|
||||||
- [ ] Ogni restrizione generata da una notizia compare nel diario con il suo motivo
|
- [x] Ogni restrizione generata da una notizia compare nel diario con il suo motivo (`TheDiarySaysEachRestrictionOnceAndChecksARumourTwoHoursLater`, `ARestrictionLeavesOutThePurchaseAndTheDiarySaysWhy`)
|
||||||
- [ ] La schermata Notizie e mercato corrisponde al mockup
|
- [x] La schermata Notizie e mercato corrisponde al mockup (`TheDemoShowsTheNewsAndTheMarketAsInTheMockup` e confronto a 1440 e 390 px con il mockup 05)
|
||||||
|
|
||||||
## Fase 8 — Apprendimento
|
## Fase 8 — Apprendimento
|
||||||
|
|
||||||
@@ -238,20 +239,20 @@ Un modello che impara dall'esito dei segnali e può solo rimpicciolire le operaz
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#62](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/62) Archivio degli indizi "a una certa data" ed etichette
|
- [x] [#62](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/62) Archivio degli indizi "a una certa data" ed etichette
|
||||||
- [ ] [#63](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/63) Addestramento, convalida, calibrazione e registro dei modelli
|
- [x] [#63](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/63) Addestramento, convalida, calibrazione e registro dei modelli
|
||||||
- [ ] [#64](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/64) Ciclo continuo: modello in carica e sfidante, ombra, deriva, messa da parte
|
- [x] [#64](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/64) Ciclo continuo: modello in carica e sfidante, ombra, deriva, messa da parte
|
||||||
- [ ] [#65](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/65) Altri apprendimenti semplici: scostamento, impatto delle notizie, scoperte in chiaro
|
- [x] [#65](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/65) Altri apprendimenti semplici: scostamento, impatto delle notizie, scoperte in chiaro
|
||||||
- [ ] [#66](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/66) Schermata Apprendimento; Impostazioni sul modello
|
- [x] [#66](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/66) Schermata Apprendimento; Impostazioni sul modello
|
||||||
- [ ] [#67](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/67) Chiusura della fase, revisione indipendente e tag `fase-8`
|
- [x] [#67](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/67) Chiusura della fase, revisione indipendente e tag `fase-8`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Un test dimostra che nessun indizio usa dati successivi alla decisione
|
- [x] Un test dimostra che nessun indizio usa dati successivi alla decisione (`NoClueUsesDataAfterTheDecision`, `NothingSavedOrDatedAfterTheDecisionIsRead`, `ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue`)
|
||||||
- [ ] Il primo modello è addestrato sugli esempi storici con rapporto di convalida
|
- [x] Il primo modello è addestrato sugli esempi storici con rapporto di convalida (`docs/learning/first-model.md`; `TheFirstModelIsTheOneOfItsExamples`, `TheFirstModelTakesChargeAtTheFirstStart`). Solo crypto: le strategie azionarie aspettano lo storico di Alpaca
|
||||||
- [ ] Il moltiplicatore non può superare 1 (test di proprietà)
|
- [x] Il moltiplicatore non può superare 1 (test di proprietà: `TheMultiplierNeverExceedsOne`, `TheFilterNeverMakesAnOrderBigger`)
|
||||||
- [ ] Promozione, scarto e messa da parte sono coperti da test con dati sintetici
|
- [x] Promozione, scarto e messa da parte sono coperti da test con dati sintetici (`AChallengerThatIsReallyBetterIsPromotedAtAThreshold`, `AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases`, `ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack`, `ARisingErrorSetsTheModelAside`, `CluesNeverStudiedSetTheModelAside`)
|
||||||
- [ ] La schermata Apprendimento corrisponde al mockup
|
- [x] La schermata Apprendimento corrisponde al mockup (`TheDemoShowsTheModelAsInTheMockup` e confronto a 1440 e 390 px con il mockup 06)
|
||||||
|
|
||||||
## Fase 9 — Rifinitura e consegna in Docker
|
## Fase 9 — Rifinitura e consegna in Docker
|
||||||
|
|
||||||
|
|||||||
+114
-8
@@ -1,10 +1,10 @@
|
|||||||
# Stato del progetto
|
# Stato del progetto
|
||||||
|
|
||||||
Aggiornato: 2026-11-10
|
Aggiornato: 2026-12-01
|
||||||
|
|
||||||
## Fase corrente
|
## Fase corrente
|
||||||
|
|
||||||
**Fase 0 — Preparazione: completata.** La prossima è la Fase 1 (Fondamenta), da iniziare con il via dell'utente.
|
**Fase 8 — Apprendimento: completata.** La prossima è la Fase 9 — Rifinitura e consegna in Docker. Della Fase 7 resta un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
|
||||||
|
|
||||||
## Fatto
|
## Fatto
|
||||||
|
|
||||||
@@ -34,6 +34,93 @@ Aggiornato: 2026-11-10
|
|||||||
- `/health`.
|
- `/health`.
|
||||||
- Applicazione minima con `GET /health`, `Dockerfile` e `docker-compose.yml` con PostgreSQL 18.
|
- Applicazione minima con `GET /health`, `Dockerfile` e `docker-compose.yml` con PostgreSQL 18.
|
||||||
- CI in `.gitea/workflows/ci.yml`: test su SQLite e PostgreSQL, poi l'immagine. Solo passi `run:`.
|
- CI in `.gitea/workflows/ci.yml`: test su SQLite e PostgreSQL, poi l'immagine. Solo passi `run:`.
|
||||||
|
- **Fase 1** (scelte nell'ADR 0007):
|
||||||
|
- Piattaforma: configurazione d'avvio Docker (variabili) e desktop (`config.toml`), cartella dei dati, identità dell'installazione con impronta del database, custodia della chiave dei segreti (DPAPI su Windows).
|
||||||
|
- Database portabile su PostgreSQL e SQLite con ADO.NET: un solo schema con tipi per motore, migrazioni SQL numerate con salvataggio prima, esportazione e importazione tra motori con controllo di conteggi e totali (`Anubis.Server db export|import`), salvataggi notturni (ne tiene 14).
|
||||||
|
- Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni con registro delle modifiche, segreti cifrati AES-GCM, registri JSON con i segreti oscurati, formati italiani.
|
||||||
|
- Accesso: password PBKDF2, sessioni, CSRF, limite ai tentativi, secondo fattore TOTP facoltativo.
|
||||||
|
- Server: avvio a stati (configurazione, primo avvio, database assente, schema, identità, pronto), pagina d'errore con riprova automatica, API REST e WebSocket dello stato.
|
||||||
|
- Interfaccia: guscio di menu, barra superiore e barra in basso come nei mockup, temi chiaro e scuro, Panoramica, Diario, Rischio, Impostazioni (aspetto, sicurezza, sistema); le altre voci arrivano con le loro fasi.
|
||||||
|
- Modalità dimostrativa (`tasks seed-demo`) con i dati dell'appendice F, in un database a parte.
|
||||||
|
- Immagine Docker definitiva: `PUID`/`PGID`, controllo di salute, l'applicazione non gira come root. Provata con SQLite, PostgreSQL, configurazione sbagliata e database staccato.
|
||||||
|
- `tasks screenshots` per confrontare le schermate con i mockup.
|
||||||
|
- Dopo la chiusura, con il permesso dell'utente: carattere Instrument Sans incluso nell'applicazione (ADR 0007, punto 5).
|
||||||
|
- **Fase 2** (scelte nell'ADR 0008, fatti verificati in `docs/API-NOTES.md`):
|
||||||
|
- Catalogo degli strumenti e parte dati degli adapter OKX Europe (coppie in EUR, candele, prezzi, libro, WebSocket) e Alpaca (barre consolidate reali e rettificate, minuti, calendario, orologio, azioni societarie, flusso IEX).
|
||||||
|
- Collector storico e dal vivo dentro il server: recupero dei buchi, controlli di qualità con seconda lettura immediata, freschezza dei dati, ripresa con attese crescenti.
|
||||||
|
- Storico di ricerca in file `csv.gz` per anno; importatori degli archivi Binance (con controllo SHA-256) e dei CSV dell'utente (`anubis data binance`, `anubis data csv`).
|
||||||
|
- Fonti gratuite: cambi BCE, calendario economico, date FRED e trimestrali Finnhub (con chiave facoltativa), riunioni di Fed e BCE modificabili, umore (Fear & Greed, VIX, finanziamento e open interest di OKX).
|
||||||
|
- Azioni societarie e serie rettificate ancorate al giorno della decisione.
|
||||||
|
- Universi azionario e crypto "a una certa data", senza ETF né fondi.
|
||||||
|
- Rapporto di qualità dei dati (`anubis data report`, `/api/data/quality`) e sezione Dati in Impostazioni con lo stato di ogni fonte.
|
||||||
|
- Prova sui dati reali: BTC, ETH e SOL in EUR dal 21/11/2023 (1.085 giorni ciascuna, nessun buco) e BTCUSDT di Binance dal 17/08/2017 (3.363 giorni).
|
||||||
|
- **Fase 3** (scelte nell'ADR 0009, fatti verificati in `docs/API-NOTES.md`):
|
||||||
|
- Interfaccia comune dei conti (`IBrokerAccount`), simulatore interno (`PaperBroker`) e parte conti degli adapter Alpaca (paper) e OKX (demo). Nessun conto reale viene creato; gli adapter rifiutano l'ambiente reale prima di qualsiasi richiesta.
|
||||||
|
- Gestore degli ordini: stati che vanno solo avanti, id deterministici mai rimandati due volte, limite che insegue il prezzo, al massimo sei invii al minuto con le vendite per prime.
|
||||||
|
- Stop sul broker per ogni posizione: permanenti sulle azioni intere, giornalieri sulle frazioni, sempre allineati alla quantità; stop già superato; residui invendibili.
|
||||||
|
- Contabilità per strategia in sola aggiunta: esecuzioni, lotti, registro della liquidità, capitale affidato in euro diviso per quote, dividendi e frazionamenti, fotografie del patrimonio ogni 5 minuti, rendimento ponderato nel tempo.
|
||||||
|
- Riconciliazione ogni 5 minuti con modalità prudente, scelta "allinea" o "escludi", blocco delle chiavi che permettono i prelievi.
|
||||||
|
- Schermata Conti e posizioni come il mockup, esportazione CSV delle posizioni; in Impostazioni chiavi (verificate col broker prima di salvarle) e capitale affidato; la Panoramica indica il capitale come primo passo.
|
||||||
|
- Batteria di conformità sul simulatore e sulle risposte d'esempio della documentazione; sui conti di prova parte da sola quando ci sono le chiavi.
|
||||||
|
- **Fase 4** (scelte nell'ADR 0010):
|
||||||
|
- Motore di backtest a eventi, una seduta alla volta: si decide sulla chiusura e si esegue all'apertura dopo, con gli stessi costi del simulatore (moltiplicabili per 2 e 3), stop, frazionamenti e dividendi, nessun prestito. Le strategie sono le stesse classi che girano dal vivo; correttivi e rischio hanno già il loro posto e fino alla Fase 5 lasciano passare tutto.
|
||||||
|
- Metriche del rapporto (rendimento, volatilità, Sharpe, calo massimo, operazioni, esposizione, risultati per anno) e confronto con "comprare e tenere".
|
||||||
|
- Convalide scritte in casa: finestre che avanzano, K-fold purgato combinatorio, Deflated Sharpe Ratio, PBO, regola dell'altopiano, test contro lo sguardo in avanti. DSR e PBO riproducono i casi noti.
|
||||||
|
- Registro delle prove: il piano (con le soglie) e la sua impronta si scrivono prima dei risultati e non cambiano; il numero di prove del DSR conta tutti i tentativi della stessa strategia.
|
||||||
|
- Laboratorio su un thread a priorità bassa, una prova alla volta, con ripresa dopo un riavvio; dati dalle barre raccolte o dallo storico di ricerca Binance.
|
||||||
|
- Schermata Laboratorio: elenco delle prove, modulo per un nuovo test, rapporto completo, confronto tra due prove. La sezione "Migliorie in osservazione" aspetta la Fase 9; "Stime di costo da confermare" è arrivata con la Fase 8.
|
||||||
|
- Strategia d'esempio `sma_cross` (incrocio di medie) per provare il laboratorio; le strategie di base arrivano con la Fase 5.
|
||||||
|
- **Fase 5** (scelte nell'ADR 0011):
|
||||||
|
- Le tre strategie di base: `crypto_trend` (rottura su nove periodi, stop a metà del canale, pesi a volatilità obiettivo, universo dei primi dieci del mese), `equity_momentum` (revisione settimanale con il filtro di SPY, pesi a volatilità inversa, stop che segue il prezzo) e `equity_meanrev` (RSI a 2 sopra la media a 200 sedute, rischio fisso, uscita alla chiusura). Le stesse classi girano in prova e dal vivo e passano il test contro lo sguardo in avanti.
|
||||||
|
- Correttivi comuni (regime crypto, calendario economico), dimensionamento sulla quota del bot e motore del rischio completo: limiti di perdita per mondo, calo dal massimo con dimezzamento e interruttore, limiti di dimensione, controlli tecnici, niente vendite allo scoperto né leva. Toglie o riduce, mai aggiunge. Gira anche dentro i backtest.
|
||||||
|
- Ogni passo di una decisione resta scritto con i suoi codici motivo (tabella `decisions`).
|
||||||
|
- 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** (ADR 0013, 0014, 0015, 0016 e 0017):
|
||||||
|
- 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.
|
||||||
|
- Stato per strumento e regole di 10.5 (#59, ADR 0014 punti 9–12):
|
||||||
|
- eventi gravi, notizie negative, trimestrali e dati macro fermano o spostano i nuovi acquisti, contando dal momento del fatto;
|
||||||
|
- una voce non confermata dà solo una riga nel diario e un nuovo controllo dopo 2 ore;
|
||||||
|
- ogni restrizione compare nel diario con il suo motivo, e ogni riga si spegne in Impostazioni;
|
||||||
|
- dopo un'assenza valgono solo le restrizioni ancora in corso;
|
||||||
|
- lo stato di ogni strumento tiene il tono a 1 e 3 giorni, il numero di storie rispetto alla norma e la restrizione in corso.
|
||||||
|
- Schermata Notizie e mercato (#60, ADR 0014 punti 13–14):
|
||||||
|
- l'elenco "cosa ho letto e cosa ne ho fatto" con tre filtri, e per ogni notizia la frase di cosa ha fatto il bot e perché;
|
||||||
|
- l'umore del mercato, il calendario con l'effetto di ogni evento, le fonti e la spesa del giorno;
|
||||||
|
- in Impostazioni → Notizie: le righe di 10.5, le fonti, la chiave e il tetto del modello linguistico, le chiavi di Finnhub e FRED, le riunioni di Fed e BCE;
|
||||||
|
- nella demo la schermata corrisponde al mockup (fotografie con `tasks screenshots /notizie`).
|
||||||
|
- Analista facoltativo con il modello linguistico (#58, ADR 0014 punto 15):
|
||||||
|
- Anthropic, un servizio con l'API di OpenAI oppure Ollama; servizio, modello, indirizzo, prezzi e tetto si scelgono in Impostazioni;
|
||||||
|
- il testo delle notizie viaggia come dato; della risposta vale solo lo schema dell'appendice B, e un giudizio può solo aggiungere una restrizione;
|
||||||
|
- tetto di spesa giornaliero controllato sul costo peggiore prima di ogni richiesta, cache per hash, otto storie per richiesta;
|
||||||
|
- senza chiave non parte nessuna richiesta e tutto funziona come prima.
|
||||||
|
- Esercitazione della guardia: aspetta che la vendita sia partita (#100) e il motore della prova non esce mai dal computer (#102, ADR 0016).
|
||||||
|
- Correzioni della revisione indipendente (#61, ADR 0017): risposte malformate del modello e tetto di spesa, giro delle notizie accanto alla coda dei lavori, nomi e parole chiave, storie di società diverse, inizio delle finestre, trimestrali, acquisti rimandati, confronto a un passo.
|
||||||
|
|
||||||
|
- **Fase 8** (scelte nell'ADR 0018, niente pacchetti nuovi: i modelli sono scritti in casa):
|
||||||
|
- Archivio degli esempi (#62): ogni intenzione d'ingresso, anche rifiutata o in osservazione, diventa un esempio con gli indizi visti in quel momento. L'esito è l'operazione simulata da sola con il motore del backtest.
|
||||||
|
- Addestramento e convalida (#63): regressione logistica, alberi potenziati e foresta, finestre che avanzano e combinazioni purgate, calibrazione, registro dei modelli. `anubis learning base` scrive il primo modello e il suo rapporto in `docs/learning/`; il modello viaggia nel programma e al primo avvio prende il posto in carica, in osservazione.
|
||||||
|
- Ciclo continuo (#64): stime in ombra, controllo ogni notte alle 03:00, messa da parte e rientro automatici, sfidante la domenica, promozione o scarto a soglie fisse, avvio solo con i criteri di 11.5. Il moltiplicatore sta tra 0 e 1 e vale per l'operazione dalla nascita alla chiusura.
|
||||||
|
- Altri apprendimenti (#65): scostamento misurato sulle esecuzioni, impatto delle notizie, scoperte dette a parole.
|
||||||
|
- Schermata Apprendimento come il mockup 06 e sezione del modello in Impostazioni (#66).
|
||||||
|
- Correzioni di due revisioni indipendenti (#67, ADR 0018 punti 17 e 18).
|
||||||
|
|
||||||
## In corso
|
## In corso
|
||||||
|
|
||||||
@@ -41,13 +128,30 @@ Nulla.
|
|||||||
|
|
||||||
## Prossimo passo
|
## Prossimo passo
|
||||||
|
|
||||||
Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, accesso, guscio dell'interfaccia.
|
1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55.
|
||||||
|
2. La Fase 9 — Rifinitura e consegna in Docker, in una nuova sessione, sul branch `fase-9` da `main`.
|
||||||
|
3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
|
||||||
|
|
||||||
## Da sapere
|
## Da sapere
|
||||||
|
|
||||||
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
||||||
|
- 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. Le notizie fuori dalla demo si vedono dalla Fase 7, l'apprendimento dalla Fase 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`.
|
||||||
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
|
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
|
||||||
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
|
- 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 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).
|
||||||
|
- Il primo modello è appena migliore di chi risponde sempre la frequenza di base (errore più basso dello 0,2% e dell'1,1% nelle due prove) e ha studiato solo `crypto_trend`, che è in osservazione. Non cambia nessuna operazione finché non passa i criteri di 11.5. Per rifarlo: `anubis learning base --to AAAA-MM-GG --data-dir … --out docs/learning`, con percorsi assoluti.
|
||||||
|
- 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.
|
||||||
|
- Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2).
|
||||||
- Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale.
|
- Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale.
|
||||||
- Su questo PC Docker Desktop non partiva: erano rimasti due file di comunicazione di una sessione di ottobre, che Windows non riusciva a cancellare. Le cartelle che li contengono sono state rinominate, non cancellate: `%LOCALAPPDATA%\Docker\run.stale*` e `%LOCALAPPDATA%\docker-secrets-engine.stale*`. Si possono eliminare dopo un riavvio.
|
- Su questo PC Docker Desktop non partiva: erano rimasti due file di comunicazione di una sessione di ottobre, che Windows non riusciva a cancellare. Le cartelle che li contengono sono state rinominate, non cancellate: `%LOCALAPPDATA%\Docker\run.stale*` e `%LOCALAPPDATA%\docker-secrets-engine.stale*`. Si possono eliminare dopo un riavvio.
|
||||||
|
|
||||||
@@ -55,12 +159,14 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc
|
|||||||
|
|
||||||
| Cosa | Da quando serve | Senza |
|
| Cosa | Da quando serve | Senza |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Via libera per la Fase 1 | 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 | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa |
|
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria e Alpaca News (#107) spente; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa |
|
||||||
| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa |
|
| Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa |
|
||||||
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
|
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | 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 |
|
||||||
| Chiavi FRED e Finnhub (facoltative, gratuite) | Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
|
| Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme |
|
||||||
|
| Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
|
||||||
|
| Se mandare alla SEC un nome e un contatto, e quali (facoltativo, #107) | Fase 7 | Niente comunicati EDGAR dei singoli titoli; resta il feed generale della SEC |
|
||||||
| Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale |
|
| Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale |
|
||||||
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
|
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
|
||||||
| Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa |
|
| Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa |
|
||||||
|
|||||||
@@ -79,6 +79,30 @@ Un criterio che dipende solo da qualcosa che deve dare l'utente (chiavi dei cont
|
|||||||
|
|
||||||
Per ogni schermata: implementa, apri sui dati dimostrativi (`tasks seed-demo`), fotografa con Edge senza finestra (`msedge --headless --screenshot`) a 1440 e 390 pixel, confronta zona per zona con lo screen di `docs/design/`, correggi, ripeti finché restano differenze trascurabili. I testi fissi si leggono dalle immagini, i dati dall'appendice F, colori e misure dall'appendice C. Guarda uno screen per volta e ritaglia la zona che ti serve: le immagini sono a doppia densità.
|
Per ogni schermata: implementa, apri sui dati dimostrativi (`tasks seed-demo`), fotografa con Edge senza finestra (`msedge --headless --screenshot`) a 1440 e 390 pixel, confronta zona per zona con lo screen di `docs/design/`, correggi, ripeti finché restano differenze trascurabili. I testi fissi si leggono dalle immagini, i dati dall'appendice F, colori e misure dall'appendice C. Guarda uno screen per volta e ritaglia la zona che ti serve: le immagini sono a doppia densità.
|
||||||
|
|
||||||
|
## Debug con Visual Studio Code
|
||||||
|
|
||||||
|
Apri la radice del repository in VS Code con l'estensione C# (`ms-dotnettools.csharp`, suggerita da `.vscode/extensions.json`), poi Esegui e debug (F5). Ogni voce compila il server in Debug (attività `build-server` di `.vscode/tasks.json`) e apre il browser quando il server ascolta:
|
||||||
|
|
||||||
|
- **Anubis: server, dati di prova**: una cartella dati a parte, `artifacts/debug-data`, ignorata da git. Al primo avvio chiede la configurazione iniziale; per ripartire da zero basta cancellare la cartella.
|
||||||
|
- **Anubis: modalità dimostrativa**: i dati dell'appendice F, come `tasks seed-demo`.
|
||||||
|
- **Anubis: server, dati dell'utente**: la cartella vera, `%APPDATA%\Anubis`, come `tasks dev`.
|
||||||
|
- **Anubis: aggancia a un processo**: per un server già avviato, per esempio con `tasks dev`.
|
||||||
|
|
||||||
|
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
|
## 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.
|
- **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.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 0004 — Nessun SDK o componente esterno senza il permesso dell'utente
|
# 0004 — Nessun SDK o componente esterno senza il permesso dell'utente
|
||||||
|
|
||||||
Data: 2026-11-09 · Stato: accettata · Precisata dall'ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8)
|
Data: 2026-11-09 · Stato: accettata · Precisata dagli ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8) e 0007 (`ProtectedData` dalla Fase 1; Instrument Sans scaricato il 10/11/2026)
|
||||||
|
|
||||||
## Contesto
|
## Contesto
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# 0007 — Scelte della Fase 1: database portabile, interfaccia, immagine Docker
|
||||||
|
|
||||||
|
Data: 2026-11-10 · Stato: accettata · Precisa gli ADR 0003, 0004 e 0006, senza aggiungere componenti esterni
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 1 costruisce le fondamenta: piattaforma, database su due motori, accesso, guscio dell'interfaccia, modalità dimostrativa e immagine Docker. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. Un solo schema per i due motori.**
|
||||||
|
- Le migrazioni sono file SQL numerati (`src/Anubis/Db/Migrations`). Lo stesso testo gira su PostgreSQL e SQLite. Le parole tra graffe diventano i tipi del motore:
|
||||||
|
|
||||||
|
| Segno | PostgreSQL | SQLite |
|
||||||
|
|---|---|---|
|
||||||
|
| `{money}` | `NUMERIC(38,18)` | `TEXT` in forma canonica, arrotondato a 18 decimali |
|
||||||
|
| `{timestamp}` | `TIMESTAMPTZ` | `TEXT` ISO 8601 in UTC |
|
||||||
|
| `{uuid}` | `UUID` | `TEXT` |
|
||||||
|
| `{bool}`, `{bytes}`, `{json}`, `{float}` | `BOOLEAN`, `BYTEA`, `JSON`, `DOUBLE PRECISION` | `INTEGER`, `BLOB`, `TEXT`, `REAL` |
|
||||||
|
|
||||||
|
- Su SQLite le tabelle sono `STRICT` e il database lavora con WAL, `synchronous=FULL` e chiavi esterne attive.
|
||||||
|
- Il denaro passa sempre come `decimal` e non è mai `REAL`. `{float}` serve solo a misure che non sono importi.
|
||||||
|
- Lo schema 1 contiene le tabelle che servono adesso e quelle contabili che la modalità dimostrativa riempie (conti, ordini, eseguiti, lotti, liquidità, posizioni, patrimonio, diario, rischio). Le tabelle delle fasi successive (barre, notizie, modelli, prove storiche, segnali) arrivano ciascuna con la propria migrazione.
|
||||||
|
- Prima di ogni migrazione si fa un salvataggio.
|
||||||
|
- I limiti di SQLite restano quelli della specifica: un solo processo scrive, e il file deve stare su un disco locale.
|
||||||
|
|
||||||
|
**2. Il database non si ricrea da solo.**
|
||||||
|
- Un file SQLite già visto che sparisce, mentre l'applicazione gira, è un errore. Non si crea un database nuovo e vuoto al suo posto: compare la pagina d'errore finché il file non torna.
|
||||||
|
- All'avvio il file si crea solo se nella cartella dei dati manca `installation.json`, cioè alla prima installazione.
|
||||||
|
|
||||||
|
**3. Password con PBKDF2, secondo fattore senza codice QR.**
|
||||||
|
- Le password si cifrano con PBKDF2-SHA512 (ADR 0003).
|
||||||
|
- Per il secondo fattore l'interfaccia mostra la chiave in base32 e l'indirizzo `otpauth://`. Non disegna un codice QR, che richiederebbe una libreria esterna o un generatore scritto in casa. Le app di autenticazione accettano la chiave scritta a mano.
|
||||||
|
- La chiave in prova resta sul server, legata alla sessione, per 15 minuti. Non passa mai nell'indirizzo della pagina.
|
||||||
|
|
||||||
|
**4. Interfaccia con rendering statico.**
|
||||||
|
- Le pagine Blazor sono generate sul server e arrivano come HTML semplice. Niente modalità interattiva e niente `blazor.web.js`: per questo il progetto del server imposta `RequiresAspNetWebAssets=false`, e il pacchetto `Microsoft.AspNetCore.App.Internal.Assets` non entra.
|
||||||
|
- I pulsanti sono moduli HTML che inviano ad `/azioni/*`, con il gettone CSRF. La risposta riporta alla pagina (post/redirect/get). Gli errori tornano come codici brevi, mai con i valori scritti dall'utente.
|
||||||
|
- Lo stato dal vivo (bot, freschezza dei dati) arriva da un WebSocket su `/ws`, letto da un piccolo `app.js`.
|
||||||
|
- Fogli di stile, script e logo sono risorse incluse nella DLL. Il logo arriva solo da `docs/design/logo` (ADR 0005).
|
||||||
|
- Le chiavi dei gettoni dei moduli stanno in `web-keys/`, nella cartella dei dati, così un riavvio non rompe le pagine aperte. Sono salvate senza cifratura, ma la cartella dei dati è leggibile solo dall'utente dell'applicazione.
|
||||||
|
|
||||||
|
**5. Instrument Sans incluso nell'applicazione.**
|
||||||
|
- L'ADR 0004 ammette Instrument Sans. L'utente ha dato il permesso di scaricarlo il 10/11/2026, dopo la chiusura della fase. Fino ad allora l'interfaccia usava i caratteri di sistema.
|
||||||
|
- Il file sta in `src/Anubis.Server/Assets/`, con accanto la sua licenza. L'applicazione lo serve da sé e non lo carica mai da internet. Provenienza e impronta sono in `docs/API-NOTES.md`.
|
||||||
|
- C'è un solo file variabile, solo in versione normale. Se il file non arriva, il foglio di stile ripiega sui caratteri di sistema.
|
||||||
|
- Instrument Sans è un po' più largo del carattere di sistema. Nella barra superiore etichette e pulsanti passano a 13 px, come nel mockup, così la riga con la data resta intera a 1440 px.
|
||||||
|
|
||||||
|
**6. Modalità dimostrativa.**
|
||||||
|
- `--demo` crea una cartella dei dati nuova in quella temporanea, con un database SQLite proprio, e non legge mai la configurazione vera.
|
||||||
|
- La modalità dimostrativa:
|
||||||
|
- usa un orologio fermo al 9 ottobre 2026, 08:21;
|
||||||
|
- risponde solo dal computer stesso;
|
||||||
|
- accede da sola;
|
||||||
|
- tiene la chiave dei segreti in un file della propria cartella, per non toccare il portachiavi di Windows.
|
||||||
|
- Carica i dati dell'appendice F solo nelle tabelle che esistono già. Strategie, notizie e apprendimento compaiono quando arrivano le loro fasi.
|
||||||
|
- Gli importi in dollari si mostrano solo qui, con il cambio dei dati d'esempio. Nell'uso vero restano in euro finché la Fase 2 non porta i cambi del giorno.
|
||||||
|
|
||||||
|
**7. Custodia della chiave su desktop dalla Fase 1.** `System.Security.Cryptography.ProtectedData` (già nell'ADR 0004) entra adesso e non nella Fase 10: la chiave dei segreti va custodita da quando nasce lo strato di piattaforma.
|
||||||
|
|
||||||
|
**8. Immagine Docker.**
|
||||||
|
- Il container parte come root solo per preparare `/data` e darla a `PUID:PGID` (99:100 su Unraid). Poi l'applicazione gira con quell'utente tramite `setpriv`, che è già nell'immagine di base. Niente `gosu`.
|
||||||
|
- Il controllo di salute usa `/dev/tcp` di bash su `/health`, perché nell'immagine non ci sono `curl` né `wget`. Un 503 (database che non risponde) conta come container non sano.
|
||||||
|
- `libgomp1` resta rimandata alla Fase 8 (ADR 0006).
|
||||||
|
|
||||||
|
**9. Fotografie con il browser già installato.**
|
||||||
|
- `tasks screenshots` usa Edge o Chrome già presenti sul computer e li guida con il protocollo DevTools, attraverso il `ClientWebSocket` di .NET. Niente Playwright (ADR 0004).
|
||||||
|
- Il protocollo serve per fissare la larghezza esatta: una finestra senza schermo non scende sotto i 500 pixel circa, troppi per il telefono a 390.
|
||||||
|
|
||||||
|
**10. Correzioni della revisione indipendente.**
|
||||||
|
- **Indirizzo di ritorno.** Dopo l'accesso si torna solo a un percorso del sito. Sono esclusi i percorsi con barre rovesciate o caratteri di controllo, perché il browser li toglie e `/␉/altro.sito` diventerebbe `//altro.sito`.
|
||||||
|
- **Solo dal computer.** Desktop e modalità dimostrativa controllano due cose: l'indirizzo di chi chiama e il nome con cui chiama. Sono ammessi solo `localhost`, `127.0.0.1` e `[::1]`. Così una pagina web che fa puntare il proprio nome a 127.0.0.1 (DNS rebinding) non arriva alla procedura guidata né alle scelte della pagina d'errore.
|
||||||
|
- **Limite ai tentativi.**
|
||||||
|
- Ogni tentativo si conta prima di controllare la password, così tentativi in parallelo non passano tutti.
|
||||||
|
- Lo stesso limite vale per la password della configurazione d'avvio chiesta dalla pagina d'errore.
|
||||||
|
- **Secondo fattore.**
|
||||||
|
- Ogni codice vale una volta sola. Il registro sta in memoria: un riavvio lo azzera, ma il codice scade comunque entro 90 secondi.
|
||||||
|
- Per disattivare il secondo fattore servono la password e un codice.
|
||||||
|
- **Pagina d'errore e ciclo d'avvio.**
|
||||||
|
- Una scelta (ripristina, importa, comincia da capo, usa questo) tiene fermo il ciclo d'avvio finché non ha finito, rinnovo dell'identità compreso.
|
||||||
|
- L'identità si controlla prima di migrare. Un database che appartiene a un'altra installazione non viene toccato. Uno vuoto resta vuoto, quindi accoglie anche un salvataggio con uno schema più vecchio.
|
||||||
|
- Dopo un ripristino, un'importazione o "usa questo database", il bot riparte con "Ferma tutto" acceso (SPEC 15.1), qualunque cosa dicesse l'archivio.
|
||||||
|
- Un archivio rovinato dà un messaggio sulla pagina, non un errore del server.
|
||||||
|
- La scelta azzera lo stato dell'applicazione prima di lasciare ripartire il ciclo d'avvio. Prima lo faceva dopo, e il ciclo poteva ripartire nel frattempo: l'applicazione risultava pronta ma senza servizi. Il difetto è emerso nella CI su Linux.
|
||||||
|
- **File SQLite che sparisce durante l'apertura.**
|
||||||
|
- Controllare che il file esista non basta: può sparire tra il controllo e l'apertura, e un'apertura che può creare il file metterebbe al suo posto un database vuoto.
|
||||||
|
- Dopo la prima apertura riuscita, il file si apre solo se c'è già.
|
||||||
|
- **Pagine che leggono prima di disegnare.**
|
||||||
|
- Con il rendering statico Blazor disegna una prima volta mentre `OnInitializedAsync` aspetta ancora.
|
||||||
|
- Con SQLite le letture finiscono subito e il difetto non si vede. Con PostgreSQL la pagina si rompe.
|
||||||
|
- I componenti che leggono dati ereditano da `LoadedComponent` (o `LoadedLayout`): prima leggono, poi disegnano una volta sola.
|
||||||
|
- I test del server ora girano anche su PostgreSQL.
|
||||||
|
- **Docker con SQLite e `/data` non collegata.**
|
||||||
|
- Docker crea un volume anonimo senza `installation.json`, quindi parte un'installazione nuova e vuota. Non si può distinguere da una prima installazione vera.
|
||||||
|
- Il manuale (Fase 9) dirà di controllare la riga "Cartella dei dati" in Impostazioni.
|
||||||
|
|
||||||
|
## Alternative scartate
|
||||||
|
|
||||||
|
- **Tipi diversi per motore scritti a mano in due serie di migrazioni.** Raddoppia il lavoro e lascia divergere i due schemi.
|
||||||
|
- **Blazor interattivo sul server (SignalR).** Una connessione sempre aperta per ogni pagina, più JavaScript del framework, e pagine che smettono di funzionare quando la connessione cade. I moduli semplici funzionano anche senza script.
|
||||||
|
- **Un generatore di codici QR scritto in casa.** È molto codice per un passo che si fa una volta sola.
|
||||||
|
- **Chiedere il pacchetto Playwright.** Il browser già installato fa lo stesso lavoro.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Ogni fase che aggiunge tabelle scrive una nuova migrazione con gli stessi segni, e la prova su entrambi i motori.
|
||||||
|
- Chi apre la modalità dimostrativa vede solo le parti costruite fino a quella fase.
|
||||||
|
- Il WebSocket dello stato non si chiude quando si esce: manda solo lo stato del bot e la freschezza dei dati, e si chiude alla prima riconnessione. Da rivedere quando porterà dati più ricchi.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# 0008 — Scelte della Fase 2: dati di mercato
|
||||||
|
|
||||||
|
Data: 2026-11-10 · Stato: accettata · Precisa la specifica (sezioni 4, 5.3, 6, 10.4) e gli ADR 0003 e 0007, senza aggiungere componenti esterni
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 2 porta in Anubis i dati di mercato: catalogo degli strumenti, storico e flusso dal vivo, controlli di qualità, cambi, calendari, umore del mercato, azioni societarie e universi. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. Storico di ricerca in CSV compresso, non Parquet.**
|
||||||
|
- La specifica (6.6) parla di file Parquet. Leggerli e scriverli richiede un pacchetto che l'ADR 0004 non elenca.
|
||||||
|
- Al suo posto: un file `csv.gz` per strumento, intervallo e anno, in `research/{mercato}/{simbolo}/{intervallo}/{anno}.csv.gz`. Usa solo `System.IO.Compression`, che fa parte di .NET.
|
||||||
|
- I prezzi restano nel testo decimale scritto dalla fonte: andata e ritorno dal file senza perdere cifre. Le prove storiche li convertono in `double` quando li leggono.
|
||||||
|
- Ogni file si scrive con un nome temporaneo e poi si sposta: un'interruzione non lascia mai mezzo file.
|
||||||
|
- Se un giorno servirà Parquet, si chiederà il pacchetto all'utente; il formato sta dietro `ResearchStore`.
|
||||||
|
|
||||||
|
**2. Scritture idempotenti.** Barre, cambi, eventi e letture dell'umore si salvano con `INSERT … ON CONFLICT … DO UPDATE`, che entrambi i motori capiscono. Riscaricare lo stesso periodo non crea doppioni.
|
||||||
|
|
||||||
|
**3. Dato anomalo: seconda lettura subito.**
|
||||||
|
- Un dato che non passa i controlli (prezzo zero o negativo, massimo sotto il minimo, salto improbabile) si salva come "sospetto" e si apre un problema.
|
||||||
|
- La fonte si interroga di nuovo subito per lo stesso periodo:
|
||||||
|
- stessi valori: il dato è **confermato**;
|
||||||
|
- valori diversi: i nuovi lo sostituiscono (**corretto**);
|
||||||
|
- nessun dato o ancora impossibile: il dato si scarta (**non recuperabile**).
|
||||||
|
- Un buco si riscarica una volta. Ciò che manca ancora resta segnato come non recuperabile ("forse minuti senza scambi") e non blocca nulla.
|
||||||
|
- Un buco tra l'ultimo dato salvato e il primo dato nuovo conta come gli altri: anche un minuto saltato dal flusso dal vivo si riscarica.
|
||||||
|
- I buchi al minuto si cercano solo per la crypto, che scambia sempre. Per le azioni il controllo dei minuti arriva con il flusso dal vivo (Fase 3); i giorni mancanti si cercano sulle sedute del calendario di borsa.
|
||||||
|
|
||||||
|
**4. Solo le coppie in EUR di OKX Europe.** Il catalogo tiene le coppie spot quotate in EUR. Le coppie in USDC (più profonde per le monete minori, API-NOTES O18) restano fuori finché la Fase 3 non verifica con le chiavi demo quali si possono davvero negoziare.
|
||||||
|
|
||||||
|
**5. Alpaca solo con le chiavi del conto di prova.**
|
||||||
|
- Le chiavi si leggono da `ALPACA_API_KEY_DEMO` e `ALPACA_API_SECRET_DEMO`, mai da altre variabili.
|
||||||
|
- Senza chiavi la parte azionaria è spenta: nessuna chiamata parte verso Alpaca, e Impostazioni → Dati dice cosa manca.
|
||||||
|
- I criteri azionari della fase restano "in attesa dell'utente" e si provano su risposte d'esempio e dati sintetici.
|
||||||
|
|
||||||
|
**6. Azioni societarie gestite.** Frazionamenti (diretti e inversi), dividendi in contanti, dividendi in azioni e cambi di simbolo. Gli altri tipi di Alpaca (unità, scorpori, fusioni) non si scaricano: un titolo che li subisce compare come salto nelle serie e il controllo dei salti lo segnala.
|
||||||
|
|
||||||
|
**6b. Prezzi rettificati sempre sulla stessa base.**
|
||||||
|
- Alpaca dà i prezzi rettificati sulla base del giorno in cui si scaricano. Ogni scaricamento riparte quindi dall'ultimo giorno già salvato, che fa da testimone.
|
||||||
|
- Se il rapporto tra prezzo rettificato e prezzo reale di quel giorno è cambiato, è arrivato un frazionamento o un dividendo: tutti i prezzi rettificati salvati si moltiplicano per lo stesso fattore prima dei controlli.
|
||||||
|
- Così un frazionamento non sembra un crollo, e la serie rettificata nel database resta continua. I prezzi reali non si toccano mai.
|
||||||
|
|
||||||
|
**7. Fondi riconosciuti anche dal nome.** La colonna ETF di `nasdaqtraded.txt` non segna molti ETN e nessun fondo chiuso. Un titolo è escluso dall'universo azionario se il file lo segna come ETF, oppure se il nome contiene parole come "ETF", "ETN", "Fund", "Closed-End", "Beneficial Interest", "Index", "Leveraged", "Preferred", "Warrant", "Right", "Unit", "Notes" (l'elenco completo è in `NasdaqTraded`). Meglio escludere un'azione vera che comprare un fondo vietato (SPEC 4.6).
|
||||||
|
|
||||||
|
**8. Universi a una data passata.**
|
||||||
|
- Azioni: NYSE e NASDAQ, frazionabili, non fondi, almeno 300 sedute di storia, ultima barra entro 7 giorni, chiusura reale sopra 10 $, le prime 150 per controvalore mediano su 60 sedute.
|
||||||
|
- Crypto: coppie in EUR quotate da almeno 400 giorni, controvalore mediano a 30 giorni sopra 250.000 €, spread mediano sotto 20 punti base (senza spread noto la coppia è esclusa), niente stablecoin, monete "wrapped" o token a leva; le prime 10.
|
||||||
|
- Si usano solo i dati fino alla data: un test lo verifica.
|
||||||
|
- Limite noto: i flag di oggi (frazionabile, ETF) valgono anche per il passato (API-NOTES, "Distorsioni che restano").
|
||||||
|
|
||||||
|
**9. I lavori lunghi in un esecutore a parte.** Il pianificatore esegue i lavori uno dopo l'altro. Lo scaricamento dello storico può durare ore, quindi i lavori del pianificatore svegliano soltanto un esecutore in sottofondo (`MarketDataService`), che fa un giro alla volta.
|
||||||
|
|
||||||
|
**10. Dati di mercato spenti dove non servono.**
|
||||||
|
- Nella modalità dimostrativa, con `ANUBIS_MARKET_DATA=off` (o `0`, `false`) e nei test del server, salvo quelli che passano una rete finta.
|
||||||
|
- I test non toccano mai la rete. La prova sui dati reali (`RealHistoryProof`) sta nella categoria `LiveDemo`, esclusa dal giro normale.
|
||||||
|
|
||||||
|
**11. Archivi Binance per la ricerca.**
|
||||||
|
- Si tengono le candele giornaliere in USDT di 25 monete dal 2017, per avere storia prima della nascita delle coppie in EUR (novembre 2023).
|
||||||
|
- Ogni zip si controlla con il suo SHA-256. Il giro si ripete al massimo ogni 25 giorni.
|
||||||
|
- La conversione da USDT a EUR, e la scelta di come usarle nelle prove, spetta alla Fase 4.
|
||||||
|
|
||||||
|
**12. Flusso dal vivo solo per la crypto.** Il flusso WebSocket segue l'universo crypto (o BTC, ETH e SOL finché l'universo non c'è). Il flusso IEX delle azioni, limitato a 30 simboli, arriva con la Fase 3, quando ci sono le chiavi e le posizioni da seguire.
|
||||||
|
|
||||||
|
**13. Calendario delle banche centrali modificabile.** La Fed avverte che le date sono provvisorie. L'elenco delle riunioni è un'impostazione (`calendar.central_banks`), con un valore iniziale letto dalle pagine ufficiali e un controllo del formato prima di salvarlo.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Nessun componente esterno nuovo: l'elenco dell'ADR 0004 non cambia.
|
||||||
|
- Il rapporto di qualità (`anubis data report`, `/api/data/quality`) mostra per ogni strumento storia, buchi, anomalie e come sono finite, i problemi aperti e lo stato di ogni fonte.
|
||||||
|
- Le prove storiche della Fase 4 leggono dai file di ricerca, mai dal database.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# 0009 — Scelte della Fase 3: conti, ordini, contabilità
|
||||||
|
|
||||||
|
Data: 2026-11-10 · Stato: accettata · Precisa la specifica (sezioni 7, 8.6, 9, 13.5, 13.6) e gli ADR 0003, 0007 e 0008, senza aggiungere componenti esterni
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 3 collega Anubis ai conti: un'interfaccia comune per i broker, il simulatore interno, il gestore degli ordini con gli stop, la contabilità per strategia, la riconciliazione e la schermata Conti e posizioni. Non ci sono ancora chiavi dei conti di prova, quindi tutto è provato sul simulatore e su risposte d'esempio della documentazione. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. Due interfacce separate per i broker.** `IBrokerAccount` (ordini, posizioni, esecuzioni, permessi della chiave) è distinta da `IMarketDataSource` della Fase 2. Il simulatore interno (`PaperBroker`) e i due adapter (`AlpacaTrading`, `OkxTrading`) la implementano allo stesso modo e passano la stessa batteria di prove.
|
||||||
|
|
||||||
|
**2. Mai conti veri in questa fase.**
|
||||||
|
- Si creano solo i conti "simulatore" e, con le chiavi di prova, "Alpaca paper" e "OKX demo". Un conto reale non viene mai creato.
|
||||||
|
- Gli adapter rifiutano l'ambiente reale prima di qualsiasi richiesta se manca il consenso di avvio (SPEC 2.2). Lo controllano i test `LiveSafetyTests`.
|
||||||
|
|
||||||
|
**3. Le strategie partono in osservazione, e dove possono.**
|
||||||
|
- Le tre strategie di base partono nello stadio "osservazione": non ci sono ancora prove storiche (Fase 4).
|
||||||
|
- Quando compaiono le chiavi di prova, una strategia passa al conto di prova solo se il suo registro sul simulatore è vuoto. Con una storia resta dov'è, così i risultati non si mescolano.
|
||||||
|
|
||||||
|
**4. Il simulatore ha i soldi che i registri gli danno.** Il simulatore non ha denaro proprio: il suo saldo è almeno la liquidità che i registri delle strategie gli affidano, e cresce quando l'utente aumenta il capitale.
|
||||||
|
|
||||||
|
**5. Commissioni prudenti nel simulatore.**
|
||||||
|
- OKX: 0,10% maker e 0,20% taker, la tariffa annunciata dal 25/09/2026 (API-NOTES O5), trattenuta nella moneta comprata come fa OKX. La pagina delle tariffe e l'esempio di `trade-fee` mostrano ancora 0,08% e 0,10%: il simulatore usa la più alta. Con le chiavi, la tariffa vera del conto si legge da `trade-fee`.
|
||||||
|
- Alpaca: nessuna commissione, solo le tasse regolamentari del listino di ottobre 2026 (SEC 0,0000206 sul controvalore delle vendite, CAT 0,000003 $ per azione su acquisti e vendite, TAF a zero), arrotondate per eccesso a ogni esecuzione: più prudente dell'arrotondamento giornaliero del broker.
|
||||||
|
- Le attività `FEE` di Alpaca non entrano ancora nei registri: si confrontano con la riconciliazione quando ci saranno le chiavi.
|
||||||
|
|
||||||
|
**6. Le esecuzioni si registrano da una sola fonte.** Il flusso degli ordini avvisa che qualcosa è cambiato; le esecuzioni si leggono sempre dalla richiesta REST (`GetFills`) e si salvano una volta sola per conto ed esecuzione. Flusso e richiesta non creano doppioni.
|
||||||
|
|
||||||
|
**7. Ogni ordine ha la sua storia.** Anche la creazione è un evento di `order_events`: si vede quando l'ordine è nato, non solo quando è cambiato.
|
||||||
|
|
||||||
|
**8. Gli stop.**
|
||||||
|
- Ogni posizione ha uno stop sul broker. Se il prezzo non si conosce, è vecchio o il mercato è chiuso, lo stop si mette comunque: meglio uno stop in più che una posizione scoperta.
|
||||||
|
- Alpaca: stop permanente (`gtc`) sulle azioni intere; sulle frazioni il broker accetta solo ordini `day`, che il gestore rimette dopo la scadenza. A mercato chiuso restano "in coda per l'apertura" e intanto li sorveglia Anubis.
|
||||||
|
- Un ordine OKX annullato e sconosciuto al broker da più di 2 ore si considera annullato. Conta come "sconosciuto" solo la risposta 51603 ("l'ordine non esiste"): ogni altro errore si riprova, così un ordine perso non parte due volte.
|
||||||
|
- Se manca il prezzo, una vendita aspetta con gli stop ancora sul broker: si tolgono solo un attimo prima che parta. Un acquisto senza prezzo si lascia cadere.
|
||||||
|
- Su Alpaca un acquisto toglie gli stop di tutte le strategie sullo stesso titolo, perché Alpaca rifiuta l'acquisto se c'è un qualsiasi stop di vendita, e li rimette quando l'acquisto finisce.
|
||||||
|
- Una vendita rifiutata non si abbandona, ma si riprova con pause crescenti: 1, 2, 4, 8 minuti, poi ogni 15. La riconciliazione cerca la causa.
|
||||||
|
|
||||||
|
**9. Contabilità per strategia, in sola aggiunta.**
|
||||||
|
- `fills`, `lots` e `cash_ledger` non si modificano mai: un errore si corregge con una riga di storno. Un test cerca `UPDATE` e `DELETE` su queste tabelle in tutto il codice.
|
||||||
|
- Il capitale affidato si decide in euro per broker e si divide tra le strategie secondo le quote. Alpaca lo converte al cambio BCE del giorno e da lì tiene il registro in dollari. Quando l'importo cambia, si converte solo la differenza in euro: i dollari già affidati restano quelli, così un movimento del cambio non diventa mai un versamento o un prelievo. Salvare lo stesso importo non cambia nulla.
|
||||||
|
- Ridurre il capitale sotto la liquidità libera di una strategia è rifiutato: il bot non vende per restituire capitale.
|
||||||
|
- I dividendi vanno a chi aveva il titolo alla chiusura prima della data di stacco, calcolato dalle esecuzioni. Caso limite noto: un frazionamento tra l'acquisto e lo stacco. Ogni pagamento ha il suo segno di "già fatto" nella stessa scrittura, così un errore a metà non paga due volte.
|
||||||
|
- Un frazionamento moltiplica solo le azioni tenute prima della data di stacco: quelle comprate dopo sono già azioni nuove. Un frazionamento vecchio, di quando la strategia non aveva il titolo, non cambia nulla. Il simulatore applica lo stesso frazionamento al suo libro, una volta, insieme al registro.
|
||||||
|
|
||||||
|
**10. Patrimonio e rendimenti.**
|
||||||
|
- Ogni 5 minuti una fotografia per strategia, per conto e per mondo (circa 7 righe). Prima di ogni fotografia le posizioni prendono il prezzo di mercato (il medio di una quotazione recente); senza quotazione resta l'ultimo prezzo noto.
|
||||||
|
- Mondo simulato e mondo reale non si sommano mai: Panoramica e Conti mostrano un solo mondo, quello reale se esiste un conto reale, altrimenti quello simulato.
|
||||||
|
- I risultati tolgono i versamenti e i prelievi di capitale; la percentuale è ponderata nel tempo (TWR).
|
||||||
|
- Le carte dei conti in dollari usano l'ultimo cambio; l'effetto del cambio si mostra a parte.
|
||||||
|
- Il confronto "senza bot" sui conti reali arriva con la Fase 4.
|
||||||
|
|
||||||
|
**11. Riconciliazione.**
|
||||||
|
- Ogni 5 minuti registro e conto si confrontano. Sul simulatore si controllano solo la coerenza interna e gli stop.
|
||||||
|
- Una differenza che si spiega da sola (esecuzione in ritardo, frazionamento, stop da rimettere) si sistema. Una che resta porta il conto in modalità prudente: niente nuovi acquisti, vendite e stop proseguono.
|
||||||
|
- Dopo 15 minuti l'utente sceglie: **allinea** (il registro prende i numeri del conto, con una riga di rettifica che conta come movimento di capitale, non come risultato) o **escludi** (la differenza resta fuori dal registro e non si segnala più). Prima di agire la scelta rifà il confronto: si applica solo alle differenze che esistono in quel momento. Se dopo i 15 minuti la differenza sparisce, il conto aspetta comunque la scelta, ma senza differenze vecchie da copiare.
|
||||||
|
- Una chiave che permette i prelievi tiene il conto in modalità prudente finché non viene sostituita: non si allinea né si esclude. Sostituita con una chiave senza prelievo, il conto torna normale.
|
||||||
|
|
||||||
|
**12. Chiavi inserite dall'interfaccia.**
|
||||||
|
- Impostazioni → Conti e chiavi accetta le chiavi dei conti di prova. Prima di salvarle Anubis chiede al broker cosa possono fare. Le rifiuta se permettono i prelievi o se non possono fare ordini.
|
||||||
|
- Salvate, sono cifrate (SPEC 15.4), non si rimostrano mai e il motore riparte da solo per usarle.
|
||||||
|
- Le chiavi nelle variabili d'ambiente valgono di più e si cambiano solo lì.
|
||||||
|
- Chiavi e capitale non entrano nella procedura del primo avvio, che resta corta (password e database) e deve funzionare anche senza chiavi. Al primo accesso, finché non c'è capitale affidato, la Panoramica indica questo passo come il primo e porta a Impostazioni → Conti e chiavi.
|
||||||
|
|
||||||
|
**13. Batteria di conformità dei broker.**
|
||||||
|
- Una classe astratta di prove, eseguita sul simulatore, sulle risposte d'esempio della documentazione di Alpaca e OKX e, con le chiavi, sui veri conti di prova (categoria `LiveDemo`).
|
||||||
|
- Senza chiavi le prove dal vivo risultano "in attesa dell'utente".
|
||||||
|
- La chiave d'esempio di OKX nella documentazione ha il permesso `withdraw`: la batteria verifica che Anubis lo legga.
|
||||||
|
|
||||||
|
**14. La schermata Conti e posizioni.**
|
||||||
|
- Il valore di ogni posizione si arrotonda al centesimo nella sua valuta, come lo mostra la tabella, così colonne e totali tornano a vista.
|
||||||
|
- La modalità dimostrativa carica righe di registro, operazioni chiuse, stop, cambio e stato della riconciliazione: è il registro stesso a calcolare i numeri del mockup.
|
||||||
|
|
||||||
|
**15. Niente operazioni nella modalità dimostrativa.** Il motore di trading è spento nella demo: la demo mostra l'appendice F e non manda nulla.
|
||||||
|
|
||||||
|
**16. Il flusso IEX delle azioni passa alla Fase 6.** L'ADR 0008 lo prevedeva in questa fase, per seguire le posizioni azionarie. Senza le chiavi Alpaca non ci sono né dati azionari né posizioni da seguire. E le posizioni non dipendono dal flusso: lo stop sta sul broker e la riconciliazione controlla ogni 5 minuti. Il flusso (al massimo 30 simboli) arriva con il motore dal vivo della Fase 6, che sceglie quali titoli seguire.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Tutto il percorso dell'ordine è provato senza rete. Le prove con i veri conti di prova aspettano le chiavi dell'utente.
|
||||||
|
- Dove la specifica lascia spazio, si è scelta la strada più prudente: stop sempre presenti, commissioni piene, nessuna vendita forzata, nessun conto reale.
|
||||||
|
- I casi limite rimasti (dividendo dopo un frazionamento, attività `FEE` di Alpaca) sono scritti qui e si ricontrollano con le chiavi.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# 0010 — Scelte della Fase 4: backtest e laboratorio
|
||||||
|
|
||||||
|
Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 5.3, 8.7, 12.1, 12.2, 13) e l'ADR 0009, senza aggiungere componenti esterni
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 4 costruisce il motore di prova sullo storico, le convalide del protocollo anti-illusioni (12.2), il registro delle prove e la schermata Laboratorio. Le strategie di base, i correttivi e il motore del rischio arrivano con la Fase 5: per provare il laboratorio c'è una strategia d'esempio, l'incrocio di due medie (`sma_cross`). Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. Il motore va a eventi, una seduta alla volta.**
|
||||||
|
- Ordine degli eventi in una seduta: azioni societarie prima dell'apertura; all'apertura gli stop che aprono sotto il livello, poi gli ordini decisi alla chiusura prima, vendite per prime; durante la seduta gli stop toccati dal minimo; alla chiusura la valutazione e la decisione.
|
||||||
|
- Si decide sulla chiusura e si esegue all'apertura dopo: è il ritardo tra decidere e agire. Niente inseguimento con ordini limite (quello lo fa il gestore degli ordini dal vivo).
|
||||||
|
- Le strategie sono le stesse classi che girano dal vivo e non sanno se sono in prova.
|
||||||
|
- Il denaro è `decimal`; le barre sono `double` (dati d'analisi) e diventano `decimal` una volta sola, quando servono come prezzo.
|
||||||
|
- Il motore ha una versione (`BacktestEngine.Version`) scritta nel piano: un rapporto dice quale motore l'ha prodotto.
|
||||||
|
|
||||||
|
**2. Gli stessi costi del simulatore.** Commissioni e scostamento vengono dai listini del simulatore interno (ADR 0009 punto 5), arrotondati a nostro sfavore. Un moltiplicatore li scala tutti insieme per la sensibilità ai costi (×1, ×2, ×3). Gli acquisti non prendono mai in prestito; un ordine sotto il minimo non parte e lascia una nota.
|
||||||
|
|
||||||
|
**3. Correttivi e rischio sono già al loro posto, ma lasciano passare tutto.** Il motore chiama i correttivi (8.5) e il motore del rischio (9) per ogni intenzione; fino alla Fase 5 sono "passanti". Un test controlla che vedano ogni intenzione e possano cambiarla. Il rapporto lo scrive tra le cose che il test non considera.
|
||||||
|
|
||||||
|
**4. Statistica scritta in casa.** Nessuna libreria esterna (ADR 0004):
|
||||||
|
- funzione di ripartizione normale con l'algoritmo 5666 di Hart, quantile con il metodo di Acklam più un passo di Halley;
|
||||||
|
- momenti del campione: deviazione standard campionaria, asimmetria e curtosi (non in eccesso) di popolazione, come nell'articolo di Bailey e López de Prado;
|
||||||
|
- il Deflated Sharpe Ratio riproduce l'esempio dell'articolo (soglia 0,1132, DSR 0,9004).
|
||||||
|
|
||||||
|
**5. Sharpe senza tasso privo di rischio.** Sharpe e volatilità sono annualizzati con le sedute di un anno (365 per le crypto, 252 per le azioni) e non tolgono un tasso privo di rischio. Il rendimento annuo usa i giorni di calendario (365,25). Il rapporto guadagni/perdite non ha valore senza un'operazione in perdita: un "0" o un "infinito" ingannerebbero.
|
||||||
|
|
||||||
|
**6. Le convalide lavorano sui rendimenti giornalieri delle varianti.** Ogni variante della griglia gira una volta sull'intero periodo; finestre che avanzano, K-fold purgato combinatorio e PBO scelgono e giudicano su pezzi di quelle serie. È più semplice e veloce che rifare ogni volta il backtest su ogni pezzo, e la scelta nel pezzo d'addestramento vede comunque solo i rendimenti di quel pezzo. Il prezzo: le posizioni aperte prima dell'inizio di un pezzo di prova restano aperte, come lo sarebbero dal vivo.
|
||||||
|
|
||||||
|
**7. La regola dell'altopiano.** Il punteggio di una variante è il più basso tra il suo Sharpe e la media del suo intorno (lei e le vicine a distanza 1 su ogni parametro della griglia). Con la sola media dell'intorno vincevano gli angoli della griglia accanto a un picco isolato; con il minimo vince una collina larga, non una punta. A parità vince la prima variante nell'ordine della griglia.
|
||||||
|
|
||||||
|
**8. Le misure delle convalide.**
|
||||||
|
- Finestre che avanzano: addestramento che si allarga, 4 finestre di prova.
|
||||||
|
- K-fold purgato combinatorio: 6 gruppi, 2 in prova per volta, quindi 15 divisioni e 5 percorsi.
|
||||||
|
- Purga ed embargo: l'1% delle sedute, almeno una.
|
||||||
|
- PBO con il metodo CSCV: 16 gruppi, ridotti a un numero pari con almeno 4 sedute per gruppo. Un logit uguale o sotto zero conta come sovra-adattamento; nei pareggi il rango è la media. Con una sola variante il PBO non si applica e il rapporto lo dice.
|
||||||
|
|
||||||
|
**9. Il numero di prove del DSR.** N è la somma delle varianti di tutte le prove concluse della stessa strategia più quelle della prova corrente; la varianza degli Sharpe è quella di tutte queste varianti. Ogni nuovo tentativo alza l'asticella dei successivi.
|
||||||
|
|
||||||
|
**10. Il piano si scrive prima e non cambia.**
|
||||||
|
- Prima di qualsiasi calcolo si salvano il piano in JSON (strategia e versione, griglia, dati, capitale, moltiplicatori dei costi, misure delle convalide, soglie, versione del motore) e la sua impronta SHA-256. Il codice non aggiorna mai piano e impronta: un test controlla che dopo la corsa testo e impronta siano identici. Prima di partire la prova ricalcola l'impronta: se il piano non le corrisponde più, non parte.
|
||||||
|
- Su PostgreSQL la colonna è `json`, non `jsonb`, così il testo resta identico e l'impronta si ricontrolla.
|
||||||
|
- Le soglie sono nel piano: risultato netto positivo con costi doppi, DSR almeno 0,90, PBO non oltre 0,40, calo massimo non oltre il 25%, nessuna decisione cambiata dai dati futuri. La prova è superata se nessun controllo è fallito; un controllo che non si applica non la fa fallire.
|
||||||
|
|
||||||
|
**11. Il test contro lo sguardo in avanti.** Si taglia lo storico a 6 date e si rifà la decisione su dati che finiscono lì: le intenzioni devono essere identiche a quelle della corsa completa. Una strategia volutamente scorretta, che legge il giorno dopo, viene presa. Lo stesso confronto "un passo" servirà nella Fase 6 per paragonare dal vivo e backtest (12.3), con una tolleranza del 10% sulla dimensione.
|
||||||
|
|
||||||
|
**12. Il laboratorio non disturba il bot.**
|
||||||
|
- Una prova alla volta, su un thread suo a priorità bassa. Solo la parte asincrona tocca il database.
|
||||||
|
- All'avvio le prove rimaste "in corso" tornano "pianificate" e ripartono con lo stesso piano.
|
||||||
|
- Una prova fallita tiene il motivo.
|
||||||
|
- Massimo 20 strumenti e 200 varianti per prova, almeno 30 sedute, capitale tra 1 e 10.000.000. I parametri che contano giorni accettano solo numeri interi: 10,5 girerebbe come 10 e conterebbe due volte nel DSR.
|
||||||
|
- Un errore del database (per esempio PostgreSQL che riparte) non ferma la coda: si riprova dopo 30 secondi.
|
||||||
|
- Nella modalità dimostrativa il laboratorio è spento.
|
||||||
|
|
||||||
|
**13. Le due origini dei dati.**
|
||||||
|
- "Barre raccolte": le barre giornaliere del database, con frazionamenti e dividendi per le azioni.
|
||||||
|
- "Storico di ricerca": gli archivi Binance (Fase 2), nella loro valuta (USDT). Le regole d'ordine non ci sono negli archivi: passo di prezzo e di quantità di 0,00000001 e controvalore minimo di 5 (come i minimi tipici delle borse crypto: un ordine più piccolo non parte e un residuo sotto i 5 si perde all'uscita); i costi sono quelli di OKX. Il rapporto lo scrive. La conversione in euro (annunciata nello STATE della Fase 2) non serve: una prova lavora in una sola valuta e rifiuta strumenti quotati in valute diverse.
|
||||||
|
|
||||||
|
**14. Il rapporto.** Contiene i controlli del protocollo, la variante scelta contro "comprare e tenere" (pesi uguali, stessi costi; uno strumento la cui storia comincia dopo si compra alla sua prima chiusura, con la quota rimasta libera per lui), i risultati per anno, la sensibilità ai costi, DSR, PBO, finestre, percorsi, sguardo in avanti, tutte le varianti con il loro punteggio, ciò che il test non considera, l'impronta dei dati e le operazioni. La curva tiene al massimo 500 punti e l'elenco le ultime 300 operazioni, per restare leggero nel database. Il confronto tra due prove dice se hanno letto gli stessi dati.
|
||||||
|
|
||||||
|
**15. Le sezioni che arrivano dopo.** "Migliorie in osservazione" (8.7) e "Stime di costo da confermare" (11.6) sono già nella schermata, vuote, con la fase che le riempie (9 e 8).
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Una prova è riproducibile: stesso piano e stessi dati danno lo stesso rapporto, e il registro non si può ritoccare dopo aver visto i risultati.
|
||||||
|
- I backtest delle tre strategie di base (Fase 5) useranno questo laboratorio così com'è; i correttivi e il rischio veri entreranno nei punti già pronti.
|
||||||
|
- La prova su PostgreSQL della tabella delle prove passa dalla CI, perché su questo PC Docker non era disponibile.
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# 0011 — Scelte della Fase 5: strategie, portafoglio, rischio
|
||||||
|
|
||||||
|
Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 7.1, 7.5, 8, 9, 12, 13.1–13.6) e l'ADR 0010, senza aggiungere componenti esterni
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del rischio, gli stadi verso i soldi veri, i backtest onesti delle strategie e le schermate Operazioni, Strategie e Rischio. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. Le strategie sono le stesse in prova e dal vivo.**
|
||||||
|
- Le tre strategie (`crypto_trend`, `equity_momentum`, `equity_meanrev`) sono classi senza stato proprio: leggono le barre, il loro portafoglio e il patrimonio di riferimento, e restituiscono intenzioni (peso voluto e stop). Ogni intenzione ha un codice motivo, mai un testo libero.
|
||||||
|
- Il motore di backtest ha imparato ciò che le regole chiedono: l'uscita alla stessa chiusura (`equity_meanrev`, che dal vivo vende alle 15:55), lo stop messo a una distanza dal prezzo ottenuto, gli strumenti di solo dato come SPY, il calendario di borsa e la storia del patrimonio.
|
||||||
|
- Il patrimonio di riferimento di una strategia è quello della sua quota del bot (`ReferenceShare`): i limiti in percentuale si misurano sul bot, non sulla sola strategia.
|
||||||
|
- Tutte e tre passano il test contro lo sguardo in avanti dell'ADR 0010 (punto 11).
|
||||||
|
|
||||||
|
**2. Correttivi e rischio girano anche nei backtest.** I correttivi di 8.5 (regime crypto: metà delle nuove entrate quando Bitcoin chiude sotto la media a 200 giorni o la sua volatilità supera il 90° percentile di due anni; calendario economico: niente entrate da 30 minuti prima a 30 dopo un dato USA importante, fino a 60 dopo una decisione di Fed o BCE) e le regole di 9.1 e 9.2 sono passi della decisione, gli stessi dal vivo e in prova. Nel backtest di una strategia:
|
||||||
|
- la strategia è una parte del bot e il resto conta come liquidità ferma, così una sua perdita pesa sul mondo quanto la sua quota;
|
||||||
|
- ogni chiusura è una giornata italiana a sé (mezzogiorno UTC);
|
||||||
|
- dopo che l'interruttore scatta si suppone che l'utente riparta una settimana dopo, e il massimo si misura da lì;
|
||||||
|
- età del prezzo, prezzo dell'ordine e orologio esistono solo dal vivo.
|
||||||
|
|
||||||
|
**3. Il motore del rischio toglie o riduce, mai aggiunge.**
|
||||||
|
- Ogni intenzione lo attraversa prima di diventare un ordine; la protezione (stop e uscite) passa sempre.
|
||||||
|
- Le tre misure di 9.2 (perdita del giorno da mezzanotte italiana, degli ultimi sette giorni, calo dal massimo) vengono dall'indice ponderato nel tempo di ciascun mondo, così versamenti e prelievi non sembrano guadagni o perdite. Simulato e reale sono due mondi: un limite ferma solo il mondo dove è stato superato.
|
||||||
|
- Il monitor è una macchina a stati pura, la stessa in prova e dal vivo, e il suo moltiplicatore è sempre uno o meno.
|
||||||
|
- L'avviso parte all'80% di una soglia, una volta per superamento, senza blocchi.
|
||||||
|
- La protezione per le operazioni in giornata (`pdt_guard`) è spenta in partenza: Anubis non usa il margine.
|
||||||
|
- I test di proprietà controllano che il risultato non sia mai più grande del richiesto, e mai più grande dopo una perdita.
|
||||||
|
|
||||||
|
**4. Fermare e ripartire passa sempre dal motore del rischio.** "Ferma tutto", "Ferma e chiudi", il file `STOP` nella cartella dei dati e l'anomalia di ordini al minuto fermano il bot finché l'utente non conferma la ripartenza. La ripartenza è rifiutata finché il file `STOP` esiste. Dopo uno scatto il massimo si misura dalla ripartenza.
|
||||||
|
|
||||||
|
**5. Ogni passo di una decisione resta scritto.** La nuova tabella `decisions` tiene una riga per passo (strategia, correttivi, dimensionamento, rischio, ordine) con codici motivo e numeri usati. La scheda "perché" di Operazioni collega decisioni ed esecuzioni con l'id d'ordine deterministico (`ClientOrderIds.Key(decision_id)`) e scrive le frasi da modelli italiani fissi.
|
||||||
|
|
||||||
|
**6. Gli stadi sono l'unica strada verso i soldi veri.**
|
||||||
|
- Quattro stadi: osservazione, simulazione, reale ridotto, reale. Da osservazione a simulazione servono il backtest superato e almeno 90 giorni di segnali raccolti dal vivo (12.3); solo il primo avvio porta in simulazione una strategia di base che ha superato il backtest, come dice la specifica.
|
||||||
|
- Un ordine su un conto reale richiede il consenso della configurazione d'avvio, tutti i requisiti di 12.3 soddisfatti, la frase scritta a mano e password (più il secondo fattore, se attivo) inseriti da poco. I gestori degli ordini sui conti reali, in caso di dubbio, rifiutano e richiedono la conferma prima di ogni ordine.
|
||||||
|
- Da osservazione a simulazione si passa con un pulsante, ma il libro degli stadi ricontrolla i due requisiti: una strategia che non li ha resta in osservazione e la schermata dice perché.
|
||||||
|
- La password inserita per la procedura conta i tentativi come l'accesso: dopo cinque errori in 15 minuti è rifiutata anche quella giusta, finché la finestra non passa.
|
||||||
|
- Prima della conferma la schermata riassume cosa cambia: capitale usato, acquisti del primo ciclo (stimati da ciò che la simulazione tiene in quel momento), limiti e la loro base. Per una strategia con soldi veri mostra la differenza di risultato con il gemello simulato, in percentuale del capitale usato.
|
||||||
|
- Con soldi veri in gioco l'esito del backtest con cui la strategia si è qualificata non cambia, nemmeno con un aggiornamento del programma: lo riceve quando torna in simulazione. L'esito tiene anche i parametri della variante qualificata, che sono quelli che girano dal vivo (Fase 6).
|
||||||
|
- Una strategia retrocessa o revocata tiene le posizioni reali in sola uscita, con i loro stop, fino a zero.
|
||||||
|
- Il gemello simulato di una strategia con soldi veri resta fuori dai totali e dal patrimonio di riferimento.
|
||||||
|
- Il patrimonio di riferimento è il capitale affidato più i risultati, contati una volta sola. A ogni cambio di stadio il registro che la strategia lascia porta con sé ciò che ha prodotto da quando era in uso (per quattro se viene dal reale ridotto), e il registro che prende il suo posto parte da ciò che ha in quel momento. Così il passaggio da reale ridotto a reale, sullo stesso conto, e il ritorno al gemello dopo una retrocessione non contano due volte gli stessi guadagni. Gli importi restano nella valuta del registro e diventano euro al momento del calcolo.
|
||||||
|
- Nel calcolo della retrocessione per il percorso atteso le azioni non contano i fine settimana, in cui non ci sono sedute.
|
||||||
|
|
||||||
|
**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Non passa comunque finché una strategia con soldi veri ha una condizione di retrocessione in corso (12.4). Ogni cambio finisce nel registro delle impostazioni. I limiti non si cambiano dall'API generale delle impostazioni (`PUT /api/settings`): solo dal modulo di Impostazioni, che fa questi controlli.
|
||||||
|
|
||||||
|
**7 bis. Liquidità, strumenti e fermate.**
|
||||||
|
- Un acquisto in corso tiene impegnata la sua liquidità finché non è eseguito, e ogni acquisto conta al prezzo più alto a cui il suo limite può arrivare (la distanza ammessa dall'ultimo prezzo): più acquisti inviati insieme non superano la liquidità della strategia.
|
||||||
|
- In uno stesso conto uno strumento appartiene a una sola strategia alla volta (8.6): se un'altra lo tiene, o lo sta comprando, l'ingresso salta con il suo motivo.
|
||||||
|
- "Ferma tutto", il file `STOP` e l'anomalia di ordini al minuto sono eventi di gravità alta, non critici: sono il bot che fa il suo lavoro, non un controllo perso, e non bloccano per 30 giorni il passaggio di stadio (12.3).
|
||||||
|
- Quando l'interruttore scatta da solo in un mondo, il bot resta "attivo" per l'altro: la pagina Rischio mostra lo scatto di entrambi i mondi e il pulsante "Riparti" anche in questo caso. La ripartenza toglie lo scatto e lascia una pausa com'era.
|
||||||
|
- Nella pagina Rischio peso di una posizione, quota crypto e rischio di un'operazione si misurano sul patrimonio di riferimento, come nel motore del rischio.
|
||||||
|
|
||||||
|
**8. Gli scenari sono una somma semplice.** "Se succedesse domani" applica la variazione al valore delle posizioni del momento. "Con gli stop" prende per ogni posizione la perdita più piccola tra lo scenario e la distanza dal suo stop, arrotondata a 5 € e scritta come "circa", perché uno stop non garantisce il prezzo. Lo scenario del dollaro tocca il conto in dollari e gli stop non lo riducono.
|
||||||
|
|
||||||
|
**9. I risultati per strategia si arrotondano come in Conti.** Ogni posizione si arrotonda al centesimo prima di sommare, così Strategie e Conti mostrano lo stesso numero.
|
||||||
|
|
||||||
|
**10. Lo storico crypto in euro, per i backtest delle strategie.** L'ADR 0010 (punto 13) lasciava i dati Binance in USDT; per le strategie di base serve l'euro, perché il bot pensa in euro.
|
||||||
|
- Le barre giornaliere USDT si dividono per il cambio BCE EUR/USD dello stesso giorno, o dell'ultimo precedente fino a 7 giorni prima; altrimenti la barra si scarta. Si salvano come sede `binance_eur`.
|
||||||
|
- Una serie si ferma al primo buco più lungo di 7 giorni (`MaxGapDays`): ciò che segue è un'altra moneta. Il LUNA rilanciato nel 2022 non si confonde con quello crollato, che si taglia al 13/05/2022.
|
||||||
|
- L'elenco degli archivi comprende le monete tolte dal listino (49 coppie, con LUNA, FTT, BCC, VEN, XMR…): l'universo passato non è scelto tra i sopravvissuti.
|
||||||
|
- Ogni barra usa l'ultimo cambio fissato prima della sua apertura, cioè quello del giorno prima: il cambio del giorno d è fissato alle 16:00, dopo l'apertura della barra di d alle 00:00 UTC, e il backtest esegue all'apertura.
|
||||||
|
- `anubis backtest base --offline` scarica i cambi BCE solo se il file manca.
|
||||||
|
|
||||||
|
**11. Il protocollo dei backtest di base.**
|
||||||
|
- Periodo dal 01/01/2019 al 31/10/2026. Le prove leggono anche 450 giorni prima dell'inizio (`TrialData.WarmupDays`), solo perché indicatori ed età minima di quotazione (400 giorni) siano pronti dal primo giorno. Il controllo "strumento vuoto" e il conteggio delle sedute guardano solo dentro il periodo.
|
||||||
|
- `crypto_trend` si prova su due universi: quello largo e solo BTC, ETH e SOL. Supera solo se superano entrambi; le misure mostrate vengono dall'universo largo.
|
||||||
|
- Nel DSR il secondo universo conta come prove precedenti anche le varianti del primo. L'id della prova viene dall'impronta del piano, così rifare il calcolo non crea prove nuove.
|
||||||
|
- Per gli strumenti dell'universo largo il limite del Laboratorio sale a 60 (`Laboratory.MaxSymbols`).
|
||||||
|
- Il costo di andata e ritorno è 2 × (commissione taker + scostamento); lo scostamento è pesato sul controvalore scambiato.
|
||||||
|
- Il percorso atteso a un anno viene da un bootstrap a blocchi stazionario: 2.000 percorsi, blocchi medi di 20 giorni, seme 20260101, 365 giorni.
|
||||||
|
- Il rapporto mostra lo Sharpe annuo (× √sedute dell'anno) e DSR e PBO con tre decimali, perché "0,90 serve ≥ 0,90" con due decimali confondeva.
|
||||||
|
- Il rapporto conta quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato la richiesta della strategia, separate dalle note del motore (ordini sotto il minimo, residui).
|
||||||
|
- "Comprare e tenere" dell'universo largo compra fin dall'inizio tutte le 47 monete che sono state tra le prime dieci in qualche momento: è un paniere scelto col senno di poi, quindi favorisce il confronto e rende il giudizio sulla strategia più severo, non più indulgente.
|
||||||
|
|
||||||
|
**12. L'esito dei backtest viaggia con il codice.** I file `docs/backtests/*.outcome.json` sono inclusi nell'applicazione e letti a ogni avvio. Gli esiti azionari sono "non superato, in attesa delle chiavi Alpaca": senza storico azionario le due strategie azionarie restano in osservazione.
|
||||||
|
|
||||||
|
**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 32,8% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 10,4% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile.
|
||||||
|
|
||||||
|
Una prima versione del calcolo usava il cambio dello stesso giorno della barra e dava un calo del 29,1%. Spostare il cambio di un giorno (punto 10) ha mosso il calo di quasi quattro punti: anche questo dice che il risultato è fragile.
|
||||||
|
|
||||||
|
**14. La demo è coerente con i mockup.** La modalità dimostrativa semina le decisioni dietro le sue operazioni, 58 giorni di simulazione, una qualifica d'esempio e gli indici delle curve, così Operazioni, Strategie e Rischio mostrano le cifre dei mockup 03, 04 e 07. Nella demo nessuno stadio cambia e i moduli del rischio non ci sono.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Nessuna strategia può arrivare alla simulazione senza un backtest superato, né ai soldi veri senza la procedura di 12.4. Oggi tutte e tre restano in osservazione: è l'esito onesto, non un difetto.
|
||||||
|
- Le prove dei backtest azionari partono quando l'utente fornisce le chiavi del conto paper di Alpaca.
|
||||||
|
- Cambiare una regola di `crypto_trend` per farla passare richiede una nuova versione della strategia e una nuova prova, che il DSR conterà insieme a quelle già fatte.
|
||||||
@@ -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,148 @@
|
|||||||
|
# 0014 — Scelte della Fase 7: raccolta e collegamento delle notizie
|
||||||
|
|
||||||
|
Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5, 10.2, 10.5 e 5.6 per le issue #56–#60. Usa solo i componenti già ammessi dall'ADR 0004 · Punti 3, 4, 7, 9, 10, 13 e 15 precisati dall'ADR 0017
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
**9. Le regole di 10.5 (#59).**
|
||||||
|
- Una restrizione vale dal momento del fatto, cioè dalla prima ora tra pubblicazione e arrivo nel bot, non da quando il bot la legge. Così, dopo un'assenza, valgono solo le restrizioni ancora in corso (SPEC 5.6), e una notizia di tre giorni fa non ferma niente oggi.
|
||||||
|
- Le righe della tabella, come le applica il bot:
|
||||||
|
- **evento grave**: una storia confermata con importanza 4 (un caso grave di 10.2), qualunque sia il tono. Per 72 ore niente nuovi acquisti dello strumento, lo stop non si allarga e parte un avviso Telegram;
|
||||||
|
- **notizia negativa**: una storia confermata con importanza 3 e tono non migliore di −0,2. Per 24 ore niente nuovi acquisti;
|
||||||
|
- **voce non confermata**: una sola fonte non affidabile. Nessuna azione: una riga nel diario e un nuovo controllo dopo 2 ore, che dice se un'altra fonte l'ha confermata;
|
||||||
|
- **trimestrale in arrivo**: `equity_meanrev` non entra se i conti cadono nelle sessioni della sua finestra (la regola della strategia di 8.3, che ora riceve il calendario anche dal vivo). L'uscita prima dei conti resta sempre, anche con la riga spenta;
|
||||||
|
- **dato macro**: da 30 minuti prima a 30 dopo, 60 dopo Fed e BCE, come nel backtest. Ora vale anche dal vivo.
|
||||||
|
- "Confermata" vuol dire una fonte affidabile o almeno due fonti indipendenti (punto 3).
|
||||||
|
- Quando più righe valgono insieme, vince quella che finisce più tardi; a parità, l'evento grave.
|
||||||
|
- Ogni riga si spegne in Impostazioni con la sua chiave (`news.rule.severe`, `news.rule.negative`, `news.rule.unconfirmed`, `calendar.rule.earnings`, `calendar.rule.macro`). Sono tutte accese all'inizio; la schermata arriva con #60.
|
||||||
|
- Queste regole restringono e non bloccano: non chiudono posizioni e non fermano la strategia, tolgono o spostano solo gli acquisti.
|
||||||
|
|
||||||
|
**10. Gli acquisti fermati.**
|
||||||
|
- Un acquisto che cade in una restrizione si sposta alla fine della restrizione, se a quell'ora l'ordine è ancora valido. Altrimenti si toglie, con il motivo.
|
||||||
|
- Lo spostamento tiene l'ora originale in `first_due_at`. Il controllo del prezzo di SPEC 5.6 confronta sempre con la decisione: se nel frattempo il prezzo si è mosso troppo, l'ordine scade come ogni ordine in ritardo.
|
||||||
|
- La decisione della strategia resta scritta tra le decisioni con la sua proposta, e accanto c'è la riga del correttivo che l'ha fermata. Gli esempi di 11.2 la trovano lì.
|
||||||
|
- Ogni restrizione compare nel diario una sola volta, con il suo motivo: il titolo della notizia e la fonte, oppure il nome del dato macro. Le righe del diario seguono l'appendice F.10.
|
||||||
|
|
||||||
|
**11. Lo stato per strumento (10.2, punto 6).**
|
||||||
|
- Tono medio a 1 e a 3 giorni: le storie pesano di meno con l'età, con un tempo di dimezzamento di metà finestra (12 ore e 36 ore).
|
||||||
|
- Numero di storie delle ultime 24 ore e la norma: le storie al giorno dei 29 giorni precedenti, solo quando ci sono almeno 2 giorni di storico. Prima la norma non c'è e lo stato non dice "più notizie del solito".
|
||||||
|
- La restrizione più forte in corso, con il suo motivo.
|
||||||
|
- Il diario parla delle notizie sugli strumenti che il bot tiene e su quelli degli universi più recenti. Gli altri si leggono nella schermata Notizie.
|
||||||
|
|
||||||
|
**12. Le etichette d'umore (10.4)** sono quelle della Fase 2 (ADR 0008) e non cambiano.
|
||||||
|
|
||||||
|
**13. La schermata Notizie e mercato (13.1–13.6, F.9).**
|
||||||
|
- Ogni nota del bot su una storia conserva la frase "cosa ho fatto" e, se è una restrizione, la sua fine (`news_notes.action` e `news_notes.until`, migrazione 0010). La schermata legge la frase com'era al momento della decisione e non la ricalcola.
|
||||||
|
- Se una restrizione è ancora in corso ma la sua riga è stata spenta, la frase lo dice ("Ora la regola è spenta: la restrizione non vale più") e la notizia non conta più tra quelle con un effetto.
|
||||||
|
- Quando il bot non ha fatto nulla, il motivo viene dalle regole: la notizia riguarda il mercato e non un singolo strumento; non è confermata; la sua riga è spenta; è positiva (le notizie non fanno mai comprare); è solo leggermente negativa; il tono non è stato letto.
|
||||||
|
- L'elenco mostra le storie viste nelle ultime 24 ore e, in più, quelle più vecchie con una restrizione ancora in corso. Per prime vengono quelle con un effetto, poi le altre dalla più recente.
|
||||||
|
- I tre filtri: "con effetto" (una restrizione o un evento in corso); "sulle tue posizioni" (gli strumenti che il bot tiene, la loro classe e il mercato nel suo insieme); "tutte". Si apre su "sulle tue posizioni" quando c'è almeno una posizione. Sei righe, poi "Mostra le altre".
|
||||||
|
- Il calendario mostra al massimo sei eventi: i dati in dollari ed euro di impatto alto e medio dei prossimi 7 giorni, le banche centrali dei prossimi 31 e le trimestrali dei prossimi 14 per i titoli che il bot tiene. Accanto a ogni evento c'è l'effetto che avrà con le righe di oggi.
|
||||||
|
- Nella demo i conteggi (312, 9, 2), l'elenco delle fonti e la spesa del giorno vengono dagli aggregati dell'appendice F, come nelle altre schermate.
|
||||||
|
- Il numero delle notizie lette sta in una riga sotto il titolo e non nel sottotitolo della barra in alto, che in tutte le schermate dice data e aggiornamento.
|
||||||
|
- La Panoramica ora mostra le vere notizie che contano: quelle con un effetto o sulle posizioni, al massimo tre.
|
||||||
|
|
||||||
|
**14. Le impostazioni di notizie e calendario (13.5).**
|
||||||
|
- Le righe di 10.5 si accendono e si spengono da una scelta Accesa/Spenta. Ogni cambio finisce nello storico della configurazione.
|
||||||
|
- Le fonti si possono spegnere e marcare come affidabili. Ogni cambio finisce nello storico con la chiave `news.source:<nome>`. Aggiungere fonti nuove non si può ancora: l'elenco è quello di SPEC 4.4.
|
||||||
|
- La chiave del modello linguistico (`LLM_API_KEY`) e quelle di Finnhub e FRED si salvano cifrate come le chiavi dei conti. Non si mostrano più e non si provano al momento: se una non funziona lo dice lo stato delle fonti al giro successivo. Una chiave che arriva dalle variabili d'ambiente non si cambia dalla pagina.
|
||||||
|
- Il tetto di spesa del modello linguistico è un'impostazione (`news.llm.daily_cap`, 0,50 € all'inizio, al massimo 10 €). Chiave e tetto li usa l'analista del punto 15.
|
||||||
|
- Le riunioni di Fed e BCE passano dalla sezione Dati a questa.
|
||||||
|
- Nella demo la sezione si vede ma non si cambia.
|
||||||
|
|
||||||
|
**15. L'analista con il modello linguistico (#58; SPEC 4.5, 10.2 punto 5, 10.3, appendice B).**
|
||||||
|
- È facoltativo. Senza la chiave `LLM_API_KEY` non parte nessuna richiesta e le regole di 10.5 lavorano con il solo primo giudizio, come prima. Ollama non chiede una chiave.
|
||||||
|
- Il servizio si sceglie in Impostazioni fra tre: Anthropic (API Messages), un servizio con l'API di OpenAI, Ollama sul computer o in rete locale. Sono impostazioni anche il modello (`news.llm.model`, all'inizio `claude-haiku-5-5`, il più economico di novembre 2026), l'indirizzo, i due prezzi per milione di token (0,10 e 0,50 all'inizio) e il tetto. Nel codice non c'è nessun nome di modello fuori dal valore iniziale.
|
||||||
|
- Le richieste sono semplici chiamate HTTP scritte in casa, senza SDK: l'ADR 0004 e la regola generale escludono pacchetti nuovi.
|
||||||
|
- Un indirizzo `http://` si accetta solo verso il computer stesso o la rete locale (indirizzi privati, nomi senza punto, `.local`, `.lan`, `.internal`): la chiave non viaggia mai in chiaro su internet.
|
||||||
|
- **Cosa si manda.** Ogni 2 minuti, dopo il giro delle notizie, le storie viste nelle ultime 24 ore che toccano uno strumento tenuto o candidato, non ancora giudicate. Di ognuna: il titolo, fino a tre altri titoli o riassunti di 500 caratteri, e i nomi degli strumenti già collegati. Otto storie per richiesta, al massimo tre richieste per giro.
|
||||||
|
- **Il testo è un dato.** Le istruzioni fisse dicono al modello che il testo è copiato da internet e che non deve seguire nessuna istruzione che contiene. Il testo viaggia come JSON dentro `<news>…</news>`, con `<`, `>` e `&` scritti come sequenze di escape: non può chiudere il contenitore. Al modello non si offre nessuno strumento.
|
||||||
|
- **Cosa si tiene.** Solo l'oggetto dello schema dell'appendice B, con il numero della storia. Tutti i campi devono esserci, nessuno in più, ogni valore nel suo elenco o intervallo. Il riassunto è una riga di testo semplice di al massimo 160 caratteri, senza indirizzi, tag o segni di formattazione. Un giudizio fuori dallo schema si butta intero; una risposta che non è l'oggetto dello schema li butta tutti. Uno strumento nominato che non era già collegato alla storia si toglie.
|
||||||
|
- **Cosa può fare un giudizio.** Solo aggiungere. Un giudizio negativo che nomina lo strumento alza l'importanza della storia per le regole e la fa contare come negativa: con 3 vale la riga "notizia negativa", con 4 o 5 l'"evento grave". Un giudizio positivo, neutro o "non confermato" non toglie mai una restrizione. Quando la restrizione c'è solo per il modello, il diario lo dice: "secondo la rilettura del modello linguistico".
|
||||||
|
- **Tetto di spesa.** Prima di ogni richiesta si calcola il costo peggiore: ogni carattere mandato conta come mezzo token e la risposta come la più lunga ammessa. La richiesta parte solo se la spesa di oggi più quel costo resta sotto il tetto. Il costo registrato è quello dei token dichiarati dal servizio, mai più della stima. I prezzi sono in dollari e si contano come euro: è una sovrastima. Il giorno va da mezzanotte a mezzanotte, ora di Roma. Quando il tetto ferma una richiesta, il diario lo dice una volta al giorno.
|
||||||
|
- **Cache e richieste perse.** Ogni giudizio si salva con l'hash di ciò che è stato chiesto (versione delle istruzioni, servizio, modello, testi, strumenti). Una storia con le stesse parole lo riprende senza una nuova richiesta. Anche una risposta fuori dallo schema si salva, come problema, così non si paga due volte. Una richiesta senza nessuna risposta conta la stima e si riprova dopo 15 minuti.
|
||||||
|
- Due tabelle nuove, uguali sui due motori (migrazione `0011_news_analyst.sql`): `news_model_calls` e `news_verdicts`. In più la colonna `news_stories.verdict_id`.
|
||||||
|
- La schermata Notizie mostra il riassunto del modello sotto il titolo e dice quante notizie ha riletto oggi e quanto è costato.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Le notizie si accumulano già nel database con il loro primo giudizio e, dal #59, fermano o spostano gli acquisti secondo 10.5. Dal #60 si vedono nella schermata Notizie e mercato. Dal #58, con una chiave, un modello linguistico le rilegge e può solo aggiungere restrizioni, entro il tetto di spesa.
|
||||||
|
- Una parola chiave che sbaglia può fermare gli acquisti di uno strumento per 72 ore. È la direzione prudente: un acquisto in meno, mai uno in più. Se l'uso reale mostra troppe restrizioni inutili, la riga si spegne in Impostazioni e le parole si correggono con un test.
|
||||||
|
- 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.
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 0015 — PostgreSQL nei container con un processo init; nella CI, senza sincronizzazioni su disco
|
||||||
|
|
||||||
|
Data: 2026-11-15 · Stato: accettata · Precisa la CI (SPEC 15.5, ADR 0007) e il `docker-compose.yml` di sviluppo, issue #98, senza componenti esterni nuovi
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Dal 14 novembre 2026 il lavoro `test (postgres)` della CI falliva spesso, ma non sempre. Dopo uno-cinque minuti di test, il PostgreSQL di servizio chiudeva tutte le connessioni. I test rimasti fallivano con `57P03: the database system is in recovery mode` o con `EndOfStreamException`. Rilanciando il lavoro passava. In locale la suite passava sempre.
|
||||||
|
|
||||||
|
Il registro del lavoro non mostrava quello del server. Per vederlo, la CI ora stampa a fine lavoro registro, stato e memoria del contenitore PostgreSQL (`tasks ci-service-log`). Li legge dal socket di Docker che l'esecutore monta nel lavoro, senza il client `docker` né altro da installare.
|
||||||
|
|
||||||
|
In una prova con la suite ripetuta tre volte sullo stesso server, il server si è riavviato quattro volte. Ogni volta il registro dice la stessa cosa:
|
||||||
|
|
||||||
|
```
|
||||||
|
LOG: untracked child process (PID 248) exited with exit code 2
|
||||||
|
LOG: terminating any other active server processes
|
||||||
|
LOG: all server processes terminated; reinitializing
|
||||||
|
```
|
||||||
|
|
||||||
|
Nessun processo ucciso per memoria (`OOMKilled false`, nessun evento `oom` di Docker) e nessun segnale. Il processo "sconosciuto" che esce con codice 2 è `pg_isready`. Il codice 2 vuol dire "il server non ha risposto".
|
||||||
|
|
||||||
|
Che cosa succede:
|
||||||
|
1. Docker esegue il controllo di salute dentro il contenitore come `/bin/sh -c "pg_isready …"`.
|
||||||
|
2. Sull'esecutore di Unraid il disco è lento. Ogni `DROP DATABASE` dei test forza un checkpoint immediato, con fino a 21 secondi di scrittura sul disco. In quei momenti il server può metterci più di 3 secondi a rispondere.
|
||||||
|
3. Passato il tempo massimo del controllo (`--health-timeout 3s`), Docker chiude la shell. `pg_isready` resta senza genitore e il sistema lo affida al processo 1 del contenitore. L'immagine `postgres` non ha un processo init, quindi il processo 1 è PostgreSQL stesso.
|
||||||
|
4. Quando `pg_isready` si arrende ed esce, PostgreSQL vede morire un figlio che non conosce. Per prudenza lo tratta come un suo processo andato in crash: chiude tutte le connessioni e rifà il recupero dal registro delle scritture.
|
||||||
|
|
||||||
|
Spiega anche gli altri indizi:
|
||||||
|
- capita solo a volte, perché serve un server lento proprio mentre scade il controllo;
|
||||||
|
- si vede da quando la suite è cresciuta con il commit della raccolta dei dati (issue #95), cioè più database creati e cancellati;
|
||||||
|
- in locale non capita, perché il disco è veloce.
|
||||||
|
|
||||||
|
Non c'entrano la memoria, `/dev/shm` (64 MiB, il server ne usa poco) e `pg_database_size` del campionatore. Il `CREATE`/`DROP DATABASE` dei test rende il server lento, ma da solo non lo fa ripartire.
|
||||||
|
|
||||||
|
**Seconda causa, vista dopo la prima correzione.** In un'esecuzione con la correzione il server non è più ripartito, ma 7 test sono falliti lo stesso:
|
||||||
|
- `Timeout during reading attempt` dopo circa 1 minuto e 18 secondi;
|
||||||
|
- `/primo-avvio?errore=database` nel test del primo avvio desktop, lo stesso errore visto il 14 novembre nell'esecuzione 304.
|
||||||
|
|
||||||
|
Il registro del server mostra il motivo:
|
||||||
|
- ogni `DROP DATABASE` forza un checkpoint immediato, e i checkpoint passano uno alla volta;
|
||||||
|
- sul disco dell'esecutore la sola sincronizzazione su disco ha richiesto fino a 37 secondi (`sync=36.849 s`);
|
||||||
|
- i `DROP DATABASE` in coda hanno superato i 30 secondi di attesa del client (`canceling statement due to user request`);
|
||||||
|
- il test desktop non ha avuto la connessione nei 5 secondi dell'applicazione.
|
||||||
|
|
||||||
|
Il server era vivo, ma fermo ad aspettare il disco.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
1. **Un processo init davanti a PostgreSQL.** Il servizio `postgres` della CI parte con `--init`, e quello di `docker-compose.yml` con `init: true`. Il processo 1 diventa il piccolo init di Docker: raccoglie lui i processi rimasti senza genitore, e PostgreSQL non li vede più.
|
||||||
|
2. **`pg_isready` si arrende prima di Docker.** Il controllo è `pg_isready -U anubis -d anubis -t 5` con `--health-timeout 15s`. Così Docker non chiude mai la shell mentre `pg_isready` sta ancora aspettando. L'intervallo resta di 3 secondi, quindi l'avvio non rallenta.
|
||||||
|
3. **Nella CI il PostgreSQL dei test non sincronizza su disco.** Il servizio nasce con `POSTGRES_INITDB_ARGS: "--no-sync -c fsync=off -c synchronous_commit=off -c full_page_writes=off"` (l'opzione `-c` di `initdb` esiste da PostgreSQL 16). Così il checkpoint forzato da ogni `DROP DATABASE` scrive solo nella memoria del sistema e dura millisecondi. È ammesso solo perché quel server vive per un lavoro e poi si butta. Non vale per `docker-compose.yml` né per nessun database vero: lì un'interruzione di corrente senza `fsync` può rovinare i dati.
|
||||||
|
4. **Il registro del server resta nella CI.** Il passo `PostgreSQL log` gira sempre a fine lavoro `test (postgres)`. Mostra anche se l'init è attivo e com'è il controllo di salute. Il prossimo problema del server si legge lì, senza rilanciare alla cieca.
|
||||||
|
|
||||||
|
Le misure 1 e 2 si coprono a vicenda: ognuna da sola basta a togliere la prima causa. La 3 toglie la seconda, e rende anche più raro un controllo di salute lento.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Il lavoro `test (postgres)` non perde più il server a metà. Rilanciarlo per farlo passare nascondeva la causa, e ora non serve più.
|
||||||
|
- Nessun test e nessuna parte di Anubis cambia: il difetto era nel modo in cui gira il contenitore, non nel bot.
|
||||||
|
- I test su PostgreSQL nella CI non provano la durata dei dati dopo un'interruzione. Non lo facevano neanche prima: quella è una proprietà di PostgreSQL, non di Anubis.
|
||||||
|
- **Per l'installazione su Unraid:** se il PostgreSQL che usa Anubis gira in un container con un controllo di salute basato su `pg_isready` e senza init, ha lo stesso rischio sotto carico. Il rimedio è lo stesso: l'opzione `--init` (in Unraid, "Extra Parameters") oppure un controllo con `-t` più breve del suo tempo massimo. Il template `deploy/unraid/anubis.xml` non installa PostgreSQL, quindi lì non cambia niente.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# 0016 — Il motore dell'esercitazione della guardia non esce dal computer
|
||||||
|
|
||||||
|
Data: 2026-11-16 · Stato: accettata · Precisa l'ADR 0012 (punto 5), issue #102, senza componenti esterni nuovi
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
L'esercitazione della guardia (`Anubis.Guard drill`, nell'immagine `anubis drill`, e il test `TheGuardDrillPassesWithTheRealEngineAsChildProcess`) avvia il motore vero come processo figlio. L'ADR 0012 dice che i prezzi vengono da un finto OKX locale (`ANUBIS_DRILL_OKX_URL`, solo su indirizzi loopback). La documentazione della prova aggiunge che dal computer non esce nulla.
|
||||||
|
|
||||||
|
Dalla Fase 7 non era più vero. Il motore della prova faceva il suo lavoro normale anche sul resto della rete:
|
||||||
|
- la lettura delle notizie ogni 2 minuti, sui feed RSS veri (ANSA, CNBC, CoinDesk e gli altri);
|
||||||
|
- lo scaricamento del modello ONNX del tono da Hugging Face;
|
||||||
|
- e, già da prima, i cambi della BCE, l'umore del mercato, il calendario economico e gli archivi di Binance.
|
||||||
|
|
||||||
|
Si vede nella CI, esecuzione 331, lavoro 1122: righe "News from ANSA…" e "News classifier ready" dal motore della prova. Sull'esecutore lento della CI è lavoro in più proprio mentre la prova misura i tempi del motore.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
1. **La prova si riconosce da sola, senza variabili nuove.** Il motore è nella prova quando gira sotto la guardia e `ANUBIS_DRILL_OKX_URL` punta a un indirizzo locale: le stesse condizioni per cui usa già il finto OKX. Fuori dalla guardia la variabile non conta, come prima.
|
||||||
|
2. **Nella prova la raccolta dei dati non esce dal computer** (`MarketDataService` con `offline`):
|
||||||
|
- il lavoro `notizie` non è in programma;
|
||||||
|
- il modello del tono non si scarica;
|
||||||
|
- tutte le richieste della raccolta passano da `LoopbackOnlyHandler`. Quelle verso il computer stesso (il finto OKX) partono. Le altre ricevono subito, senza partire, una risposta 403 con la frase "Esercitazione della guardia: nessuna richiesta esce dal computer.".
|
||||||
|
3. **Il 403 è una risposta definitiva, non un errore di rete.** Un errore di rete farebbe ripetere la richiesta dopo 2, 4 e 8 secondi. Così invece ogni fonte fallisce subito e lo annota come al solito, e i lavori del motore tengono il loro ritmo.
|
||||||
|
4. **Un ottavo controllo nella prova**, dopo i sette dell'ADR 0012: nessuna notizia letta e nessun file nella cartella `models`. Vale nei test e nell'immagine Docker.
|
||||||
|
5. **Un test senza processi** (`TheDrillsEngineReadsNoNewsAndSendsNothingOutsideLoopback`) costruisce la raccolta dei dati come la costruisce il motore nella prova. Su una rete finta esegue una volta ogni lavoro, un giro dello storico e un giro delle notizie, e controlla:
|
||||||
|
- nessun lavoro `notizie`;
|
||||||
|
- tutte le richieste arrivate alla rete sono verso loopback;
|
||||||
|
- ogni feed è stato provato e fermato;
|
||||||
|
- nessuna notizia e nessun modello.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- La documentazione della prova torna vera per la raccolta dei dati: i prezzi vengono dal finto OKX e il resto non parte. Il motore della prova non ha chiavi né per Alpaca né per Telegram e non riceve l'indirizzo del segnale di vita: neanche quelle parti mandano richieste.
|
||||||
|
- Nel registro della prova compaiono le fonti rifiutate (cambi, umore, calendario, Binance) come fonti che non rispondono. È atteso: nella prova non servono.
|
||||||
|
- Il bot vero non cambia. Senza la guardia, o senza il finto OKX locale, la raccolta dei dati è quella di sempre.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# 0017 — Correzioni della revisione indipendente della Fase 7
|
||||||
|
|
||||||
|
Data: 2026-12-01 · Stato: accettata · Precisa l'ADR 0014 (punti 3, 4, 7, 9, 10, 13 e 15) e SPEC 4.4, 5.5, 8.3, 10.2, 10.3, 10.5 e 12.3
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La revisione con un subagent a contesto pulito (issue #61) ha letto tutto il codice della Fase 7 dopo l'unione di #58 in `main`. Ha trovato difetti veri, alcuni dei quali smentivano le prove date per #58. Ogni difetto è stato riprodotto con un test che falliva, oppure verificato leggendo il codice, e poi corretto.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. L'analista con il modello linguistico (ADR 0014, punto 15).**
|
||||||
|
- Una risposta che è JSON valido ma non testo valido (mezzo carattere Unicode, una forma inattesa) si scarta come ogni valore fuori dallo schema. Prima generava un'eccezione: la richiesta si ripagava a ogni giro fuori dal tetto e il diario delle notizie si fermava.
|
||||||
|
- Il costo stimato si scrive **prima** della richiesta e si sostituisce con quello vero alla risposta. Uno spegnimento a metà conta la stima.
|
||||||
|
- La stima conta un token per ogni byte mandato, più 1.000 token di margine del servizio. Il costo vero si registra sempre intero, anche se supera la stima: prima veniva tagliato alla stima e la spesa poteva superare il tetto senza che si vedesse.
|
||||||
|
- Qualunque guasto dell'analista o di una fonte resta suo: le altre fonti si leggono e il diario si scrive.
|
||||||
|
- Il riassunto rifiuta anche gli indirizzi senza `http` e i caratteri invisibili o che invertono il testo.
|
||||||
|
|
||||||
|
**2. Il giro delle notizie non rallenta il motore.**
|
||||||
|
- Il lavoro "notizie" gira accanto alla coda dei lavori e mai due volte insieme. Prima una fonte lenta o il modello ritardavano il battito del motore e il controllo del rischio di diversi minuti. Alla chiusura del bot si aspetta che finisca.
|
||||||
|
- Il classificatore legge gli articoli prima di prendere la scrittura del database, che è una sola per tutto il bot.
|
||||||
|
|
||||||
|
**3. Parole e nomi.**
|
||||||
|
- L'apostrofo separa le parole chiave come ogni altro segno: "un'indagine" e 'fraud' tra apici si trovano.
|
||||||
|
- Un nome si trova anche dopo un articolo con l'apostrofo ("dell'Apple"), con il possessivo inglese e nella prima parte di una parola composta ("Apple-led"). Un nome che contiene il possessivo resta intero: "Wendy's" non è "Wendy".
|
||||||
|
- "The" non fa parte del nome, davanti o tra parentesi. Se dopo "The" resta una parola sola (The Metals Company) il nome non collega da solo: serve il ticker o l'elenco degli alias.
|
||||||
|
- Gli alias sono un elenco breve nel codice dei modi comuni di chiamare le grandi società (Google, Facebook, JPMorgan, Coca-Cola, Boeing…). Valgono solo se il ticker è nel catalogo.
|
||||||
|
- Due classi di azioni con lo stesso nome (Alphabet) si collegano tutte e due.
|
||||||
|
|
||||||
|
**4. Storie.**
|
||||||
|
- Un articolo entra in una storia solo se parla di almeno uno degli stessi strumenti, o se uno dei due non ne nomina nessuno. Prima "Apple batte le stime" e "Microsoft batte le stime" erano la stessa storia, e una confermava l'altra.
|
||||||
|
- Le finestre di 10.5 si contano dal primo articolo con l'importanza della storia, non dal primo in assoluto: una storia diventata grave dopo 40 ore vale 72 ore da allora. Quello che solo il modello alza conta dall'inizio, perché il modello legge la storia com'era al primo arrivo. Il tono resta contato dall'inizio.
|
||||||
|
- Il caso grave mostrato segue l'ordine di 10.2 e non l'alfabeto.
|
||||||
|
- Cambiare l'etichetta "affidabile" di una fonte vale anche per le storie già lette.
|
||||||
|
|
||||||
|
**5. Trimestrali.**
|
||||||
|
- Conti usciti prima dell'apertura o durante la seduta liberano l'ingresso della seduta dopo; quelli dopo la chiusura, o senza orario, lo fermano (10.5). Prima fermavano tutti.
|
||||||
|
- La riga del diario si scrive quando la restrizione comincia davvero: seduta d'ingresso più tre, cioè quattro giorni lavorativi. Una festività in mezzo può ritardare la riga di un giorno, ma non la regola, che conta le sedute di borsa. Senza un calendario fresco di Finnhub la riga non si scrive, come la regola non agisce.
|
||||||
|
- Una notizia su un titolo tenuto o candidato con i conti in arrivo si **mostra** con importanza 3 e "evento in arrivo" (10.2, punto 4). L'importanza salvata non cambia: una notizia con il tono non letto diventerebbe altrimenti "negativa" solo per il calendario.
|
||||||
|
|
||||||
|
**6. Acquisti fermati e confronto a un passo.**
|
||||||
|
- Una restrizione che finisce prima dell'ora dell'acquisto non cambia niente e il diario tace. Quando il giorno è un altro, il diario lo dice.
|
||||||
|
- Un acquisto di azioni rimandato a mercato chiuso va cinque minuti dopo l'apertura, come tutti (5.5), non all'apertura.
|
||||||
|
- Il confronto a un passo (12.3) rifà la decisione con lo stesso calendario delle trimestrali. Prima segnava come differenza ogni acquisto tolto per i conti, e quel conto serve per passare di stadio.
|
||||||
|
|
||||||
|
**7. Quello che manca di 10.2, punto 1.**
|
||||||
|
- Il flusso Alpaca News richiede le chiavi del conto paper, che non ci sono. Resta facoltativo (API-NOTES, A5).
|
||||||
|
- I comunicati SEC dei titoli in portafoglio vengono da EDGAR, che chiede nell'intestazione un nome e un contatto (API-NOTES, F8). Il contatto è un dato dell'utente: non si manda senza il suo permesso. Il feed generale dei comunicati SEC resta tra le fonti.
|
||||||
|
- Le due parti sono nella issue #107, in attesa dell'utente.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Più collegamenti giusti vogliono dire più restrizioni giuste, e anche qualche restrizione in più: la direzione resta prudente.
|
||||||
|
- Gli alias vanno aggiornati a mano se una grande società cambia nome.
|
||||||
|
- Le storie e gli articoli già salvati non si rileggono: valgono le nuove regole per quelli che arrivano.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# 0018 — Scelte della Fase 8 (apprendimento)
|
||||||
|
|
||||||
|
Data: 2026-12-01 · Stato: accettata · Precisa gli ADR 0003 (riga Apprendimento) e 0004 (tabella dei componenti) e SPEC 5.4, 11 e 13.6
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 8 costruisce il modulo che stima quanto è probabile che un segnale vada bene (SPEC 11). L'ADR 0003 prevedeva ML.NET con LightGBM. Il 18/11/2026 l'utente ha dato una regola più stretta per tutti i progetti: niente componenti esterni, tutto il codice in casa.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. I modelli sono scritti in casa.** `Microsoft.ML`, `Microsoft.ML.LightGbm` e `Microsoft.ML.FastTree` sono autorizzati ma non si usano: non entra nessun pacchetto nuovo, nessuna libreria nativa e `libgomp1` non serve. Al loro posto:
|
||||||
|
- regressione logistica regolarizzata (riferimento);
|
||||||
|
- alberi potenziati: pochi livelli, molti esempi per foglia, passo piccolo, regolarizzazione (principale, al posto di LightGBM);
|
||||||
|
- foresta casuale (sfidante, al posto del percettrone come già in ADR 0003), con lo stesso codice degli alberi;
|
||||||
|
- calibrazione di Platt e isotonica.
|
||||||
|
|
||||||
|
Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento dura meno di un secondo. Tutto è deterministico: stessi dati, stesso modello.
|
||||||
|
|
||||||
|
**2. Esempi.**
|
||||||
|
- Un esempio nasce dalla prima intenzione d'ingresso su uno strumento che la strategia non ha, anche se poi è rifiutata e anche in osservazione. Finché l'operazione simulata di quell'esempio è aperta, riproporre l'ingresso non ne crea un altro.
|
||||||
|
- L'esempio si scrive nella stessa transazione della decisione. Un guasto dell'apprendimento non ferma mai una decisione: la strategia prosegue come se il modello non ci fosse.
|
||||||
|
- `ml_features` contiene l'esempio con i suoi indizi, `ml_labels` l'esito (una volta sola), `ml_predictions` le stime. In più `ml_events` (la storia mostrata) e `ml_state`.
|
||||||
|
|
||||||
|
**3. Etichetta.** È l'operazione dell'esempio simulata da sola con il motore del backtest: si compra all'apertura dopo la decisione, sempre la stessa quota, si seguono le uscite e gli stop della strategia, senza aumenti, riduzioni né nuovi acquisti, con le commissioni e lo scostamento di sempre. Il risultato è una quota di quanto investito. Un'operazione che non può partire (sotto il minimo del mercato) resta senza esito e non addestra.
|
||||||
|
- `equity_momentum` ha bisogno di tutto l'universo, perché esce anche per la posizione in classifica; le altre guardano solo il proprio strumento.
|
||||||
|
|
||||||
|
**4. Indizi.** Tutti quelli di 11.2, calcolati con le sole barre fino alla decisione e con i valori esterni già datati **e già salvati** in quel momento.
|
||||||
|
- Si ricostruiscono dallo storico: strategia, forza, distanza dallo stop, volatilità e rapporto, volumi, regime, ampiezza, giorno della settimana.
|
||||||
|
- Restano fuori finché non ci sono 200 esempi dal vivo che li contengono: notizie, evento più grave, paura e avidità, VIX, finanziamento e open interest, giorni alla trimestrale. Paura e avidità e VIX hanno uno storico pubblico, ma non è tra i dati già scaricati: per ora seguono la stessa regola.
|
||||||
|
- L'open interest è il rapporto con la sua media di 30 giorni: il valore assoluto non vuol dire niente negli anni. Un valore esterno troppo vecchio (la fonte si è fermata) è mancante.
|
||||||
|
- La forza del segnale è della strategia e viaggia con l'intenzione (`Intent.Strength`); nessuna regola la legge.
|
||||||
|
|
||||||
|
**5. Addestramento e scelta.**
|
||||||
|
- Gli esempi vivono dalla decisione alla chiusura dell'operazione simulata. Due prove, sempre su esempi mai studiati: finestre che avanzano (5 pezzi) e combinazioni purgate (6 gruppi, 2 in verifica, 15 combinazioni). Un esempio che si sovrappone nel tempo a uno di verifica, o comincia nei 10 giorni dopo, non addestra.
|
||||||
|
- La calibrazione si adatta su stime di esempi non studiati (5 pezzi purgati): Platt sotto 1.000 casi, isotonica sopra; i gradini dell'isotonica hanno almeno 20 casi e nessuna stima va oltre 1 su 22 dai due estremi. Un punteggio che fuori campione non dice niente, o dice il contrario, diventa la frequenza di base.
|
||||||
|
- **Regola della scelta, fissata prima dei numeri**: vince il miglior guadagno medio per operazione proposta nelle combinazioni (al decimo di centesimo); a parità, il log-loss più basso; poi gli alberi potenziati. La foresta entra solo se batte gli altri su tutti e due.
|
||||||
|
- Il guadagno di un esempio è quota chiesta × risultato × capitale della strategia in euro. Se nessuna strategia con capitale ha esempi, si misura su tutte e il rapporto lo dice.
|
||||||
|
- Ogni tentativo è una riga di `ml_models`: il modello scelto con la sua versione, gli altri come `tried`.
|
||||||
|
- I pesi degli indizi vengono dal peggioramento delle stime, fuori campione, quando i valori di un gruppo di indizi si mescolano; su 100 con il metodo dei resti più alti.
|
||||||
|
- Meno di 100 esempi con esito: nessun modello.
|
||||||
|
|
||||||
|
**6. Moltiplicatore.** Come in 11.1, con le due soglie nelle Impostazioni (intero fino a 0 punti sotto la frequenza di base, zero da 10 punti sotto). Un numero non valido vale 1: un modello rotto non tocca le operazioni.
|
||||||
|
|
||||||
|
**7. Frequenza di base e primo modello.** `anubis learning base` ricostruisce gli esempi di `crypto_trend` sull'universo ampio del suo protocollo, con i parametri in uso, e scrive `docs/learning/first-model.json` (modello, rapporto, frequenze di base, esempi) e il rapporto leggibile. Il file viaggia nel programma come gli esiti dei backtest.
|
||||||
|
- Al primo avvio, se non ce n'è nessuno, diventa il modello in carica, in osservazione. Un file nuovo (revisione trimestrale) aggiorna frequenze di base ed esempi, non il modello: quello cambia solo con una promozione.
|
||||||
|
- Una strategia senza frequenza di base non viene stimata: moltiplicatore 1, nessuna stima, non conta tra i segnali valutati. Oggi vale per le due strategie sulle azioni, finché manca lo storico di Alpaca.
|
||||||
|
- **Esito onesto del primo modello**: 1.844 esempi crypto, 18,3% in guadagno. È scelta la regressione logistica. Le sue stime sono appena migliori di chi risponde sempre la frequenza di base (log-loss 0,4796 contro 0,4807 nelle combinazioni, 0,4735 contro 0,4788 in avanti); alberi e foresta fanno peggio. Il guadagno medio per operazione proposta passa da +1,69 a +1,76 euro nelle combinazioni e da +1,76 a +1,81 in avanti: differenze piccole, che possono essere caso. L'indizio che pesa di più è il giorno della settimana, e questo invita alla prudenza. Resta in osservazione come tutti i modelli; i criteri di 11.5 lo fermano se non impara altro.
|
||||||
|
|
||||||
|
**8. Il modello nelle decisioni.** È l'ultimo correttivo, prima del rischio: tocca ingressi e aumenti, mai uscite e riduzioni.
|
||||||
|
- Il moltiplicatore nasce con l'esempio e vale per l'operazione finché non si chiude, aumenti e riavvii compresi, anche se nel frattempo il modello cambia o viene messo da parte. La messa da parte vale quindi per le operazioni nuove.
|
||||||
|
- Su una posizione già rimpicciolita un aumento più piccolo del 20% della dimensione ridotta non si fa: sarebbe rincorrere gli arrotondamenti ogni giorno.
|
||||||
|
- Il modello stima solo le strategie che ha studiato.
|
||||||
|
- Un guasto del modello lascia le intenzioni com'erano e finisce nel registro tecnico. Il moltiplicatore di un'operazione già nata non si perde nemmeno se il resto dell'apprendimento non si legge.
|
||||||
|
- Finché il modello non conta, accanto a ogni operazione si scrive la stima e il moltiplicatore che avrebbe dato (riga `model` della decisione, stime in `ml_predictions`), sia del modello in carica sia dello sfidante.
|
||||||
|
|
||||||
|
**9. Controllo della notte** (03:00 di Roma; dopo un'assenza una volta sola, 5.6). Si guardano le stime che il modello in carica ha fatto per ogni esempio, quelle fatte da sfidante comprese.
|
||||||
|
- Precisione sugli ultimi 60 casi; conta da 40. Sotto il 50% il modello è messo da parte.
|
||||||
|
- ADWIN sull'errore quadratico (δ 0,002, finestra esatta, parti di almeno 10 casi), ricalcolato ogni notte da capo: nessuno stato da perdere. Un aumento vale come allarme per i 30 casi successivi; un calo lo chiude.
|
||||||
|
- Deriva degli indizi: negli ultimi 60 esempi, più del 20% dei valori di un indizio in uso sta fuori dall'intervallo 1%–99% visto in addestramento. Il giorno della settimana e la strategia non contano.
|
||||||
|
- Il rientro è automatico, al primo controllo senza motivi. Messa da parte e rientro si notificano.
|
||||||
|
|
||||||
|
**10. Domenica.** Senza sfidante se ne addestra uno, se ci sono esiti nuovi rispetto all'ultimo addestramento; con uno sfidante si guarda solo se i casi di confronto hanno passato una nuova soglia. Una domenica persa si recupera al primo controllo, una volta sola. Una promozione annullata lascia la versione tra le annullate: non torna da sola.
|
||||||
|
- Le strategie senza frequenza di base non addestrano: nessuno potrebbe stimarle.
|
||||||
|
|
||||||
|
**11. Avvio (11.5).** I 300 segnali sono quelli con un esito; almeno 100 devono essere di strategie con capitale (punto 18). Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte.
|
||||||
|
|
||||||
|
**12. Scostamento (11.6).** Il primo controllo notturno di ogni mese confronta, per fascia di liquidità (azioni; BTC, ETH e SOL; altre crypto), lo scostamento delle esecuzioni di conti di prova e reali degli ultimi 365 giorni. La fascia è l’unica variabile della regressione: il suo risultato è la media, con un intervallo al 95% a blocchi.
|
||||||
|
- Servono 30 esecuzioni. Gli stop scattati non contano: il salto di prezzo è già nel modo in cui simulatore e backtest li eseguono.
|
||||||
|
- Sale da sola solo se tutto l’intervallo sta sopra la stima in uso; scende solo su esecuzioni con soldi veri, con tutto l’intervallo sotto, e solo dopo la conferma nel Laboratorio. La stima si arrotonda per eccesso a mezzo punto base e non scende sotto mezzo punto. Una proposta non confermata scade il mese dopo.
|
||||||
|
- Lo scostamento si misura dal prezzo medio, quindi contiene anche la metà della forbice; il simulatore parte già dal denaro o dalla lettera: così conta un po’ di più, dal lato prudente.
|
||||||
|
- Un test nel Laboratorio scrive nel piano la tabella in uso, se diversa da quella di partenza: i piani già scritti restano identici. Le etichette (punto 3) e gli esiti di qualifica usano sempre la tabella di partenza: gli esempi restano confrontabili negli anni e il “previsto” di 12.3 resta quello della qualifica.
|
||||||
|
|
||||||
|
**13. Impatto delle notizie.** Per tipo di evento (parole chiave dei casi gravi, poi il tipo detto dal modello linguistico), il rendimento medio a 1 e a 5 chiusure dalla prima chiusura dopo la pubblicazione, sugli strumenti collegati. Solo informativa.
|
||||||
|
|
||||||
|
**14. Scoperte.** Le domande sono fisse nel codice (agitazione dei prezzi, fase del mercato, ampiezza, volumi, notizie molto negative, paura e avidità estreme, VIX, giorno della settimana), per strategia: il bot non ne cerca altre. L’errore conta come un caso solo ciò che è deciso nello stesso mese. Sotto i 100 casi basta che la differenza superi 1,96 errori e il giudizio dice da solo quanto vale; da 100 in su la soglia si alza con il numero di domande fatte. “Non conta” si dice solo con almeno 100 casi.
|
||||||
|
|
||||||
|
**15. Schermata Apprendimento** (mockup 06).
|
||||||
|
- I numeri del confronto tra modello in carica e sfidante sono quelli della verifica fatta all’addestramento, sui casi che il modello non aveva studiato. La precisione della Panoramica è la stessa.
|
||||||
|
- Il grafico delle probabilità mostra i segnali dal vivo appena una fascia ne ha almeno 20; fino ad allora mostra la verifica sui casi storici e lo dice. Una fascia sotto i 20 casi è dichiarata inaffidabile una per una.
|
||||||
|
- I grafici sono SVG e CSS fatti in casa, con le stesse cifre in una tabella (13.4); niente JavaScript.
|
||||||
|
- Il sottotitolo del mockup sta sotto la testata, come in Notizie: la riga con data e ora della testata è comune a tutte le schermate.
|
||||||
|
- L’operazione MSFT dei dati dimostrativi mostra la stima (61%, contro il 48% abituale): l’appendice F.7 non dà la frequenza di base, il 48% è quello della scoperta sui rimbalzi.
|
||||||
|
|
||||||
|
**16. Impostazioni del modello.** Soglie e messa da parte si cambiano solo dalla pagina Impostazioni, non dall’API generica. Rimpicciolire meno, o mettere da parte il modello, aumenta l’esposizione: con una strategia su soldi veri servono la frase e la password di 12.4. Rimpicciolire di più, o rimetterlo al suo posto, è libero.
|
||||||
|
|
||||||
|
**17. Correzioni della revisione indipendente** (due revisori a contesto pulito, sui calcoli e sulle schermate).
|
||||||
|
- La calibrazione isotonica usava come limite il primo gradino, anche di due casi: con pochi vincenti schiacciava tutte le stime verso l'alto. Il primo modello è stato rifatto con la calibrazione corretta, con la stessa regola di scelta, fissata prima.
|
||||||
|
- Una decisione recuperata in ritardo legge il mondo esterno com'era all'ora in cui doveva essere presa.
|
||||||
|
- Gli esempi si scrivono dentro un punto di salvataggio della transazione: un errore annulla solo loro, anche su PostgreSQL.
|
||||||
|
- Un'etichetta che non riesce non ferma il controllo della notte né la domenica: l'errore resta nel registro del lavoro. La notte si rifà una volta anche dopo che il computer ha dormito a lungo con il programma acceso.
|
||||||
|
- L'etichetta esce prima della trimestrale che la decisione conosceva, presa dagli indizi salvati.
|
||||||
|
- Un file storico nuovo non aggiunge un esempio per un'operazione già vissuta dal vivo. La data di addestramento del primo modello è la fine del suo storico.
|
||||||
|
- Le fasce di probabilità contano gli esempi e non le verifiche: le combinazioni verificano ogni esempio cinque volte. Sullo schermo le fasce dal vivo sono conteggi semplici; la pesatura per maturazione resta nei criteri di 11.4 e 11.5.
|
||||||
|
- Il contatore della prova mostra la prossima soglia non ancora giudicata; passata la soglia, dice quando si decide. Un controllo fatto su un'altra versione non si mostra.
|
||||||
|
- Una precisione sotto la soglia d'allarme non si mostra mai come 50%.
|
||||||
|
- La conferma di una stima di costo e "ho visto l'assenza" controllano il codice della pagina (CSRF), come gli altri moduli.
|
||||||
|
- La scheda di un'operazione mostra la stima anche quando il segnale è nato giorni prima dell'acquisto, e dice se il modello era messo da parte.
|
||||||
|
|
||||||
|
**18. Seconda lettura, sulle correzioni** (quattro lettori a contesto pulito, ogni rilievo passato da chi provava a smentirlo).
|
||||||
|
- **Avvio (11.5)**: il miglioramento si misura su almeno 100 segnali di strategie con capitale, oltre ai 300 in tutto. Prima ne bastava uno: l'intervallo su pochi casi aveva larghezza zero. Con meno di tre blocchi (30 casi) un intervallo non dice più niente. Questi segnali si pesano per maturazione tra loro, non insieme a quelli più vecchi in osservazione. La schermata dice quanti ne mancano.
|
||||||
|
- **Lavori recuperabili (5.6)**: un lavoro da recuperare conta dal primo avvio che lo conosce (la riga in `jobs` nasce subito). Prima, su un computer sempre spento alle 03:00, la notte del modello non sarebbe mai partita.
|
||||||
|
- **La notte aspetta le barre**: dopo un'assenza aspetta che lo storico dell'ultimo giorno chiuso sia scaricato, al massimo mezz'ora. Senza rete prosegue con quello che ha.
|
||||||
|
- **Notizie all'ora della decisione**: una storia si ricostruisce dagli articoli, dai collegamenti e dai giudizi salvati fino a quell'ora, perché cresce anche dopo la prima lettura.
|
||||||
|
- **Etichetta e trimestrali**: una trimestrale già uscita entro la seduta d'ingresso non chiude l'operazione simulata. Limite: l'orario della trimestrale non è tra gli indizi, quindi quella della seduta d'ingresso vale sempre come uscita. Succede solo con il filtro delle trimestrali spento dall'utente.
|
||||||
|
- Una promozione annullata fa ripartire da zero le soglie dello sfidante in prova.
|
||||||
|
- Una stima che fallisce vale 1 solo per l'operazione nuova; quelle già nate tengono il loro moltiplicatore.
|
||||||
|
- Scheda dell'operazione: la riga del modello si cerca quando manca nella decisione dell'acquisto, non in tutta la finestra, e vale anche se l'operazione simulata si è chiusa lo stesso giorno. Una riduzione non si scrive mai "al 100%" né "al 0%".
|
||||||
|
- La frase "è ben tarato" sui segnali dal vivo usa l'errore del criterio di avvio, come il resto della pagina; punti e percentuali restano conteggi semplici.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# 0019 — Nella CI i database SQLite delle prove stanno in memoria
|
||||||
|
|
||||||
|
Data: 2026-12-01 · Stato: accettata · Continua l'ADR 0015 (CI, SPEC 15.5), senza componenti esterni nuovi
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Il 1° dicembre 2026 la CI di `main` (run 557, lavoro `test (sqlite)`) è fallita in `HealthChecksDatabaseAndScheduler`: `/health` ha risposto 503. Il registro mostra che per oltre 6 secondi nessun test è avanzato, e il ping al database ha superato il suo limite di 5 secondi. Lo stesso codice era passato sul branch e nel lavoro PostgreSQL.
|
||||||
|
|
||||||
|
È la causa già vista nell'ADR 0015: il disco dell'esecutore su Unraid si ferma per secondi sotto carico. Lì il rimedio riguardava solo PostgreSQL. I database SQLite dei test sincronizzano ogni scrittura (`synchronous=FULL`, come dal vivo), e la Fase 8 ne ha aggiunti molti.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
1. **Cartella temporanea in memoria.** Il contenitore del lavoro `test` monta un `tmpfs` da 4 GB al massimo in `/test-tmp`, e le prove la usano come cartella temporanea (`TMPDIR`). Il codice di Anubis e le impostazioni di SQLite restano quelli veri.
|
||||||
|
2. **Il test di `/health` aspetta.** Un computer fermo da più di 5 secondi *deve* risultare non disponibile: il test guarda la risposta a cui si arriva entro 30 secondi. Uno scheduler o un database davvero fermi lo fanno fallire ancora, e il messaggio dice quale.
|
||||||
|
|
||||||
|
## Alternative scartate
|
||||||
|
|
||||||
|
- `synchronous=OFF` nei test: cambierebbe il codice che si prova.
|
||||||
|
- Rilanciare il lavoro: nasconde la causa.
|
||||||
|
- Meno test in parallelo: la CI durerebbe di più e il disco si fermerebbe lo stesso.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- I test SQLite della CI non provano la durata dei dati dopo un'interruzione di corrente: non lo facevano nemmeno prima.
|
||||||
|
- In locale non cambia niente.
|
||||||
|
- Il passo `Check` stampa lo spazio della cartella: se il montaggio sparisse si vedrebbe lì.
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
# Backtest di `crypto_trend` (Trend crypto)
|
||||||
|
|
||||||
|
**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 32,8%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,835, serve ≤ 0,40. Resta in osservazione.
|
||||||
|
|
||||||
|
Calcolato il 2026-11-11 con la versione 1 della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.
|
||||||
|
|
||||||
|
Per rifarlo: `anubis backtest base --to 2026-10-31`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/crypto_trend.outcome.json`.
|
||||||
|
|
||||||
|
## Dati
|
||||||
|
|
||||||
|
- Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.
|
||||||
|
- Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno (7133 giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1).
|
||||||
|
- 47 coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni.
|
||||||
|
- Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.
|
||||||
|
- Senza archivi nel periodo, quindi non usate: BCCEUR, VENEUR.
|
||||||
|
|
||||||
|
## Riepilogo
|
||||||
|
|
||||||
|
| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
|
||||||
|
|---|---|---:|---:|---:|---:|---:|---|
|
||||||
|
| Universo ampio | `coin_vol=10;max_stop=20` | 10,4% | −32,8% | 7.264,22 € | 0,924 | 0,085 | non superata |
|
||||||
|
| BTC, ETH e SOL | `coin_vol=20;max_stop=10` | 12,2% | −15,0% | 10.274,96 € | 0,961 | 0,835 | non superata |
|
||||||
|
|
||||||
|
## Cosa conserva il bot
|
||||||
|
|
||||||
|
- Calo massimo del backtest: −32,8%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).
|
||||||
|
- Scostamento di prezzo previsto: 11,94 punti base; costo stimato di andata e ritorno 0,64%.
|
||||||
|
- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −5,1% dopo 30 giorni, −8,0% dopo 90, −14,1% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro.
|
||||||
|
|
||||||
|
## Universo ampio
|
||||||
|
|
||||||
|
Le 10 monete con più scambi, scelte ogni mese tra 47 coppie (anche quelle poi chiuse).
|
||||||
|
|
||||||
|
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `b5f566d59bfa`, dei dati `840015607150`.
|
||||||
|
|
||||||
|
| | Strategia | Comprare e tenere |
|
||||||
|
|---|---:|---:|
|
||||||
|
| Risultato netto | 11.628,28 € | 82.820,55 € |
|
||||||
|
| Rendimento totale | 116,3% | 828,2% |
|
||||||
|
| Rendimento annuo | 10,4% | 32,9% |
|
||||||
|
| Volatilità annua | 14,2% | 74,7% |
|
||||||
|
| Calo massimo | −32,8% (11/2021 → 10/2023) | −85,8% |
|
||||||
|
| Sharpe annuo | 0,77 | 0,76 |
|
||||||
|
| Operazioni chiuse | 1842 | 0 |
|
||||||
|
| Operazioni in guadagno | 13,1% | — |
|
||||||
|
| Rapporto guadagni/perdite | 1,47 | — |
|
||||||
|
| Commissioni pagate | 2.967,95 € | 20,00 € |
|
||||||
|
| Tempo investito | 16,9% | 92,0% |
|
||||||
|
|
||||||
|
**Per anno**
|
||||||
|
|
||||||
|
| Anno | Strategia | Comprare e tenere |
|
||||||
|
|---|---:|---:|
|
||||||
|
| 2019 | 17,0% | 4,8% |
|
||||||
|
| 2020 | 36,2% | 103,2% |
|
||||||
|
| 2021 | 19,8% | 1.603,8% |
|
||||||
|
| 2022 | −11,2% | −79,9% |
|
||||||
|
| 2023 | 12,2% | 56,4% |
|
||||||
|
| 2024 | 26,2% | 33,8% |
|
||||||
|
| 2025 | −7,4% | −32,9% |
|
||||||
|
| 2026 | −2,6% | −9,4% |
|
||||||
|
|
||||||
|
**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)
|
||||||
|
|
||||||
|
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| ×1 | 11.628,28 € | 116,3% | 0,77 | −32,8% | 2.967,95 € |
|
||||||
|
| ×2 | 7.264,22 € | 72,6% | 0,56 | −35,8% | 5.039,47 € |
|
||||||
|
| ×3 | 3.522,91 € | 35,2% | 0,34 | −38,9% | 6.471,34 € |
|
||||||
|
|
||||||
|
**Convalide**
|
||||||
|
|
||||||
|
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 58,4%, Sharpe annuo 0,58.
|
||||||
|
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,77, peggiore 0,77, percorsi positivi 100,0%.
|
||||||
|
- Deflated Sharpe Ratio 0,92, contando 9 varianti provate in tutto.
|
||||||
|
- Probabilità di sovra-adattamento (PBO) 0,09, su 12870 combinazioni di 9 varianti.
|
||||||
|
- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
|
||||||
|
|
||||||
|
**Soglie**
|
||||||
|
|
||||||
|
| Controllo | Valore | Soglia | Esito |
|
||||||
|
|---|---:|---:|---|
|
||||||
|
| Risultato netto con costi doppi | 7.264,22 € | > 0,00 € | superato |
|
||||||
|
| Deflated Sharpe Ratio | 0,924 | ≥ 0,9 | superato |
|
||||||
|
| Probabilità di sovra-adattamento (PBO) | 0,085 | ≤ 0,4 | superato |
|
||||||
|
| Calo massimo | 32,8% | ≤ 25% | **non superato** |
|
||||||
|
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
|
||||||
|
|
||||||
|
**Varianti della griglia**
|
||||||
|
|
||||||
|
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| `coin_vol=10;max_stop=10` | 0,54 | 0,54 | 5.784,07 € | −24,0% | 2269 |
|
||||||
|
| `coin_vol=10;max_stop=15` | 0,86 | 0,66 | 13.191,01 € | −27,8% | 2008 |
|
||||||
|
| `coin_vol=10;max_stop=20` (scelta) | 0,77 | 0,75 | 11.628,28 € | −32,8% | 1842 |
|
||||||
|
| `coin_vol=15;max_stop=10` | 0,39 | 0,39 | 3.932,83 € | −26,3% | 2281 |
|
||||||
|
| `coin_vol=15;max_stop=15` | 0,71 | 0,61 | 10.147,48 € | −31,9% | 2015 |
|
||||||
|
| `coin_vol=15;max_stop=20` | 0,68 | 0,68 | 9.971,55 € | −33,4% | 1853 |
|
||||||
|
| `coin_vol=20;max_stop=10` | 0,35 | 0,35 | 3.437,00 € | −26,8% | 2284 |
|
||||||
|
| `coin_vol=20;max_stop=15` | 0,59 | 0,55 | 7.855,25 € | −33,4% | 2021 |
|
||||||
|
| `coin_vol=20;max_stop=20` | 0,57 | 0,57 | 7.673,22 € | −34,6% | 1856 |
|
||||||
|
|
||||||
|
**Interventi di correttivi e rischio sulla variante scelta**
|
||||||
|
|
||||||
|
Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.
|
||||||
|
|
||||||
|
| Motivo | Volte |
|
||||||
|
|---|---:|
|
||||||
|
| `crypto_regime_below_average` | 3565 |
|
||||||
|
| `risk_reduction` | 1590 |
|
||||||
|
| `crypto_regime_high_volatility` | 151 |
|
||||||
|
| `trade_risk_limit` | 43 |
|
||||||
|
| `switch_tripped` | 34 |
|
||||||
|
| `daily_loss_block` | 14 |
|
||||||
|
| `stop_above_price` | 13 |
|
||||||
|
|
||||||
|
**Note del motore di prova**
|
||||||
|
|
||||||
|
Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.
|
||||||
|
|
||||||
|
| Motivo | Volte |
|
||||||
|
|---|---:|
|
||||||
|
| `residue_written_off` | 1837 |
|
||||||
|
| `below_min_notional` | 449 |
|
||||||
|
|
||||||
|
**Strumenti**
|
||||||
|
|
||||||
|
| Coppia | Prima barra | Ultima barra | Barre |
|
||||||
|
|---|---|---|---:|
|
||||||
|
| ADAEUR | 2018-04-17 | 2026-10-31 | 3120 |
|
||||||
|
| APEEUR | 2022-03-17 | 2026-10-31 | 1690 |
|
||||||
|
| ARBEUR | 2023-03-23 | 2026-10-31 | 1319 |
|
||||||
|
| ATOMEUR | 2019-04-29 | 2026-10-31 | 2743 |
|
||||||
|
| AVAXEUR | 2020-09-22 | 2026-10-31 | 2231 |
|
||||||
|
| BCHABCEUR | 2018-11-16 | 2019-11-28 | 378 |
|
||||||
|
| BCHEUR | 2019-11-28 | 2026-10-31 | 2530 |
|
||||||
|
| BCHSVEUR | 2018-11-16 | 2019-04-22 | 158 |
|
||||||
|
| BNBEUR | 2017-11-06 | 2026-10-31 | 3282 |
|
||||||
|
| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||||
|
| DASHEUR | 2019-03-28 | 2026-10-31 | 2775 |
|
||||||
|
| DOGEEUR | 2019-07-05 | 2026-10-31 | 2676 |
|
||||||
|
| DOTEUR | 2020-08-18 | 2026-10-31 | 2266 |
|
||||||
|
| EOSEUR | 2018-05-28 | 2025-05-26 | 2556 |
|
||||||
|
| ETCEUR | 2018-06-12 | 2026-10-31 | 3064 |
|
||||||
|
| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||||
|
| FILEUR | 2020-10-15 | 2026-10-31 | 2208 |
|
||||||
|
| FTTEUR | 2019-12-20 | 2022-11-15 | 1062 |
|
||||||
|
| GMTEUR | 2022-03-09 | 2026-10-31 | 1698 |
|
||||||
|
| ICXEUR | 2018-06-13 | 2026-09-03 | 3005 |
|
||||||
|
| IOTAEUR | 2018-05-31 | 2026-10-31 | 3076 |
|
||||||
|
| LINKEUR | 2019-01-16 | 2026-10-31 | 2846 |
|
||||||
|
| LTCEUR | 2017-12-13 | 2026-10-31 | 3245 |
|
||||||
|
| LUNAEUR | 2020-08-21 | 2022-05-13 | 631 |
|
||||||
|
| MATICEUR | 2019-04-26 | 2024-09-10 | 1965 |
|
||||||
|
| NEAREUR | 2020-10-14 | 2026-10-31 | 2209 |
|
||||||
|
| NEOEUR | 2017-11-20 | 2026-10-31 | 3268 |
|
||||||
|
| ONTEUR | 2018-06-08 | 2026-10-31 | 3068 |
|
||||||
|
| OPEUR | 2022-06-01 | 2026-10-31 | 1614 |
|
||||||
|
| ORDIEUR | 2023-11-07 | 2026-10-31 | 1090 |
|
||||||
|
| PEPEEUR | 2023-05-05 | 2026-10-31 | 1276 |
|
||||||
|
| POLEUR | 2024-09-13 | 2026-10-31 | 779 |
|
||||||
|
| QTUMEUR | 2018-03-19 | 2026-10-31 | 3149 |
|
||||||
|
| SANDEUR | 2020-08-14 | 2026-10-31 | 2270 |
|
||||||
|
| SHIBEUR | 2021-05-10 | 2026-10-31 | 2001 |
|
||||||
|
| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 |
|
||||||
|
| SUIEUR | 2023-05-03 | 2026-10-31 | 1278 |
|
||||||
|
| TONEUR | 2024-08-08 | 2026-06-30 | 692 |
|
||||||
|
| TRUMPEUR | 2025-01-19 | 2026-10-31 | 651 |
|
||||||
|
| TRXEUR | 2018-06-11 | 2026-10-31 | 3065 |
|
||||||
|
| UNIEUR | 2020-09-17 | 2026-10-31 | 2236 |
|
||||||
|
| VETEUR | 2018-07-25 | 2026-10-31 | 3021 |
|
||||||
|
| WIFEUR | 2024-03-05 | 2026-10-31 | 971 |
|
||||||
|
| XLMEUR | 2018-05-31 | 2026-10-31 | 3076 |
|
||||||
|
| XMREUR | 2019-03-15 | 2024-02-20 | 1804 |
|
||||||
|
| XRPEUR | 2018-05-04 | 2026-10-31 | 3103 |
|
||||||
|
| ZECEUR | 2019-03-21 | 2026-10-31 | 2782 |
|
||||||
|
|
||||||
|
## BTC, ETH e SOL
|
||||||
|
|
||||||
|
Solo le tre coppie in euro con la liquidità migliore.
|
||||||
|
|
||||||
|
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=10` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `1ce210e9cbcb`, dei dati `3b890d6f2ef3`.
|
||||||
|
|
||||||
|
| | Strategia | Comprare e tenere |
|
||||||
|
|---|---:|---:|
|
||||||
|
| Risultato netto | 14.642,97 € | 216.831,80 € |
|
||||||
|
| Rendimento totale | 146,4% | 2.168,3% |
|
||||||
|
| Rendimento annuo | 12,2% | 49,0% |
|
||||||
|
| Volatilità annua | 11,8% | 72,2% |
|
||||||
|
| Calo massimo | −15,0% (11/2021 → 10/2023) | −86,7% |
|
||||||
|
| Sharpe annuo | 1,03 | 0,92 |
|
||||||
|
| Operazioni chiuse | 539 | 0 |
|
||||||
|
| Operazioni in guadagno | 16,7% | — |
|
||||||
|
| Rapporto guadagni/perdite | 1,76 | — |
|
||||||
|
| Commissioni pagate | 2.866,85 € | 20,00 € |
|
||||||
|
| Tempo investito | 12,9% | 95,2% |
|
||||||
|
|
||||||
|
**Per anno**
|
||||||
|
|
||||||
|
| Anno | Strategia | Comprare e tenere |
|
||||||
|
|---|---:|---:|
|
||||||
|
| 2019 | 20,8% | 29,3% |
|
||||||
|
| 2020 | 29,0% | 219,6% |
|
||||||
|
| 2021 | 14,1% | 647,5% |
|
||||||
|
| 2022 | −6,7% | −81,5% |
|
||||||
|
| 2023 | 27,3% | 257,8% |
|
||||||
|
| 2024 | 20,9% | 92,3% |
|
||||||
|
| 2025 | −5,5% | −31,3% |
|
||||||
|
| 2026 | 2,3% | −16,1% |
|
||||||
|
|
||||||
|
**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)
|
||||||
|
|
||||||
|
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| ×1 | 14.642,97 € | 146,4% | 1,03 | −15,0% | 2.866,85 € |
|
||||||
|
| ×2 | 10.274,96 € | 102,7% | 0,82 | −18,9% | 5.161,91 € |
|
||||||
|
| ×3 | 6.273,26 € | 62,7% | 0,59 | −21,3% | 6.782,83 € |
|
||||||
|
|
||||||
|
**Convalide**
|
||||||
|
|
||||||
|
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 82,4%, Sharpe annuo 0,85.
|
||||||
|
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,90, peggiore 0,82, percorsi positivi 100,0%.
|
||||||
|
- Deflated Sharpe Ratio 0,96, contando 18 varianti provate in tutto.
|
||||||
|
- Probabilità di sovra-adattamento (PBO) 0,83, su 12870 combinazioni di 9 varianti.
|
||||||
|
- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
|
||||||
|
|
||||||
|
**Soglie**
|
||||||
|
|
||||||
|
| Controllo | Valore | Soglia | Esito |
|
||||||
|
|---|---:|---:|---|
|
||||||
|
| Risultato netto con costi doppi | 10.274,96 € | > 0,00 € | superato |
|
||||||
|
| Deflated Sharpe Ratio | 0,961 | ≥ 0,9 | superato |
|
||||||
|
| Probabilità di sovra-adattamento (PBO) | 0,835 | ≤ 0,4 | **non superato** |
|
||||||
|
| Calo massimo | 15,0% | ≤ 25% | superato |
|
||||||
|
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
|
||||||
|
|
||||||
|
**Varianti della griglia**
|
||||||
|
|
||||||
|
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| `coin_vol=10;max_stop=10` | 0,98 | 0,95 | 8.962,80 € | −11,2% | 539 |
|
||||||
|
| `coin_vol=10;max_stop=15` | 0,91 | 0,91 | 9.287,93 € | −13,3% | 457 |
|
||||||
|
| `coin_vol=10;max_stop=20` | 0,97 | 0,95 | 10.893,96 € | −13,9% | 393 |
|
||||||
|
| `coin_vol=15;max_stop=10` | 1,00 | 0,97 | 12.333,91 € | −13,5% | 539 |
|
||||||
|
| `coin_vol=15;max_stop=15` | 0,91 | 0,91 | 12.048,69 € | −16,1% | 457 |
|
||||||
|
| `coin_vol=15;max_stop=20` | 0,99 | 0,96 | 14.421,53 € | −16,5% | 393 |
|
||||||
|
| `coin_vol=20;max_stop=10` (scelta) | 1,03 | 0,98 | 14.642,97 € | −15,0% | 539 |
|
||||||
|
| `coin_vol=20;max_stop=15` | 0,97 | 0,97 | 14.521,59 € | −17,1% | 457 |
|
||||||
|
| `coin_vol=20;max_stop=20` | 1,02 | 0,97 | 16.651,30 € | −16,6% | 393 |
|
||||||
|
|
||||||
|
**Interventi di correttivi e rischio sulla variante scelta**
|
||||||
|
|
||||||
|
Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.
|
||||||
|
|
||||||
|
| Motivo | Volte |
|
||||||
|
|---|---:|
|
||||||
|
| `crypto_regime_below_average` | 1104 |
|
||||||
|
| `crypto_regime_high_volatility` | 52 |
|
||||||
|
| `trade_risk_limit` | 41 |
|
||||||
|
| `stop_above_price` | 3 |
|
||||||
|
| `daily_loss_block` | 1 |
|
||||||
|
|
||||||
|
**Note del motore di prova**
|
||||||
|
|
||||||
|
Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.
|
||||||
|
|
||||||
|
| Motivo | Volte |
|
||||||
|
|---|---:|
|
||||||
|
| `residue_written_off` | 539 |
|
||||||
|
| `below_min_notional` | 105 |
|
||||||
|
|
||||||
|
**Strumenti**
|
||||||
|
|
||||||
|
| Coppia | Prima barra | Ultima barra | Barre |
|
||||||
|
|---|---|---|---:|
|
||||||
|
| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||||
|
| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||||
|
| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 |
|
||||||
|
|
||||||
|
## Cosa il backtest non rappresenta
|
||||||
|
|
||||||
|
- I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.
|
||||||
|
- Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.
|
||||||
|
- Sharpe e volatilità sono calcolati senza tasso privo di rischio.
|
||||||
|
- Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il 40% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo.
|
||||||
|
- Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX.
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
{
|
||||||
|
"passed": false,
|
||||||
|
"verdict": "Protocollo non superato. Universo ampio: calo massimo 32,8%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,835, serve \u2264 0,40. Resta in osservazione.",
|
||||||
|
"report": "docs/backtests/crypto_trend.md",
|
||||||
|
"plan_hash": "b5f566d59bfae84f7c0821705d243dc0707803db36f74c1eecd130fb14fed8ed",
|
||||||
|
"parameters": "coin_vol=10;max_stop=20",
|
||||||
|
"max_drawdown": 0.3278,
|
||||||
|
"expected_slippage_bp": 11.94,
|
||||||
|
"round_trip_cost": 0.006388,
|
||||||
|
"expected_path_p5": [
|
||||||
|
-0.01,
|
||||||
|
-0.0144,
|
||||||
|
-0.0179,
|
||||||
|
-0.0199,
|
||||||
|
-0.023,
|
||||||
|
-0.0252,
|
||||||
|
-0.0256,
|
||||||
|
-0.0269,
|
||||||
|
-0.0284,
|
||||||
|
-0.0294,
|
||||||
|
-0.0313,
|
||||||
|
-0.0316,
|
||||||
|
-0.0327,
|
||||||
|
-0.0346,
|
||||||
|
-0.0355,
|
||||||
|
-0.0373,
|
||||||
|
-0.0381,
|
||||||
|
-0.0396,
|
||||||
|
-0.0411,
|
||||||
|
-0.0412,
|
||||||
|
-0.0413,
|
||||||
|
-0.0426,
|
||||||
|
-0.0429,
|
||||||
|
-0.0445,
|
||||||
|
-0.0457,
|
||||||
|
-0.0457,
|
||||||
|
-0.0468,
|
||||||
|
-0.0481,
|
||||||
|
-0.0499,
|
||||||
|
-0.0512,
|
||||||
|
-0.0507,
|
||||||
|
-0.0519,
|
||||||
|
-0.0538,
|
||||||
|
-0.0548,
|
||||||
|
-0.0558,
|
||||||
|
-0.0566,
|
||||||
|
-0.0582,
|
||||||
|
-0.0585,
|
||||||
|
-0.0583,
|
||||||
|
-0.0594,
|
||||||
|
-0.0599,
|
||||||
|
-0.06,
|
||||||
|
-0.06,
|
||||||
|
-0.0616,
|
||||||
|
-0.0619,
|
||||||
|
-0.0619,
|
||||||
|
-0.061,
|
||||||
|
-0.0626,
|
||||||
|
-0.0634,
|
||||||
|
-0.0655,
|
||||||
|
-0.0646,
|
||||||
|
-0.0651,
|
||||||
|
-0.0674,
|
||||||
|
-0.0681,
|
||||||
|
-0.0683,
|
||||||
|
-0.0678,
|
||||||
|
-0.0684,
|
||||||
|
-0.0691,
|
||||||
|
-0.0705,
|
||||||
|
-0.0724,
|
||||||
|
-0.0733,
|
||||||
|
-0.0725,
|
||||||
|
-0.0736,
|
||||||
|
-0.0737,
|
||||||
|
-0.0746,
|
||||||
|
-0.0729,
|
||||||
|
-0.074,
|
||||||
|
-0.0737,
|
||||||
|
-0.0744,
|
||||||
|
-0.0739,
|
||||||
|
-0.0751,
|
||||||
|
-0.0742,
|
||||||
|
-0.0749,
|
||||||
|
-0.076,
|
||||||
|
-0.0754,
|
||||||
|
-0.0755,
|
||||||
|
-0.0757,
|
||||||
|
-0.0774,
|
||||||
|
-0.0781,
|
||||||
|
-0.0782,
|
||||||
|
-0.0776,
|
||||||
|
-0.0791,
|
||||||
|
-0.0786,
|
||||||
|
-0.0785,
|
||||||
|
-0.0781,
|
||||||
|
-0.0785,
|
||||||
|
-0.0789,
|
||||||
|
-0.0788,
|
||||||
|
-0.0806,
|
||||||
|
-0.0802,
|
||||||
|
-0.0802,
|
||||||
|
-0.0802,
|
||||||
|
-0.0813,
|
||||||
|
-0.0826,
|
||||||
|
-0.0842,
|
||||||
|
-0.0841,
|
||||||
|
-0.087,
|
||||||
|
-0.0859,
|
||||||
|
-0.0855,
|
||||||
|
-0.0868,
|
||||||
|
-0.0868,
|
||||||
|
-0.0875,
|
||||||
|
-0.0872,
|
||||||
|
-0.0872,
|
||||||
|
-0.0876,
|
||||||
|
-0.0868,
|
||||||
|
-0.0866,
|
||||||
|
-0.0865,
|
||||||
|
-0.0867,
|
||||||
|
-0.0875,
|
||||||
|
-0.0877,
|
||||||
|
-0.0884,
|
||||||
|
-0.0882,
|
||||||
|
-0.0887,
|
||||||
|
-0.0882,
|
||||||
|
-0.0888,
|
||||||
|
-0.0895,
|
||||||
|
-0.0912,
|
||||||
|
-0.0919,
|
||||||
|
-0.0915,
|
||||||
|
-0.0929,
|
||||||
|
-0.0933,
|
||||||
|
-0.0938,
|
||||||
|
-0.0941,
|
||||||
|
-0.0943,
|
||||||
|
-0.0957,
|
||||||
|
-0.096,
|
||||||
|
-0.0957,
|
||||||
|
-0.0958,
|
||||||
|
-0.0957,
|
||||||
|
-0.0973,
|
||||||
|
-0.0965,
|
||||||
|
-0.0957,
|
||||||
|
-0.0941,
|
||||||
|
-0.0956,
|
||||||
|
-0.0958,
|
||||||
|
-0.0969,
|
||||||
|
-0.0992,
|
||||||
|
-0.0988,
|
||||||
|
-0.0996,
|
||||||
|
-0.1003,
|
||||||
|
-0.0996,
|
||||||
|
-0.101,
|
||||||
|
-0.1006,
|
||||||
|
-0.1041,
|
||||||
|
-0.1051,
|
||||||
|
-0.1045,
|
||||||
|
-0.1032,
|
||||||
|
-0.1035,
|
||||||
|
-0.1038,
|
||||||
|
-0.1048,
|
||||||
|
-0.1045,
|
||||||
|
-0.1067,
|
||||||
|
-0.1051,
|
||||||
|
-0.1065,
|
||||||
|
-0.1061,
|
||||||
|
-0.1062,
|
||||||
|
-0.1082,
|
||||||
|
-0.1073,
|
||||||
|
-0.1078,
|
||||||
|
-0.1088,
|
||||||
|
-0.109,
|
||||||
|
-0.1097,
|
||||||
|
-0.1116,
|
||||||
|
-0.1089,
|
||||||
|
-0.1105,
|
||||||
|
-0.1103,
|
||||||
|
-0.1083,
|
||||||
|
-0.1116,
|
||||||
|
-0.1108,
|
||||||
|
-0.1116,
|
||||||
|
-0.1132,
|
||||||
|
-0.1133,
|
||||||
|
-0.1131,
|
||||||
|
-0.1132,
|
||||||
|
-0.114,
|
||||||
|
-0.1141,
|
||||||
|
-0.1144,
|
||||||
|
-0.1159,
|
||||||
|
-0.116,
|
||||||
|
-0.1165,
|
||||||
|
-0.1157,
|
||||||
|
-0.1165,
|
||||||
|
-0.1191,
|
||||||
|
-0.1195,
|
||||||
|
-0.1198,
|
||||||
|
-0.1205,
|
||||||
|
-0.12,
|
||||||
|
-0.1216,
|
||||||
|
-0.1213,
|
||||||
|
-0.1219,
|
||||||
|
-0.1204,
|
||||||
|
-0.12,
|
||||||
|
-0.1217,
|
||||||
|
-0.1194,
|
||||||
|
-0.1206,
|
||||||
|
-0.1194,
|
||||||
|
-0.1184,
|
||||||
|
-0.1195,
|
||||||
|
-0.119,
|
||||||
|
-0.1195,
|
||||||
|
-0.1201,
|
||||||
|
-0.121,
|
||||||
|
-0.1206,
|
||||||
|
-0.1195,
|
||||||
|
-0.1217,
|
||||||
|
-0.1212,
|
||||||
|
-0.1204,
|
||||||
|
-0.1217,
|
||||||
|
-0.1229,
|
||||||
|
-0.124,
|
||||||
|
-0.1231,
|
||||||
|
-0.1232,
|
||||||
|
-0.1247,
|
||||||
|
-0.1256,
|
||||||
|
-0.1277,
|
||||||
|
-0.1286,
|
||||||
|
-0.1292,
|
||||||
|
-0.1271,
|
||||||
|
-0.1276,
|
||||||
|
-0.1301,
|
||||||
|
-0.1289,
|
||||||
|
-0.1273,
|
||||||
|
-0.1289,
|
||||||
|
-0.1285,
|
||||||
|
-0.1272,
|
||||||
|
-0.1265,
|
||||||
|
-0.1257,
|
||||||
|
-0.1273,
|
||||||
|
-0.127,
|
||||||
|
-0.1244,
|
||||||
|
-0.1244,
|
||||||
|
-0.125,
|
||||||
|
-0.126,
|
||||||
|
-0.1261,
|
||||||
|
-0.1262,
|
||||||
|
-0.1249,
|
||||||
|
-0.1243,
|
||||||
|
-0.1255,
|
||||||
|
-0.1267,
|
||||||
|
-0.1269,
|
||||||
|
-0.1283,
|
||||||
|
-0.1288,
|
||||||
|
-0.1296,
|
||||||
|
-0.1314,
|
||||||
|
-0.1302,
|
||||||
|
-0.1313,
|
||||||
|
-0.1311,
|
||||||
|
-0.1322,
|
||||||
|
-0.1315,
|
||||||
|
-0.1337,
|
||||||
|
-0.1319,
|
||||||
|
-0.1309,
|
||||||
|
-0.1341,
|
||||||
|
-0.1328,
|
||||||
|
-0.1323,
|
||||||
|
-0.1346,
|
||||||
|
-0.1315,
|
||||||
|
-0.1328,
|
||||||
|
-0.1353,
|
||||||
|
-0.1347,
|
||||||
|
-0.1338,
|
||||||
|
-0.1365,
|
||||||
|
-0.1356,
|
||||||
|
-0.1338,
|
||||||
|
-0.1346,
|
||||||
|
-0.1343,
|
||||||
|
-0.134,
|
||||||
|
-0.1345,
|
||||||
|
-0.1331,
|
||||||
|
-0.1332,
|
||||||
|
-0.1347,
|
||||||
|
-0.1339,
|
||||||
|
-0.136,
|
||||||
|
-0.1347,
|
||||||
|
-0.1348,
|
||||||
|
-0.1368,
|
||||||
|
-0.136,
|
||||||
|
-0.1356,
|
||||||
|
-0.1313,
|
||||||
|
-0.1334,
|
||||||
|
-0.134,
|
||||||
|
-0.1349,
|
||||||
|
-0.1341,
|
||||||
|
-0.1342,
|
||||||
|
-0.1341,
|
||||||
|
-0.135,
|
||||||
|
-0.1353,
|
||||||
|
-0.1319,
|
||||||
|
-0.1345,
|
||||||
|
-0.137,
|
||||||
|
-0.1358,
|
||||||
|
-0.1369,
|
||||||
|
-0.1368,
|
||||||
|
-0.1372,
|
||||||
|
-0.1347,
|
||||||
|
-0.1376,
|
||||||
|
-0.1345,
|
||||||
|
-0.1346,
|
||||||
|
-0.1343,
|
||||||
|
-0.1344,
|
||||||
|
-0.132,
|
||||||
|
-0.1331,
|
||||||
|
-0.133,
|
||||||
|
-0.1345,
|
||||||
|
-0.1347,
|
||||||
|
-0.1355,
|
||||||
|
-0.1349,
|
||||||
|
-0.1346,
|
||||||
|
-0.1341,
|
||||||
|
-0.1339,
|
||||||
|
-0.1334,
|
||||||
|
-0.1326,
|
||||||
|
-0.1343,
|
||||||
|
-0.134,
|
||||||
|
-0.1342,
|
||||||
|
-0.1351,
|
||||||
|
-0.135,
|
||||||
|
-0.1352,
|
||||||
|
-0.1353,
|
||||||
|
-0.1382,
|
||||||
|
-0.1366,
|
||||||
|
-0.1363,
|
||||||
|
-0.1368,
|
||||||
|
-0.1354,
|
||||||
|
-0.1352,
|
||||||
|
-0.1383,
|
||||||
|
-0.1382,
|
||||||
|
-0.1356,
|
||||||
|
-0.1354,
|
||||||
|
-0.1349,
|
||||||
|
-0.1379,
|
||||||
|
-0.1382,
|
||||||
|
-0.1364,
|
||||||
|
-0.1364,
|
||||||
|
-0.1348,
|
||||||
|
-0.1345,
|
||||||
|
-0.1346,
|
||||||
|
-0.1353,
|
||||||
|
-0.1342,
|
||||||
|
-0.1372,
|
||||||
|
-0.1386,
|
||||||
|
-0.1385,
|
||||||
|
-0.1388,
|
||||||
|
-0.1402,
|
||||||
|
-0.1399,
|
||||||
|
-0.1397,
|
||||||
|
-0.1397,
|
||||||
|
-0.1401,
|
||||||
|
-0.1393,
|
||||||
|
-0.1394,
|
||||||
|
-0.1417,
|
||||||
|
-0.1402,
|
||||||
|
-0.1399,
|
||||||
|
-0.1409,
|
||||||
|
-0.1417,
|
||||||
|
-0.1404,
|
||||||
|
-0.1408,
|
||||||
|
-0.1418,
|
||||||
|
-0.1422,
|
||||||
|
-0.1423,
|
||||||
|
-0.1444,
|
||||||
|
-0.1423,
|
||||||
|
-0.1399,
|
||||||
|
-0.1405
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Backtest di `equity_meanrev` (Ritorno alla media azioni)
|
||||||
|
|
||||||
|
**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.
|
||||||
|
|
||||||
|
Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.
|
||||||
|
|
||||||
|
Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.
|
||||||
|
|
||||||
|
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"passed": false,
|
||||||
|
"verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.",
|
||||||
|
"report": "docs/backtests/equity_meanrev.md",
|
||||||
|
"max_drawdown": 0,
|
||||||
|
"expected_slippage_bp": 0,
|
||||||
|
"round_trip_cost": 0,
|
||||||
|
"expected_path_p5": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Backtest di `equity_momentum` (Momentum azioni)
|
||||||
|
|
||||||
|
**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.
|
||||||
|
|
||||||
|
Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.
|
||||||
|
|
||||||
|
Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.
|
||||||
|
|
||||||
|
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"passed": false,
|
||||||
|
"verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.",
|
||||||
|
"report": "docs/backtests/equity_momentum.md",
|
||||||
|
"max_drawdown": 0,
|
||||||
|
"expected_slippage_bp": 0,
|
||||||
|
"round_trip_cost": 0,
|
||||||
|
"expected_path_p5": []
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"Through":"2026-10-31","BaseRates":{"crypto_trend":0.18329718004338394},"Model":{"Clues":["strength","stop_distance","volatility","volatility_ratio","volume","market_trend","market_volatility","breadth","weekday_sin","weekday_cos"],"Learned":{"Learner":"logistic","Linear":{"Intercept":-1.5574604345197345,"Weights":[0.1590340105154227,0.11908779476819635,-0.162432512465705,-0.08003982796993969,-0.19132480071600444,0.3022103731539277,0.10780995530583182,-0.23941305842109442,-0.22326128923555164,-0.15096635705365147],"Means":[0.19601108548807236,0.050460482868763604,0.8833982208676783,0.9192900882537972,0.9662490365618214,0.0835851831670285,0.5876342481616039,0.476247288508679,0.08773042725596508,-0.05221374460412148],"Scales":[0.165485155045225,0.04067752287292153,0.4848501513845519,0.310638619072209,1.0200137514523773,0.33648118132548555,0.2603576946488006,0.34682317518394806,0.7017578634342959,0.70506240583181]},"Trees":null},"Calibration":{"Kind":"isotonic","Slope":1,"Offset":0,"Scores":[-2.31013942719076,-1.9151100659396874,-1.7663451007315563,-1.7294273092893189,-1.6834534361695037,-1.279712934228674],"Values":[0.11555555555555555,0.125,0.14736842105263157,0.15384615384615385,0.16393442622950818,0.23052959501557632]},"Ranges":{"strength":{"Low":0.11111111,"High":1,"Cases":1844},"stop_distance":{"Low":0.00554256,"High":0.2,"Cases":1844},"volatility":{"Low":0.22509683,"High":2.6730656,"Cases":1844},"volatility_ratio":{"Low":0.33680145,"High":1.81238384,"Cases":1844},"volume":{"Low":0.31563245,"High":3.85783042,"Cases":1844},"market_trend":{"Low":-0.42829195,"High":1.23482451,"Cases":1844},"market_volatility":{"Low":0.25961056,"High":1.79265636,"Cases":1844},"breadth":{"Low":0,"High":1,"Cases":1844},"weekday_sin":{"Low":-0.97492791,"High":0.97492791,"Cases":1844},"weekday_cos":{"Low":-0.90096887,"High":1,"Cases":1844}},"Strategies":["crypto_trend"]},"Report":{"Examples":1844,"Live":0,"ByStrategy":{"crypto_trend":1844},"BaseRates":{"crypto_trend":0.18329718004338394},"FirstDay":"2019-01-01","LastDay":"2026-10-28","Attempts":[{"Learner":"boosting","Forward":{"Cases":1107,"LogLoss":0.4901472349109493,"BaseLogLoss":0.47884194965218496,"Brier":0.15371685226409482,"Precision":0.507289937506103,"GainWithout":1.7619015934416593,"GainWith":1.4133353140068803,"Improvement":-0.348566279434779,"CalibrationError":0.045766180646463546,"Bands":[{"From":0.05,"To":0.1,"Cases":27,"Estimated":0.08513321633688159,"Observed":0.33327967159013155},{"From":0.1,"To":0.15,"Cases":76,"Estimated":0.1205846499171033,"Observed":0.2692438228736069},{"From":0.15,"To":0.2,"Cases":602,"Estimated":0.17613223786197266,"Observed":0.1707911333371173},{"From":0.2,"To":0.25,"Cases":261,"Estimated":0.2227211085612617,"Observed":0.14663644573512966},{"From":0.25,"To":0.3,"Cases":70,"Estimated":0.2646022340952087,"Observed":0.21307426019867914},{"From":0.3,"To":0.35,"Cases":38,"Estimated":0.3291545441015799,"Observed":0.21140647874817575},{"From":0.35,"To":0.4,"Cases":16,"Estimated":0.37353561368298727,"Observed":0.35049852907302864},{"From":0.4,"To":0.45,"Cases":12,"Estimated":0.42519433372299786,"Observed":0.283533030708765},{"From":0.45,"To":0.5,"Cases":5,"Estimated":0.4714069044078384,"Observed":0}]},"Combined":{"Cases":9220,"LogLoss":0.4837238568877384,"BaseLogLoss":0.4806696575091626,"Brier":0.15185458964467266,"Precision":0.5204232380144118,"GainWithout":1.6880808292523108,"GainWith":1.6364813104483271,"Improvement":-0.051599518803983724,"CalibrationError":0.03014685726947035,"Bands":[{"From":0,"To":0.05,"Cases":1,"Estimated":0.046564955701587085,"Observed":0.3333333333333333},{"From":0.05,"To":0.1,"Cases":46,"Estimated":0.07881756467240499,"Observed":0.15789473684210525},{"From":0.1,"To":0.15,"Cases":354,"Estimated":0.13721738144360052,"Observed":0.18972332015810275},{"From":0.15,"To":0.2,"Cases":887,"Estimated":0.17631601405250116,"Observed":0.18241262683201803},{"From":0.2,"To":0.25,"Cases":389,"Estimated":0.214237231909851,"Observed":0.19023136246786632},{"From":0.25,"To":0.3,"Cases":136,"Estimated":0.26749199949900143,"Observed":0.15905743740795286},{"From":0.3,"To":0.35,"Cases":31,"Estimated":0.30986280783768577,"Observed":0.1858974358974359},{"From":0.35,"To":0.4,"Cases":1,"Estimated":0.3668701553971652,"Observed":0.3333333333333333}]},"Chosen":false},{"Learner":"logistic","Forward":{"Cases":1107,"LogLoss":0.4735156194734787,"BaseLogLoss":0.47884194965218496,"Brier":0.14890023945017386,"Precision":0.5457932574943853,"GainWithout":1.7619015934416593,"GainWith":1.8120652589010067,"Improvement":0.05016366545934736,"CalibrationError":0.017426102268308204,"Bands":[{"From":0.05,"To":0.1,"Cases":2,"Estimated":0.0909525554691676,"Observed":0},{"From":0.1,"To":0.15,"Cases":101,"Estimated":0.140951208737604,"Observed":0.16040173361620094},{"From":0.15,"To":0.2,"Cases":520,"Estimated":0.1790306767513123,"Observed":0.1688945041903547},{"From":0.2,"To":0.25,"Cases":452,"Estimated":0.21795407082480758,"Observed":0.19599570984164852},{"From":0.25,"Line truncated
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Primo modello: rapporto di convalida
|
||||||
|
|
||||||
|
Generato con `anubis learning base --to 2026-10-31` sullo storico fino al 31/10/2026. Gli stessi dati danno sempre lo stesso modello.
|
||||||
|
|
||||||
|
## La domanda
|
||||||
|
|
||||||
|
Il modello non prevede i prezzi. Guarda un segnale di una strategia e stima quanto è probabile che l'operazione chiuda in guadagno, al netto dei costi. Può solo rimpicciolire l'operazione.
|
||||||
|
|
||||||
|
## Gli esempi
|
||||||
|
|
||||||
|
1848 esempi ricostruiti facendo girare le strategie sullo storico: 1844 con un esito, 4 con l'operazione ancora aperta, 0 mai partiti (sotto il minimo).
|
||||||
|
|
||||||
|
| Strategia | Esempi con esito | Dal | Al | In guadagno (frequenza di base) | Risultato medio dell'operazione |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| crypto_trend | 1844 | 01/01/2019 | 28/10/2026 | 18,3% | +0,8% |
|
||||||
|
| equity_momentum | 0 | | | nessuna: aspetta lo storico di Alpaca | |
|
||||||
|
| equity_meanrev | 0 | | | nessuna: aspetta lo storico di Alpaca | |
|
||||||
|
|
||||||
|
Una strategia senza frequenza di base non viene stimata: il modello lascia le sue operazioni come sono.
|
||||||
|
|
||||||
|
## La convalida
|
||||||
|
|
||||||
|
Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si studia il passato e si verifica il periodo dopo, 5 volte. «A combinazioni»: 15 combinazioni di 6 periodi, togliendo dallo studio ogni esempio che si sovrappone nel tempo a quelli di verifica, più 10 giorni di distacco.
|
||||||
|
|
||||||
|
| Modello | Prova | Casi | Errore (log-loss) | Di chi risponde sempre la frequenza di base | Errore sulle probabilità (Brier) | Previsioni azzeccate | Guadagno medio per operazione proposta, senza filtro | con il filtro |
|
||||||
|
|---|---|---|---|---|---|---|---|---|
|
||||||
|
| Alberi potenziati | in avanti | 1107 | 0,4901 | 0,4788 | 0,1537 | 50,7% | +1,76 € | +1,41 € |
|
||||||
|
| Alberi potenziati | a combinazioni | 9220 | 0,4837 | 0,4807 | 0,1519 | 52,0% | +1,69 € | +1,64 € |
|
||||||
|
| Regressione logistica (scelto) | in avanti | 1107 | 0,4735 | 0,4788 | 0,1489 | 54,6% | +1,76 € | +1,81 € |
|
||||||
|
| Regressione logistica (scelto) | a combinazioni | 9220 | 0,4796 | 0,4807 | 0,1506 | 56,0% | +1,69 € | +1,76 € |
|
||||||
|
| Foresta casuale | in avanti | 1107 | 0,4819 | 0,4788 | 0,1512 | 50,7% | +1,76 € | +1,69 € |
|
||||||
|
| Foresta casuale | a combinazioni | 9220 | 0,4821 | 0,4807 | 0,1513 | 52,6% | +1,69 € | +1,64 € |
|
||||||
|
|
||||||
|
Il guadagno è calcolato sul capitale di riferimento (10.000 € in tutto, quote predefinite). Nelle combinazioni ogni caso è verificato più volte.
|
||||||
|
|
||||||
|
**Scelta.** Regressione logistica: il miglior guadagno medio per operazione proposta su esempi mai visti. La regola era fissata prima di guardare i numeri (ADR 0018).
|
||||||
|
|
||||||
|
**Lettura onesta.** Le stime sono migliori di chi risponde sempre la frequenza di base in tutte e due le prove, ma di poco: errore più basso, 0,2% in meno nelle combinazioni e 1,1% in meno in avanti. Con il filtro il guadagno medio per operazione proposta cambia di +0,07 € nelle combinazioni e di +0,05 € in avanti.
|
||||||
|
|
||||||
|
## Cosa guarda di più
|
||||||
|
|
||||||
|
| Indizio | Peso su 100 |
|
||||||
|
|---|---|
|
||||||
|
| Giorno della settimana | 34 |
|
||||||
|
| Forza della tendenza | 30 |
|
||||||
|
| Agitazione recente dei prezzi | 19 |
|
||||||
|
| Quota di titoli in salita | 12 |
|
||||||
|
| Fase generale del mercato | 5 |
|
||||||
|
| Distanza dallo stop | 0 |
|
||||||
|
| Volumi scambiati | 0 |
|
||||||
|
|
||||||
|
Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizio. Con tutti i pesi a zero nessun indizio aiuta.
|
||||||
|
|
||||||
|
## Ci si può fidare delle probabilità?
|
||||||
|
|
||||||
|
Verifica a combinazioni, fasce da 5 punti; un esempio verificato più volte conta come un caso. Contano le fasce con almeno 20 casi; errore medio 2,2 punti.
|
||||||
|
|
||||||
|
| Stima | Casi | Stimato in media | Andate bene |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 0–5% | 12 | 4,6% | 19,0% |
|
||||||
|
| 5–10% | 38 | 8,1% | 16,9% |
|
||||||
|
| 10–15% | 377 | 13,3% | 14,6% |
|
||||||
|
| 15–20% | 837 | 17,7% | 19,1% |
|
||||||
|
| 20–25% | 395 | 21,7% | 20,6% |
|
||||||
|
| 25–30% | 167 | 26,9% | 17,7% |
|
||||||
|
| 30–35% | 13 | 31,8% | 18,2% |
|
||||||
|
| 35–40% | 5 | 35,9% | 26,9% |
|
||||||
|
|
||||||
|
## Cosa succede adesso
|
||||||
|
|
||||||
|
Il modello parte in osservazione: stima ogni segnale e non cambia nessuna operazione. Comincerà a contare solo dopo almeno 300 segnali dal vivo, con probabilità ben tarate e un miglioramento distinguibile dal caso (SPEC 11.5).
|
||||||
@@ -2,8 +2,125 @@
|
|||||||
"version": 2,
|
"version": 2,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"net10.0-windows7.0": {
|
"net10.0-windows7.0": {
|
||||||
|
"Google.Protobuf": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "3.30.2",
|
||||||
|
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||||
|
},
|
||||||
|
"Microsoft.Data.Sqlite.Core": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||||
|
"dependencies": {
|
||||||
|
"SQLitePCLRaw.core": "2.1.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||||
|
"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==",
|
||||||
|
"dependencies": {
|
||||||
|
"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",
|
||||||
|
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||||
|
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.core": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"SQLitePCLRaw.core": "2.1.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"System.Numerics.Tensors": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||||
|
},
|
||||||
"anubis": {
|
"anubis": {
|
||||||
"type": "Project"
|
"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, )"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Data.Sqlite": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[10.0.14, )",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||||
|
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"System.Security.Cryptography.ProtectedData": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[10.0.14, )",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
<RootNamespace>Anubis.Guard</RootNamespace>
|
<RootNamespace>Anubis.Guard</RootNamespace>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<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" />
|
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,3 +1,49 @@
|
|||||||
// Placeholder: the guard process (SPEC 9.3) arrives in phase 6 (ADR 0003).
|
using System.Collections;
|
||||||
await Console.Error.WriteLineAsync("Anubis.Guard non è ancora disponibile: arriva nella Fase 6.").ConfigureAwait(false);
|
using System.Runtime.InteropServices;
|
||||||
return 2;
|
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,8 +2,109 @@
|
|||||||
"version": 2,
|
"version": 2,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"net10.0": {
|
"net10.0": {
|
||||||
|
"Google.Protobuf": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "3.30.2",
|
||||||
|
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
|
||||||
|
},
|
||||||
|
"Microsoft.Data.Sqlite.Core": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||||
|
"dependencies": {
|
||||||
|
"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",
|
||||||
|
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||||
|
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.core": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||||
|
},
|
||||||
|
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.13",
|
||||||
|
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"SQLitePCLRaw.core": "2.1.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"System.Numerics.Tensors": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
|
||||||
|
},
|
||||||
"anubis": {
|
"anubis": {
|
||||||
"type": "Project"
|
"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, )"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Data.Sqlite": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[10.0.14, )",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||||
|
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||||
|
"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=="
|
||||||
|
},
|
||||||
|
"System.Security.Cryptography.ProtectedData": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[10.0.14, )",
|
||||||
|
"resolved": "10.0.14",
|
||||||
|
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>One account of the Conti screen, in its own currency and in euro.</summary>
|
||||||
|
internal sealed record AccountCard(Guid Id, string Name, string Broker, string Environment, string Currency, decimal Cash, decimal Invested, decimal InvestedEur, int Holdings,
|
||||||
|
decimal Realized, decimal Unrealized, decimal Fees, decimal Flows, AccountState State, decimal Rate)
|
||||||
|
{
|
||||||
|
/// <summary>Cash plus the positions, each valued to the cent as the table shows it, so the figures add up on screen.</summary>
|
||||||
|
public decimal Equity => Cash + Invested;
|
||||||
|
|
||||||
|
public string Kind => Broker == Venues.Alpaca ? "Azioni USA" : "Crypto";
|
||||||
|
|
||||||
|
public string Short => Broker == Venues.Alpaca ? "Alpaca" : "OKX";
|
||||||
|
|
||||||
|
public decimal Result => Equity - Flows;
|
||||||
|
|
||||||
|
public decimal Percent => Flows > 0m ? Result / Flows * 100m : 0m;
|
||||||
|
|
||||||
|
/// <summary>An amount of this account in euro, at the latest rate.</summary>
|
||||||
|
public decimal Eur(decimal amount) => Currency == "EUR" || Rate <= 0m ? amount : amount / Rate;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record PositionRow(Guid AccountId, string Broker, string Symbol, string Name, string Strategy, decimal Quantity, decimal Average, decimal Last, decimal? Stop,
|
||||||
|
string Currency, DateTimeOffset OpenedAt, decimal ValueEur, decimal ResultEur)
|
||||||
|
{
|
||||||
|
public decimal Percent => Average == 0m ? 0m : (Last / Average - 1m) * 100m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A line of "Ordini in attesa": one order, or the stops of Alpaca grouped by validity.</summary>
|
||||||
|
internal sealed record PendingRow(string Action, string Subject, string Where, string Level, string Status, bool Waiting);
|
||||||
|
|
||||||
|
internal sealed record ResidueRow(string Broker, string Symbol, decimal Quantity, decimal Value, string Currency, DateTimeOffset At);
|
||||||
|
|
||||||
|
internal sealed record StrategySlice(string Label, string Color, decimal Eur);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Conti e posizioni screen (SPEC 13.6, mockup 02): totals, accounts with key and reconciliation, open positions,
|
||||||
|
/// pending orders, residues and where the money is by currency. One world only: real accounts when there are any,
|
||||||
|
/// otherwise the simulated ones, so finto and vero never add up (SPEC 7.1).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record AccountsView(
|
||||||
|
IReadOnlyList<AccountCard> Accounts,
|
||||||
|
IReadOnlyList<PositionRow> Positions,
|
||||||
|
IReadOnlyList<PendingRow> Pending,
|
||||||
|
int PendingOthers,
|
||||||
|
bool AlpacaStops,
|
||||||
|
IReadOnlyList<ResidueRow> Residues,
|
||||||
|
IReadOnlyList<StrategySlice> Slices,
|
||||||
|
decimal? UsdRate,
|
||||||
|
DateOnly? RateDay,
|
||||||
|
decimal? FxEffect,
|
||||||
|
bool MarketOpen,
|
||||||
|
DateTimeOffset MarketNext)
|
||||||
|
{
|
||||||
|
public bool HasAccounts => Accounts.Count > 0;
|
||||||
|
|
||||||
|
public decimal TotalEur => Accounts.Sum(a => a.Eur(a.Equity));
|
||||||
|
|
||||||
|
public decimal CashEur => Accounts.Sum(a => a.Eur(a.Cash));
|
||||||
|
|
||||||
|
public decimal InvestedEur => Accounts.Sum(a => a.InvestedEur);
|
||||||
|
|
||||||
|
public decimal ResultEur => Accounts.Sum(a => a.Eur(a.Result));
|
||||||
|
|
||||||
|
public decimal OpenResultEur => Positions.Sum(p => p.ResultEur);
|
||||||
|
|
||||||
|
public static async Task<AccountsView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(services);
|
||||||
|
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
|
||||||
|
var reconciler = services.Trading?.Reconciler ?? new Reconciler(services.Db, clock, ledger);
|
||||||
|
var fx = await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false);
|
||||||
|
var rate = fx?.Rate ?? 0m;
|
||||||
|
|
||||||
|
var (accounts, instruments, trades, orders, residues) = await services.Db.ReadAsync(async s =>
|
||||||
|
{
|
||||||
|
var a = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY broker DESC, created_at",
|
||||||
|
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false);
|
||||||
|
var i = await s.QueryAsync("SELECT id, symbol, name, quote_currency FROM instruments",
|
||||||
|
r => (Id: r.Id("id"), Symbol: r.Text("symbol"), Name: r.TextOrNull("name"), Quote: r.TextOrNull("quote_currency"))).ConfigureAwait(false);
|
||||||
|
var t = await s.QueryAsync("SELECT account_id, realized, fees FROM trades", r => (Account: r.Id("account_id"), Realized: r.Money("realized"), Fees: r.Money("fees")))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var o = await s.QueryAsync(
|
||||||
|
"SELECT account_id, instrument_id, side, order_type, purpose, quantity, filled_quantity, limit_price, stop_price, time_in_force, step, created_at, updated_at FROM orders " +
|
||||||
|
"WHERE status IN ('created', 'submitted', 'partially_filled') ORDER BY created_at, id",
|
||||||
|
r => new OpenOrder(r.Id("account_id"), r.Id("instrument_id"), r.Text("side"), r.Text("order_type"), r.TextOrNull("purpose") ?? "entry", r.Money("quantity"),
|
||||||
|
r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.TextOrNull("time_in_force") ?? "day",
|
||||||
|
r.IsNull("step") ? null : (int)r.Number("step"), r.Moment("created_at"), r.Moment("updated_at"))).ConfigureAwait(false);
|
||||||
|
var res = await s.QueryAsync("SELECT account_id, instrument_id, quantity, value, currency, created_at FROM residues ORDER BY created_at DESC",
|
||||||
|
r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Quantity: r.Money("quantity"), Value: r.Money("value"), Currency: r.Text("currency"),
|
||||||
|
At: r.Moment("created_at"))).ConfigureAwait(false);
|
||||||
|
return (a, i.ToDictionary(x => x.Id), t, o, res);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
|
||||||
|
accounts = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToList();
|
||||||
|
var shown = accounts.Select(a => a.Id).ToHashSet();
|
||||||
|
var equities = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => shown.Contains(e.AccountId)).ToList();
|
||||||
|
var positions = (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Where(p => shown.Contains(p.AccountId)).ToList();
|
||||||
|
|
||||||
|
var rates = accounts.ToDictionary(a => a.Id, a => a.Currency == "USD" ? rate : 1m);
|
||||||
|
decimal Eur(Guid account, decimal amount) => rates[account] is var r && r > 0m && r != 1m ? amount / r : amount;
|
||||||
|
var currencies = accounts.ToDictionary(a => a.Id, a => a.Currency);
|
||||||
|
var rows = positions
|
||||||
|
.Select(p =>
|
||||||
|
{
|
||||||
|
var instrument = instruments.GetValueOrDefault(p.InstrumentId);
|
||||||
|
var value = Math.Round(p.Value, 2, MidpointRounding.AwayFromZero);
|
||||||
|
return (Native: value, Row: new PositionRow(p.AccountId, accounts.First(a => a.Id == p.AccountId).Broker, instrument.Symbol ?? "?", instrument.Name ?? "", p.Strategy,
|
||||||
|
p.Quantity, p.AveragePrice, p.LastPrice ?? p.AveragePrice, p.StopPrice, instrument.Quote ?? currencies[p.AccountId], p.OpenedAt,
|
||||||
|
Math.Round(Eur(p.AccountId, value), 2, MidpointRounding.AwayFromZero), Math.Round(Eur(p.AccountId, p.Unrealized), 2, MidpointRounding.AwayFromZero)));
|
||||||
|
})
|
||||||
|
.OrderByDescending(r => r.Row.ValueEur)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var cards = new List<AccountCard>();
|
||||||
|
foreach (var a in accounts)
|
||||||
|
{
|
||||||
|
var mine = equities.Where(e => e.AccountId == a.Id).ToList();
|
||||||
|
var held = positions.Where(p => p.AccountId == a.Id).ToList();
|
||||||
|
var valued = rows.Where(r => r.Row.AccountId == a.Id).ToList();
|
||||||
|
var state = await reconciler.StateAsync(a.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
cards.Add(new AccountCard(a.Id, a.Name, a.Broker, a.Environment, a.Currency, mine.Sum(e => e.Cash), valued.Sum(r => r.Native), valued.Sum(r => r.Row.ValueEur),
|
||||||
|
held.Select(p => p.InstrumentId).Distinct().Count(), trades.Where(t => t.Account == a.Id).Sum(t => t.Realized), held.Sum(p => p.Unrealized),
|
||||||
|
trades.Where(t => t.Account == a.Id).Sum(t => t.Fees), mine.Sum(e => e.Flows), state, rates[a.Id]));
|
||||||
|
}
|
||||||
|
|
||||||
|
var byId = cards.ToDictionary(c => c.Id);
|
||||||
|
var market = MarketState(services.MarketData?.UsCalendar, clock.UtcNow);
|
||||||
|
var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol),
|
||||||
|
positions, market.Open, market.Next, clock.UtcNow, zone);
|
||||||
|
|
||||||
|
var slices = StrategyNames.Base.Select(b => new StrategySlice(StrategyNames.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")",
|
||||||
|
rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList();
|
||||||
|
decimal? fxEffect = null;
|
||||||
|
if (cards.Count > 0)
|
||||||
|
{
|
||||||
|
fxEffect = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync(
|
||||||
|
"SELECT fx_effect FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at DESC LIMIT 1", r => r.MoneyOrNull("fx_effect"), ("w", world)),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var residueRows = residues.Where(r => shown.Contains(r.Account))
|
||||||
|
.Select(r => new ResidueRow(byId[r.Account].Short, instruments.GetValueOrDefault(r.Instrument).Symbol ?? "?", r.Quantity, r.Value, r.Currency, r.At)).ToList();
|
||||||
|
return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The positions as CSV for an Italian spreadsheet (SPEC 13): semicolons, decimal commas, no thousands separator, one row per position.</summary>
|
||||||
|
public string Csv(string? broker)
|
||||||
|
{
|
||||||
|
var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n");
|
||||||
|
foreach (var p in Positions.Where(p => broker is null || p.Broker == broker))
|
||||||
|
{
|
||||||
|
text.Append(string.Join(';', Clean(p.Symbol), Clean(p.Name), p.Broker, p.Strategy, Number(p.Quantity), Number(p.Average), Number(p.Last), p.Currency,
|
||||||
|
Number(Math.Round(p.ValueEur, 2)), Number(Math.Round(p.ResultEur, 2)), p.Stop is { } stop ? Number(stop) : "",
|
||||||
|
p.OpenedAt.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))).Append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
return text.ToString();
|
||||||
|
|
||||||
|
// Trailing zeros dropped, so both database engines give the same text.
|
||||||
|
static string Number(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
|
||||||
|
|
||||||
|
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop,
|
||||||
|
string Tif, int? Step, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt);
|
||||||
|
|
||||||
|
private static (List<PendingRow> Rows, int Others, bool AlpacaStops) PendingRows(List<OpenOrder> orders, Dictionary<Guid, AccountCard> accounts, Dictionary<Guid, string> symbols,
|
||||||
|
IReadOnlyList<LedgerPosition> positions, bool marketOpen, DateTimeOffset marketNext, DateTimeOffset now, TimeZoneInfo zone)
|
||||||
|
{
|
||||||
|
var rows = new List<PendingRow>();
|
||||||
|
var others = 0;
|
||||||
|
foreach (var o in orders.Where(o => o.Purpose != "stop"))
|
||||||
|
{
|
||||||
|
others++;
|
||||||
|
var account = accounts[o.Account];
|
||||||
|
var verb = o.Side == "buy" ? "Compra" : "Vendi";
|
||||||
|
var level = o.Limit is { } limit ? Format.Money(limit, account.Currency) : "a mercato";
|
||||||
|
var status = o.Step is { } step && o.Kind == "limit" ? $"Passo {Math.Min(step + 1, 4)} di 4, dalle {Local(o.CreatedAt, zone)}" : "In corso dalle " + Local(o.CreatedAt, zone);
|
||||||
|
rows.Add(new PendingRow($"{verb} {Format.Quantity(o.Quantity - o.Filled)}", symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, level, status, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
var stops = orders.Where(o => o.Purpose == "stop").ToList();
|
||||||
|
foreach (var o in stops.Where(o => accounts[o.Account].Broker != Venues.Alpaca).OrderByDescending(o => (o.Quantity - o.Filled) * (o.Stop ?? 0m)))
|
||||||
|
{
|
||||||
|
var account = accounts[o.Account];
|
||||||
|
var local = TimeZoneInfo.ConvertTime(o.UpdatedAt, zone);
|
||||||
|
var status = local.Date == TimeZoneInfo.ConvertTime(now, zone).Date && o.UpdatedAt > o.CreatedAt
|
||||||
|
? "Attivo, aggiornato oggi alle " + local.ToString("HH:mm", CultureInfo.InvariantCulture)
|
||||||
|
: "Attivo dal " + DayMonth(TimeZoneInfo.ConvertTime(o.CreatedAt, zone));
|
||||||
|
rows.Add(new PendingRow("Vendi " + Format.Quantity(o.Quantity - o.Filled), symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short,
|
||||||
|
o.Stop is { } stop ? Format.Money(stop, account.Currency, decimals: StopDecimals(stop)) : "", status, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
var alpaca = stops.Where(o => accounts[o.Account].Broker == Venues.Alpaca).ToList();
|
||||||
|
var alpacaHeld = positions.Where(p => accounts.TryGetValue(p.AccountId, out var a) && a.Broker == Venues.Alpaca && p.StopPrice is not null).ToList();
|
||||||
|
var gtc = alpaca.Count(o => o.Tif == "gtc");
|
||||||
|
var fractions = alpacaHeld.Count(p => p.Quantity != decimal.Truncate(p.Quantity));
|
||||||
|
if (gtc > 0)
|
||||||
|
{
|
||||||
|
rows.Add(new PendingRow(gtc == 1 ? "1 stop permanente" : $"{gtc} stop permanenti", "sulle azioni intere", "Alpaca", "vedi tabella sopra", gtc == 1 ? "Attivo" : "Attivi", false));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fractions > 0)
|
||||||
|
{
|
||||||
|
var opens = Local(marketNext, zone);
|
||||||
|
rows.Add(new PendingRow(fractions == 1 ? "1 stop giornaliero" : $"{fractions} stop giornalieri", "sulle frazioni di azione", "Alpaca", "vedi tabella sopra",
|
||||||
|
marketOpen ? "Attivi fino alla chiusura delle " + opens : "In coda per l'apertura delle " + opens, !marketOpen));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (rows, others, gtc > 0 || fractions > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the US market is open now, and its next close (open) or next open (closed).</summary>
|
||||||
|
public static (bool Open, DateTimeOffset Next) MarketState(IMarketCalendar? calendar, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, Zones.NewYork).DateTime);
|
||||||
|
foreach (var useCalendar in new[] { true, false })
|
||||||
|
{
|
||||||
|
for (var d = -1; d <= 8; d++)
|
||||||
|
{
|
||||||
|
var day = today.AddDays(d);
|
||||||
|
var session = useCalendar ? calendar?.SessionOn(day) : Regular(day);
|
||||||
|
if (session is null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now >= session.OpenUtc && now < session.CloseUtc)
|
||||||
|
{
|
||||||
|
return (true, session.CloseUtc);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.OpenUtc > now)
|
||||||
|
{
|
||||||
|
return (false, session.OpenUtc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (false, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A regular session, 9:30 to 16:00 in New York on weekdays: used only when the broker's calendar is not there yet.</summary>
|
||||||
|
private static MarketSession? Regular(DateOnly day)
|
||||||
|
{
|
||||||
|
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTimeOffset At(int hour, int minute)
|
||||||
|
{
|
||||||
|
var local = day.ToDateTime(new TimeOnly(hour, minute));
|
||||||
|
return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)).ToUniversalTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MarketSession(day, At(9, 30), At(16, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Local(DateTimeOffset moment, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(moment, zone).ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
/// <summary>Stops of a thousand or more without cents when they are round (66.180 €), the others with cents (166,00 $).</summary>
|
||||||
|
public static int StopDecimals(decimal stop) => stop >= 1000m && stop == decimal.Truncate(stop) ? 0 : 2;
|
||||||
|
|
||||||
|
public static string DayMonth(DateTimeOffset local)
|
||||||
|
{
|
||||||
|
var text = Format.LongDate(DateOnly.FromDateTime(local.DateTime));
|
||||||
|
return text[..text.LastIndexOf(' ')];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,11 @@
|
|||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<RootNamespace>Anubis.Server</RootNamespace>
|
<RootNamespace>Anubis.Server</RootNamespace>
|
||||||
<InvariantGlobalization>false</InvariantGlobalization>
|
<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>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||||
@@ -9,4 +14,10 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- Style and scripts served from the assembly: no static web assets pipeline, no files to lose (ADR 0007). -->
|
||||||
|
<EmbeddedResource Include="Assets\*" LogicalName="Anubis.Server.Assets.%(Filename)%(Extension)" />
|
||||||
|
<!-- The logo comes only from docs/design/logo (ADR 0005). -->
|
||||||
|
<EmbeddedResource Include="..\..\docs\design\logo\*.svg;..\..\docs\design\logo\*.png;..\..\docs\design\logo\*.ico" LogicalName="Anubis.Server.Brand.%(Filename)%(Extension)" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,768 @@
|
|||||||
|
using Anubis.Access;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
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;
|
||||||
|
|
||||||
|
public enum HostMode
|
||||||
|
{
|
||||||
|
Starting,
|
||||||
|
|
||||||
|
/// <summary>The startup configuration is missing or wrong: the error page lists what to fix.</summary>
|
||||||
|
ConfigProblem,
|
||||||
|
|
||||||
|
/// <summary>Desktop without config.toml, or without a user yet: the first-run wizard.</summary>
|
||||||
|
FirstRun,
|
||||||
|
|
||||||
|
/// <summary>The configured database does not answer: error page, retry, never another database (trap 20).</summary>
|
||||||
|
DatabaseUnavailable,
|
||||||
|
|
||||||
|
/// <summary>The database schema is newer than this version or was altered.</summary>
|
||||||
|
SchemaProblem,
|
||||||
|
|
||||||
|
/// <summary>Database and data folder do not belong together (SPEC 15.1): the user chooses.</summary>
|
||||||
|
IdentityProblem,
|
||||||
|
|
||||||
|
Ready,
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Identity, DateTimeOffset Since, int Attempts);
|
||||||
|
|
||||||
|
/// <summary>Published on the bus whenever the host changes mode.</summary>
|
||||||
|
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, TelegramServices? Telegram = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
|
||||||
|
/// database and nothing else, migrates it after a backup, checks the installation identity, then runs. While anything
|
||||||
|
/// is wrong the interface shows the error page and the host retries by itself; when the database comes back the
|
||||||
|
/// application resumes without a restart.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed partial class AnubisHost(
|
||||||
|
ServerOptions options,
|
||||||
|
StartupConfig initialConfig,
|
||||||
|
IReadOnlyDictionary<string, string?> environment,
|
||||||
|
IClock clock,
|
||||||
|
EventBus bus,
|
||||||
|
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();
|
||||||
|
|
||||||
|
// One step of the loop or one error-page choice at a time: a restore must not race the start that would follow it.
|
||||||
|
private readonly SemaphoreSlim _exclusive = new(1, 1);
|
||||||
|
private TaskCompletionSource _wake = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
private Database? _db;
|
||||||
|
private Task? _schedulerLoop;
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Desktop first run: the password chosen in the wizard, used once the database is ready.</summary>
|
||||||
|
public string? PendingPassword { get; set; }
|
||||||
|
|
||||||
|
public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations;
|
||||||
|
|
||||||
|
/// <summary>Asks the loop to check again now (after the wizard or an error-page choice).</summary>
|
||||||
|
public void Wake()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_wake.TrySetResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Waits until the host reaches <paramref name="mode"/>; for tests and the CLI.</summary>
|
||||||
|
public async Task WaitForAsync(HostMode mode, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
using var cts = new CancellationTokenSource(timeout);
|
||||||
|
while (_status.Mode != mode)
|
||||||
|
{
|
||||||
|
await Task.Delay(20, cts.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Last time the database answered: the "Dati aggiornati" of the top bar.</summary>
|
||||||
|
public DateTimeOffset? LastCheckUtc { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The scheduler loop is alive (health check).</summary>
|
||||||
|
public bool SchedulerRunning => _schedulerLoop is { IsCompleted: false };
|
||||||
|
|
||||||
|
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
|
||||||
|
internal Database? Database => _db;
|
||||||
|
|
||||||
|
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
|
||||||
|
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await _exclusive.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return new Releaser(_exclusive);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable
|
||||||
|
{
|
||||||
|
private int _released;
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _released, 1) == 0)
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Dispose()
|
||||||
|
{
|
||||||
|
base.Dispose();
|
||||||
|
_exclusive.Dispose();
|
||||||
|
_schedulerStop?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
if (options.Demo)
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_wake.Task.IsCompleted)
|
||||||
|
{
|
||||||
|
_wake = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
}
|
||||||
|
|
||||||
|
wake = _wake.Task;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (await ExclusiveAsync(stoppingToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await StepAsync(stoppingToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogStepFailed(logger, ex);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
await StopSchedulerAsync().ConfigureAwait(false);
|
||||||
|
if (_db is not null)
|
||||||
|
{
|
||||||
|
await _db.DisposeAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task StepAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// Desktop: the wizard may have written config.toml, or the user fixed it by hand.
|
||||||
|
if (Config.Platform == PlatformKind.Desktop && !options.Demo && !Config.IsComplete)
|
||||||
|
{
|
||||||
|
Config = options.LoadConfig(environment);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Config.NeedsFirstRun)
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.FirstRun, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Config.IsComplete)
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.ConfigProblem, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_services is not null)
|
||||||
|
{
|
||||||
|
await CheckRunningAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _db.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
LastCheckUtc = clock.UtcNow;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||||
|
if (Config.Db!.Engine == DbEngine.Sqlite)
|
||||||
|
{
|
||||||
|
// Reopen next time: the file may come back, or the folder may be released.
|
||||||
|
await _db.DisposeAsync().ConfigureAwait(false);
|
||||||
|
_db = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
IdentityCheck identity;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var schema = await Migrations.StatusAsync(_db, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (schema.IsEmpty && File.Exists(Config.Data.InstallationFile))
|
||||||
|
{
|
||||||
|
identity = new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (schema.IsEmpty)
|
||||||
|
{
|
||||||
|
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (identity.CanStart)
|
||||||
|
{
|
||||||
|
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (SchemaException ex)
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.SchemaProblem, ex.Message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!identity.CanStart)
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||||
|
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);
|
||||||
|
var access = new AccessStore(_db, clock, secrets, PasswordIterations);
|
||||||
|
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
|
||||||
|
{
|
||||||
|
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
SetStatus(HostMode.FirstRun, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var scheduler = new Scheduler(clock, bus);
|
||||||
|
|
||||||
|
// The guard drill's engine: prices from the drill's local OKX, and then nothing else leaves the computer either
|
||||||
|
// (no news, no model, no other source: ADR 0016). Honored only under a guard, like the drill's OKX itself.
|
||||||
|
var drill = Guard is null ? null : GuardDrill.DrillOkx(environment);
|
||||||
|
_market = MarketDataEnabled
|
||||||
|
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, drill,
|
||||||
|
offline: drill is not null)
|
||||||
|
: 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)
|
||||||
|
{
|
||||||
|
// Before "ready": the Strategie page must never show a strategy without its backtest outcome (SPEC 12.3).
|
||||||
|
// A failure here is logged and left to the trading start, which repeats it: the interface still opens.
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _trading.PrepareAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
LogTradingFailed(logger, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
// 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 (!options.Demo)
|
||||||
|
{
|
||||||
|
await StartCountingAsync([.. SchedulerJobs(backups)], lastDues, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (applied > 0)
|
||||||
|
{
|
||||||
|
LogMigrated(logger, applied, Migrations.Latest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<bool> EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (await access.HasUserAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.Demo)
|
||||||
|
{
|
||||||
|
// The demo signs in by itself (see SessionAuthentication); the password exists only to fill the table.
|
||||||
|
await access.EnsureUserAsync(Ids.NewToken(), mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Config.Platform == PlatformKind.Docker && Config.AdminPassword is { } initial)
|
||||||
|
{
|
||||||
|
await access.EnsureUserAsync(initial, mustChange: true, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PendingPassword is { } chosen)
|
||||||
|
{
|
||||||
|
await access.EnsureUserAsync(chosen, mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||||
|
PendingPassword = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// While running: the database is checked every few seconds. If it stops answering, the error page shows and the
|
||||||
|
// engine waits; when it answers again the installation is checked again (it might be another copy) and the
|
||||||
|
// application resumes by itself.
|
||||||
|
private async Task CheckRunningAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _db!.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
LastCheckUtc = clock.UtcNow;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
if (_status.Mode != HostMode.DatabaseUnavailable)
|
||||||
|
{
|
||||||
|
LogLost(logger, Redactor.Redact(ex.Message));
|
||||||
|
}
|
||||||
|
|
||||||
|
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_status.Mode == HostMode.Ready)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!identity.CanStart)
|
||||||
|
{
|
||||||
|
await StopSchedulerAsync().ConfigureAwait(false);
|
||||||
|
_services = null;
|
||||||
|
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogBack(logger);
|
||||||
|
SetStatus(HostMode.Ready, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// After an error-page choice changed the database: forget the services so the next step starts over. Called while
|
||||||
|
/// the choice still holds <see cref="ExclusiveAsync"/>.
|
||||||
|
/// </summary>
|
||||||
|
internal async Task ResetAsync()
|
||||||
|
{
|
||||||
|
await StopSchedulerAsync().ConfigureAwait(false);
|
||||||
|
_services = null;
|
||||||
|
SetStatus(HostMode.Starting, null);
|
||||||
|
Wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops and rebuilds the services, so that new broker keys take effect: a few seconds of "avvio".</summary>
|
||||||
|
internal async Task RestartServicesAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using (await ExclusiveAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await ResetAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Market data needs the network: off in demo mode (SPEC 13.7), when <c>ANUBIS_MARKET_DATA</c> is <c>off</c>, and
|
||||||
|
/// in tests unless they bring their own fake network.
|
||||||
|
/// </summary>
|
||||||
|
private bool MarketDataEnabled =>
|
||||||
|
!options.Demo && overrides?.MarketData != false &&
|
||||||
|
environment.GetValueOrDefault("ANUBIS_MARKET_DATA") is not ("0" or "off" or "false");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Accounts and orders: off in demo mode (the demo shows appendix F and sends nothing), when
|
||||||
|
/// <c>ANUBIS_TRADING</c> is <c>off</c>, and in tests unless they ask for it.
|
||||||
|
/// </summary>
|
||||||
|
private bool TradingEnabled =>
|
||||||
|
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
|
||||||
|
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
|
||||||
|
|
||||||
|
private IEnumerable<ScheduledJob> SchedulerJobs(Backups backups)
|
||||||
|
{
|
||||||
|
// 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), CatchUpWithin = TimeSpan.FromDays(3650) };
|
||||||
|
return new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A job to make up for after an absence counts from the first start that knows it. Otherwise a computer always off at
|
||||||
|
/// its hour would never make it: without a first run there would be no run to find missed (SPEC 5.6).
|
||||||
|
/// </summary>
|
||||||
|
private Task StartCountingAsync(IReadOnlyList<ScheduledJob> jobs, Dictionary<string, DateTimeOffset> lastDues, CancellationToken cancellationToken) => _db!.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
foreach (var job in jobs.Where(j => j.CatchUpWithin is not null && !lastDues.ContainsKey(j.Name)))
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, created_at, updated_at) VALUES (@id, @n, @d, @now, @now, @now) ON CONFLICT (name) DO NOTHING", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("n", job.Name), ("d", job.Description), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
|
||||||
|
{
|
||||||
|
foreach (var job in SchedulerJobs(backups))
|
||||||
|
{
|
||||||
|
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
_schedulerStop = new CancellationTokenSource();
|
||||||
|
var token = _schedulerStop.Token;
|
||||||
|
var market = _market;
|
||||||
|
var trading = _trading;
|
||||||
|
var lab = _lab;
|
||||||
|
var telegram = _telegram;
|
||||||
|
_schedulerLoop = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
using var runs = bus.Subscribe<JobRun>();
|
||||||
|
var recorder = RecordJobsAsync(runs, token);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
await collecting.ConfigureAwait(false);
|
||||||
|
await dealing.ConfigureAwait(false);
|
||||||
|
await testing.ConfigureAwait(false);
|
||||||
|
await writing.ConfigureAwait(false);
|
||||||
|
await recorder.ConfigureAwait(false);
|
||||||
|
}, CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RunMarketDataAsync(MarketDataService market, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await market.RunAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogMarketDataFailed(logger, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RunLabAsync(Laboratory lab, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await lab.RunAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogLabFailed(logger, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
await trading.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await trading.RunAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogTradingFailed(logger, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6).
|
||||||
|
private async Task RecordJobsAsync(EventSubscription<JobRun> runs, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await foreach (var run in runs.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _db!.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
if (updated == 0)
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync(
|
||||||
|
"INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) VALUES (@id, @n, @desc, @d, @s, @f, @o, @e, @f, @f)",
|
||||||
|
("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)
|
||||||
|
{
|
||||||
|
LogJobRecordFailed(logger, ex, run.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task StopSchedulerAsync()
|
||||||
|
{
|
||||||
|
if (_schedulerStop is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _schedulerStop.CancelAsync().ConfigureAwait(false);
|
||||||
|
if (_schedulerLoop is not null)
|
||||||
|
{
|
||||||
|
await _schedulerLoop.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
_schedulerStop.Dispose();
|
||||||
|
_schedulerStop = null;
|
||||||
|
_schedulerLoop = null;
|
||||||
|
_market?.Dispose();
|
||||||
|
_market = null;
|
||||||
|
_trading?.Dispose();
|
||||||
|
_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).
|
||||||
|
private static Dictionary<string, StartupOverride> StartupOverrides() => [];
|
||||||
|
|
||||||
|
private void SetStatus(HostMode mode, string? detail, IdentityCheck? identity = null)
|
||||||
|
{
|
||||||
|
var previous = _status;
|
||||||
|
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);
|
||||||
|
bus.Publish(new HostChanged(mode));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Information, Message = "Mode: {Mode}")]
|
||||||
|
private static partial void LogMode(ILogger logger, HostMode mode);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")]
|
||||||
|
private static partial void LogDemo(ILogger logger, string folder);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
|
||||||
|
private static partial void LogMigrated(ILogger logger, int count, int version);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Error, Message = "Database lost: {Reason}")]
|
||||||
|
private static partial void LogLost(ILogger logger, string reason);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Information, Message = "Database back: resuming")]
|
||||||
|
private static partial void LogBack(ILogger logger);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Error, Message = "Startup step failed")]
|
||||||
|
private static partial void LogStepFailed(ILogger logger, Exception exception);
|
||||||
|
|
||||||
|
[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);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Error, Message = "Trading stopped")]
|
||||||
|
private static partial void LogTradingFailed(ILogger logger, Exception exception);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")]
|
||||||
|
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
@@ -0,0 +1,884 @@
|
|||||||
|
/* Anubis — tokens of appendix C (SPEC), light and dark. ContrastTests reads this block: keep one token per line. */
|
||||||
|
:root {
|
||||||
|
--page: #f1f3f0;
|
||||||
|
--surface: #fbfcfa;
|
||||||
|
--surface-2: #e9ede8;
|
||||||
|
--track: #dfe4de;
|
||||||
|
--rule: #d9ded8;
|
||||||
|
--rule-inner: #e3e7e2;
|
||||||
|
--control: #8a948e;
|
||||||
|
--text: #141a17;
|
||||||
|
--text-2: #46504a;
|
||||||
|
--text-3: #5f6963;
|
||||||
|
--link: #1c5cab;
|
||||||
|
--info-bg: #e3eefb;
|
||||||
|
--gain: #0a6b55;
|
||||||
|
--gain-bg: #dff2ea;
|
||||||
|
--loss: #b42f1a;
|
||||||
|
--loss-bg: #fbe5df;
|
||||||
|
--attention: #7a5000;
|
||||||
|
--attention-bg: #fbefcf;
|
||||||
|
--s-crypto-trend: #2a78d6;
|
||||||
|
--s-equity-momentum: #eb6834;
|
||||||
|
--s-equity-meanrev: #4a3aa7;
|
||||||
|
--bench: #8a948e;
|
||||||
|
--cash: #c5cbc4;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--page: #101412;
|
||||||
|
--surface: #181d1a;
|
||||||
|
--surface-2: #222924;
|
||||||
|
--track: #2c342f;
|
||||||
|
--rule: #2c342f;
|
||||||
|
--rule-inner: #262d28;
|
||||||
|
--control: #6c766f;
|
||||||
|
--text: #f2f5f1;
|
||||||
|
--text-2: #c3cbc4;
|
||||||
|
--text-3: #9aa39c;
|
||||||
|
--link: #86b6ef;
|
||||||
|
--info-bg: #17304f;
|
||||||
|
--gain: #4cc9a4;
|
||||||
|
--gain-bg: #12372d;
|
||||||
|
--loss: #ff8d78;
|
||||||
|
--loss-bg: #45201a;
|
||||||
|
--attention: #f2c14e;
|
||||||
|
--attention-bg: #3d2f0c;
|
||||||
|
--s-crypto-trend: #17a2b8;
|
||||||
|
--s-equity-momentum: #d95926;
|
||||||
|
--s-equity-meanrev: #9085e9;
|
||||||
|
--bench: #6c766f;
|
||||||
|
--cash: #3a433d;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--page: #101412;
|
||||||
|
--surface: #181d1a;
|
||||||
|
--surface-2: #222924;
|
||||||
|
--track: #2c342f;
|
||||||
|
--rule: #2c342f;
|
||||||
|
--rule-inner: #262d28;
|
||||||
|
--control: #6c766f;
|
||||||
|
--text: #f2f5f1;
|
||||||
|
--text-2: #c3cbc4;
|
||||||
|
--text-3: #9aa39c;
|
||||||
|
--link: #86b6ef;
|
||||||
|
--info-bg: #17304f;
|
||||||
|
--gain: #4cc9a4;
|
||||||
|
--gain-bg: #12372d;
|
||||||
|
--loss: #ff8d78;
|
||||||
|
--loss-bg: #45201a;
|
||||||
|
--attention: #f2c14e;
|
||||||
|
--attention-bg: #3d2f0c;
|
||||||
|
--s-crypto-trend: #17a2b8;
|
||||||
|
--s-equity-momentum: #d95926;
|
||||||
|
--s-equity-meanrev: #9085e9;
|
||||||
|
--bench: #6c766f;
|
||||||
|
--cash: #3a433d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Instrument Sans served by the app itself, never from the internet (ADR 0004, SIL OFL: assets/InstrumentSans-OFL.txt).
|
||||||
|
One variable file covers weights 400 to 700; italics are drawn by the browser from it. */
|
||||||
|
@font-face {
|
||||||
|
font-family: "Instrument Sans";
|
||||||
|
src: url("/assets/InstrumentSans.ttf") format("truetype");
|
||||||
|
font-weight: 400 700;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--font: "Instrument Sans", "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
color-scheme: light dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
*, *::before, *::after { box-sizing: border-box; }
|
||||||
|
html { -webkit-text-size-adjust: 100%; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--page);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: var(--font);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 20px;
|
||||||
|
font-variant-numeric: proportional-nums;
|
||||||
|
}
|
||||||
|
a { color: var(--link); }
|
||||||
|
h1, h2, h3 { margin: 0; font-weight: 650; }
|
||||||
|
h1 { font-size: 22px; line-height: 28px; }
|
||||||
|
h2 { font-size: 17px; line-height: 24px; }
|
||||||
|
h3 { font-size: 14px; line-height: 20px; }
|
||||||
|
p { margin: 0; }
|
||||||
|
code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; overflow-wrap: anywhere; }
|
||||||
|
:focus-visible { outline: 2px solid var(--link); outline-offset: 2px; border-radius: 4px; }
|
||||||
|
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||||
|
.icon { flex: none; }
|
||||||
|
.logo-dark { display: none; }
|
||||||
|
:root[data-theme="dark"] .logo-light { display: none; }
|
||||||
|
:root[data-theme="dark"] .logo-dark { display: inline; }
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) .logo-light { display: none; }
|
||||||
|
:root:not([data-theme="light"]) .logo-dark { display: inline; }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
*, *::before, *::after { transition: none !important; animation: none !important; scroll-behavior: auto !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Shell ---- */
|
||||||
|
.shell { display: grid; grid-template-columns: 220px minmax(0, 1fr); min-height: 100vh; }
|
||||||
|
.sidebar {
|
||||||
|
position: sticky; top: 0; height: 100vh; overflow-y: auto;
|
||||||
|
background: var(--surface); border-right: 1px solid var(--rule);
|
||||||
|
padding: 20px 12px 24px;
|
||||||
|
}
|
||||||
|
.brand { display: flex; align-items: center; justify-content: space-between; padding: 0 8px 0 10px; margin-bottom: 20px; min-height: 40px; }
|
||||||
|
.brand-link { display: flex; align-items: center; gap: 14px; color: var(--text); text-decoration: none; font-size: 20px; font-weight: 650; }
|
||||||
|
.icon-button {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px;
|
||||||
|
border: 0; border-radius: 8px; background: transparent; color: var(--text-3); cursor: pointer;
|
||||||
|
}
|
||||||
|
.icon-button:hover { background: var(--surface-2); color: var(--text); }
|
||||||
|
.when-closed { display: none; }
|
||||||
|
.nav-group { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.nav-group + .nav-group { margin-top: 22px; }
|
||||||
|
.nav-item {
|
||||||
|
display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 8px 12px; margin-bottom: 2px;
|
||||||
|
border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px;
|
||||||
|
}
|
||||||
|
.nav-item:hover { background: var(--surface-2); color: var(--text); }
|
||||||
|
.nav-item.active { background: var(--surface-2); color: var(--text); font-weight: 600; }
|
||||||
|
|
||||||
|
:root[data-nav="collapsed"] .shell { grid-template-columns: 72px minmax(0, 1fr); }
|
||||||
|
:root[data-nav="collapsed"] .brand { flex-direction: column; gap: 8px; padding: 0; }
|
||||||
|
:root[data-nav="collapsed"] .brand-name,
|
||||||
|
:root[data-nav="collapsed"] .nav-label { display: none; }
|
||||||
|
:root[data-nav="collapsed"] .nav-item { justify-content: center; padding: 10px; }
|
||||||
|
:root[data-nav="collapsed"] .when-open { display: none; }
|
||||||
|
:root[data-nav="collapsed"] .when-closed { display: inline; }
|
||||||
|
|
||||||
|
.main { min-width: 0; display: flex; flex-direction: column; }
|
||||||
|
.topbar {
|
||||||
|
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: nowrap;
|
||||||
|
padding: 16px 32px; background: var(--surface); border-bottom: 1px solid var(--rule);
|
||||||
|
}
|
||||||
|
.topbar-title { min-width: 0; flex: 1 1 auto; }
|
||||||
|
.status-line { color: var(--text-3); font-size: 13px; line-height: 18px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.topbar-actions { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||||
|
@media (max-width: 1240px) {
|
||||||
|
.topbar { flex-wrap: wrap; }
|
||||||
|
.topbar-actions { flex-wrap: wrap; }
|
||||||
|
}
|
||||||
|
.topbar-actions form { margin: 0; }
|
||||||
|
/* As in the mockup: one point smaller up here, so the date line keeps its full length at 1440 px. */
|
||||||
|
.topbar-actions .pill, .topbar-actions .btn, .topbar-actions .currency select { font-size: 13px; }
|
||||||
|
.phone-brand, .phone-bot, .mode-band, .bottombar { display: none; }
|
||||||
|
|
||||||
|
.pill {
|
||||||
|
display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px;
|
||||||
|
border-radius: 999px; font-size: 14px; font-weight: 550; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.pill-bot { border: 1px solid var(--rule); background: var(--surface); color: var(--text); margin-right: 0; }
|
||||||
|
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--gain); flex: none; }
|
||||||
|
[data-state="paused"] .dot { background: var(--attention); }
|
||||||
|
[data-state="stopped"] .dot { background: var(--loss); }
|
||||||
|
.pill-mode { background: var(--info-bg); color: var(--link); margin-right: 12px; }
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 40px; padding: 0 16px;
|
||||||
|
border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
|
||||||
|
font: inherit; font-size: 14px; font-weight: 550; cursor: pointer; text-decoration: none; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--surface-2); }
|
||||||
|
.btn:disabled { opacity: .55; cursor: not-allowed; }
|
||||||
|
.btn-small { height: 32px; padding: 0 12px; }
|
||||||
|
.btn-danger { border-color: var(--loss); color: var(--loss); }
|
||||||
|
.btn-danger:hover { background: var(--loss-bg); }
|
||||||
|
.btn-primary { background: var(--text); border-color: var(--text); color: var(--surface); }
|
||||||
|
.btn-primary:hover { background: var(--text-2); }
|
||||||
|
|
||||||
|
.currency { position: relative; }
|
||||||
|
.currency select, select, input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]) {
|
||||||
|
height: 40px; border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
|
||||||
|
font: inherit; font-size: 14px; padding: 0 12px;
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
|
||||||
|
font-family: ui-monospace, Consolas, monospace; font-size: 13.5px; padding: 8px 12px; resize: vertical;
|
||||||
|
}
|
||||||
|
.currency select { appearance: none; padding: 0 40px 0 16px; font-weight: 550; cursor: pointer; }
|
||||||
|
.select-chevron { position: absolute; right: 14px; top: 12px; pointer-events: none; color: var(--text-2); }
|
||||||
|
|
||||||
|
.stale-notice {
|
||||||
|
display: flex; align-items: center; gap: 10px; margin: 12px 32px 0; padding: 10px 12px; border-radius: 10px;
|
||||||
|
background: var(--attention-bg); color: var(--attention); font-size: 13.5px;
|
||||||
|
}
|
||||||
|
.stale-notice[hidden] { display: none; }
|
||||||
|
|
||||||
|
.page { padding: 28px 32px 36px; display: flex; flex-direction: column; gap: 28px; flex: 1; }
|
||||||
|
.page-footer { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||||
|
|
||||||
|
/* ---- Components ---- */
|
||||||
|
.panel { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; }
|
||||||
|
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||||
|
.panel > h3, .panel h3 { margin: 20px 0 8px; }
|
||||||
|
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||||
|
h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; }
|
||||||
|
.hint { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||||
|
.empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; }
|
||||||
|
.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
|
||||||
|
.notice {
|
||||||
|
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border-radius: 10px; font-size: 13.5px; line-height: 20px;
|
||||||
|
}
|
||||||
|
.notice .icon { margin-top: 2px; }
|
||||||
|
.notice-loss { background: var(--loss-bg); color: var(--loss); }
|
||||||
|
.notice-gain { background: var(--gain-bg); color: var(--gain); }
|
||||||
|
.notice-attention { background: var(--attention-bg); color: var(--attention); }
|
||||||
|
.badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 8px; font-size: 18px; line-height: 24px; font-weight: 600; }
|
||||||
|
.badge-gain { background: var(--gain-bg); color: var(--gain); }
|
||||||
|
.badge-loss { background: var(--loss-bg); color: var(--loss); }
|
||||||
|
.gain { color: var(--gain); }
|
||||||
|
.loss { color: var(--loss); }
|
||||||
|
.arrow { flex: none; }
|
||||||
|
|
||||||
|
.table-wrap { overflow-x: auto; }
|
||||||
|
.table { width: 100%; border-collapse: collapse; font-size: 13.5px; line-height: 20px; font-variant-numeric: tabular-nums; }
|
||||||
|
.table th { text-align: left; font-size: 12.5px; font-weight: 500; color: var(--text-3); padding: 9px 12px 9px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.table td { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; }
|
||||||
|
.table .num { text-align: right; }
|
||||||
|
.nowrap { white-space: nowrap; }
|
||||||
|
|
||||||
|
.facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 20px; margin: 0; }
|
||||||
|
.facts dt { color: var(--text-3); }
|
||||||
|
.facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||||
|
.facts + .hint, .facts + h2, .facts + h3 { margin-top: 16px; }
|
||||||
|
|
||||||
|
.form { display: flex; flex-direction: column; gap: 8px; max-width: 420px; }
|
||||||
|
.form label { font-weight: 550; margin-top: 6px; }
|
||||||
|
.form .btn { align-self: flex-start; margin-top: 10px; }
|
||||||
|
.form fieldset { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }
|
||||||
|
.form-inline { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 8px 0; }
|
||||||
|
.form-inline label { min-width: 80px; font-weight: 550; }
|
||||||
|
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||||
|
.row > div { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.choice { display: flex; gap: 10px; align-items: flex-start; font-weight: 400 !important; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; }
|
||||||
|
.choice input { margin-top: 4px; }
|
||||||
|
fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||||
|
legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-weight: 650; margin-bottom: 8px; padding: 0; }
|
||||||
|
.step { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; background: var(--surface-2); align-items: center; justify-content: center; font-size: 14px; }
|
||||||
|
.postgres-fields { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
|
||||||
|
.postgres-fields[hidden] { display: none; }
|
||||||
|
.test-result:empty { display: none; }
|
||||||
|
.steps { margin: 8px 0; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.secret { background: var(--surface-2); padding: 2px 6px; border-radius: 6px; }
|
||||||
|
.tabs { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||||
|
.tabs a { color: var(--text-2); text-decoration: none; font-weight: 550; }
|
||||||
|
.tabs a:hover { color: var(--text); text-decoration: underline; }
|
||||||
|
.columns { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||||
|
.more-list { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.more-list a { display: flex; align-items: center; gap: 12px; min-height: 48px; color: var(--text); text-decoration: none; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
|
||||||
|
/* ---- Panoramica ---- */
|
||||||
|
.head-block { display: grid; grid-template-columns: 1.35fr 1fr; padding: 0; }
|
||||||
|
.half { padding: 24px 28px; min-width: 0; }
|
||||||
|
.half + .half { border-left: 1px solid var(--rule); }
|
||||||
|
.half-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; min-height: 44px; }
|
||||||
|
.half-head h2 { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.segmented { display: inline-flex; padding: 4px; border-radius: 10px; background: var(--surface-2); gap: 2px; }
|
||||||
|
.segmented a { padding: 6px 14px; border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px; }
|
||||||
|
.segmented a.on { background: var(--surface); color: var(--text); font-weight: 550; }
|
||||||
|
.lead { color: var(--text-2); font-size: 17px; line-height: 24px; margin-top: 20px; }
|
||||||
|
.big-result { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; margin-top: 4px; }
|
||||||
|
.big-number { font-size: 60px; line-height: 60px; font-weight: 650; letter-spacing: -0.025em; }
|
||||||
|
.half-past .note { margin-top: 10px; }
|
||||||
|
.cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-top: 20px; padding: 16px 0; border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); }
|
||||||
|
.cell { display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.cell-label { color: var(--text-3); font-size: 13px; }
|
||||||
|
.cell-value { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; }
|
||||||
|
.cell-change { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 550; }
|
||||||
|
.statement { font-size: 20px; line-height: 28px; font-weight: 650; margin: 20px 0 8px; }
|
||||||
|
.list-title { color: var(--text-3); font-weight: 550; margin-top: 20px !important; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
|
||||||
|
.moves { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.moves li { display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.move-time { font-weight: 650; font-variant-numeric: tabular-nums; }
|
||||||
|
.moves-past .move-time { font-weight: 500; color: var(--text-3); }
|
||||||
|
.more { display: inline-block; margin-top: 12px; }
|
||||||
|
|
||||||
|
.chart { margin: 20px 0 0; }
|
||||||
|
.chart-box { position: relative; display: grid; grid-template-columns: 64px minmax(0, 1fr) 84px; height: 284px; }
|
||||||
|
.chart-axis { position: relative; }
|
||||||
|
.chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; }
|
||||||
|
.chart-plot { position: relative; }
|
||||||
|
.chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
||||||
|
.chart .grid { stroke: var(--rule-inner); stroke-width: 1; }
|
||||||
|
.chart .area { fill: var(--text); opacity: .05; }
|
||||||
|
.chart .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.chart .bench { fill: none; stroke: var(--bench); stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.end-dot { position: absolute; width: 14px; height: 14px; margin: -7px 0 0 -7px; border-radius: 50%; background: var(--text); border: 2px solid var(--surface); }
|
||||||
|
.end-dot.bench-dot { background: var(--bench); }
|
||||||
|
.end-label { position: absolute; left: 100%; margin-left: 14px; transform: translateY(-50%); font-weight: 650; font-size: 13px; white-space: nowrap; }
|
||||||
|
.end-label.bench-label { font-weight: 400; color: var(--text-3); }
|
||||||
|
.legend { display: flex; gap: 20px; margin-top: 12px; color: var(--text-2); font-size: 13px; }
|
||||||
|
.key { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
.key::before { content: ""; width: 18px; height: 2px; background: var(--text); }
|
||||||
|
.key-bench::before { background: var(--bench); }
|
||||||
|
.chart-table { margin-top: 8px; font-size: 13px; }
|
||||||
|
.chart-table summary { color: var(--link); cursor: pointer; }
|
||||||
|
.chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; }
|
||||||
|
|
||||||
|
/* ---- Conti e posizioni ---- */
|
||||||
|
.muted { color: var(--text-3); font-weight: 400; }
|
||||||
|
.attention { color: var(--attention); }
|
||||||
|
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; margin-bottom: 12px; }
|
||||||
|
.panel-head h2 { margin: 0; }
|
||||||
|
.panel-tools { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.totals { padding: 24px 28px; }
|
||||||
|
.totals-cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
|
||||||
|
.total-value { font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||||
|
.cell-note { color: var(--text-3); font-size: 13px; }
|
||||||
|
.split-bar { display: flex; gap: 3px; height: 12px; margin-top: 24px; }
|
||||||
|
.split-bar span { border-radius: 3px; min-width: 3px; }
|
||||||
|
.split-bar.slim { height: 12px; margin: 16px 0 12px; }
|
||||||
|
.split-legend { list-style: none; display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 12px 0 0; padding: 0; color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.split-legend li { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
.split-legend strong { color: var(--text); font-weight: 600; }
|
||||||
|
.swatch { display: inline-block; width: 11px; height: 11px; border-radius: 2px; flex: none; margin-right: 8px; vertical-align: -1px; }
|
||||||
|
.swatch.round { width: 8px; height: 8px; border-radius: 50%; }
|
||||||
|
.split-legend .swatch { margin-right: 0; }
|
||||||
|
.account-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); gap: 20px; }
|
||||||
|
.account { display: flex; flex-direction: column; padding: 22px 26px; }
|
||||||
|
.account-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.account-head h2 { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.tag { padding: 2px 8px; border-radius: 6px; background: var(--surface-2); color: var(--text-2); font-size: 13px; font-weight: 500; line-height: 20px; }
|
||||||
|
.tag.gain { background: var(--gain-bg); color: var(--gain); }
|
||||||
|
.tag.loss { background: var(--loss-bg); color: var(--loss); }
|
||||||
|
.link-state { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.link-state.down .dot { background: var(--loss); }
|
||||||
|
.account-value { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin: 14px 0 12px; }
|
||||||
|
.account-equity { font-size: 32px; line-height: 40px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||||
|
.account-native, .native { color: var(--text-3); font-size: 13.5px; font-weight: 400; }
|
||||||
|
.native { margin-left: 0.35em; }
|
||||||
|
.account-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 0; font-variant-numeric: tabular-nums; }
|
||||||
|
.account-lines dt, .account-lines dd { padding: 9px 0; border-top: 1px solid var(--rule-inner); margin: 0; }
|
||||||
|
.account-lines dt { color: var(--text-2); }
|
||||||
|
.account-lines dd { text-align: right; }
|
||||||
|
.account-lines strong { font-weight: 600; }
|
||||||
|
.account-facts { list-style: none; margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); display: flex; flex-direction: column; gap: 6px; font-size: 13.5px; color: var(--text-2); }
|
||||||
|
.account-facts li { display: flex; align-items: flex-start; gap: 10px; }
|
||||||
|
.account-facts .icon { margin-top: 2px; color: var(--text-3); }
|
||||||
|
.account-facts .loss .icon, .account-facts .attention .icon { color: inherit; }
|
||||||
|
.prudent { margin-top: 16px; }
|
||||||
|
.prudent > div { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.differences { margin: 0; padding-left: 18px; }
|
||||||
|
.choices { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.choices form { margin: 0; }
|
||||||
|
.positions th[scope="row"] { font-weight: 400; text-align: left; white-space: nowrap; }
|
||||||
|
.positions th[scope="row"] strong { font-weight: 650; }
|
||||||
|
.table tbody tr:last-child td, .table tbody tr:last-child th { border-bottom: 0; }
|
||||||
|
.table tfoot th, .table tfoot td { padding: 12px 12px 4px 0; border-top: 2px solid var(--text); text-align: left; }
|
||||||
|
.table tfoot .num { text-align: right; }
|
||||||
|
.table th[scope="row"] { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; }
|
||||||
|
.pending th[scope="row"], .positions th[scope="row"] { color: var(--text); }
|
||||||
|
.pending th[scope="row"] { font-weight: 400; text-align: left; }
|
||||||
|
.pending th[scope="row"] strong { font-weight: 650; }
|
||||||
|
.order-state { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
.order-state .icon { color: var(--text-3); }
|
||||||
|
.aside { margin-top: 16px; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.currency-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 16px; margin: 0 0 12px; font-variant-numeric: tabular-nums; }
|
||||||
|
.currency-lines dt { display: flex; align-items: center; color: var(--text-2); }
|
||||||
|
.currency-lines dd { margin: 0; text-align: right; }
|
||||||
|
.fx-warning { margin-top: 16px; }
|
||||||
|
|
||||||
|
/* ---- Operazioni ---- */
|
||||||
|
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||||
|
.trades-head .lead { margin-top: 0; }
|
||||||
|
.trades-head .big-number { margin-top: 8px; }
|
||||||
|
.trades-head .note { margin-top: 10px; }
|
||||||
|
.trades-head h2 { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.cells { margin-bottom: 0; }
|
||||||
|
.cells > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||||
|
.cells dt { color: var(--text-3); font-size: 13px; }
|
||||||
|
.cells dd { margin: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.cells dd strong { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; font-variant-numeric: tabular-nums; }
|
||||||
|
.cells dd span { color: var(--text-3); font-size: 13px; }
|
||||||
|
.result-bars { display: block; width: 100%; height: 170px; margin-top: 16px; }
|
||||||
|
.result-bars .axis { stroke: var(--rule); stroke-width: 1; vector-effect: non-scaling-stroke; }
|
||||||
|
.result-bars rect.gain { fill: var(--gain); }
|
||||||
|
.result-bars rect.loss { fill: var(--loss); }
|
||||||
|
.bars-scale { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
|
||||||
|
.filters .btn:last-child { margin-left: auto; }
|
||||||
|
.search { position: relative; flex: 1 1 240px; display: flex; align-items: center; }
|
||||||
|
.search .icon { position: absolute; left: 14px; color: var(--text-3); pointer-events: none; }
|
||||||
|
.search input { width: 100%; padding-left: 40px !important; }
|
||||||
|
.trades { display: flex; flex-direction: column; margin: 0 -22px; }
|
||||||
|
.trade-row {
|
||||||
|
display: grid; grid-template-columns: 116px minmax(0, 1fr) 128px 70px 176px 146px minmax(0, 1.7fr) 20px;
|
||||||
|
gap: 12px; align-items: center; padding: 14px 22px; border-bottom: 1px solid var(--rule-inner); font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.trade-header { color: var(--text-3); font-size: 13px; padding-top: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
|
||||||
|
.trade-header::after { content: ""; }
|
||||||
|
.trade-row .num { text-align: right; }
|
||||||
|
.trade summary { list-style: none; cursor: pointer; }
|
||||||
|
.trade summary::-webkit-details-marker { display: none; }
|
||||||
|
.trade summary::after {
|
||||||
|
content: ""; justify-self: end; width: 8px; height: 8px; margin-right: 4px;
|
||||||
|
border-right: 2px solid var(--text-2); border-bottom: 2px solid var(--text-2); transform: rotate(45deg) translateY(-3px);
|
||||||
|
}
|
||||||
|
.trade[open] summary::after { transform: rotate(-135deg) translateY(-3px); }
|
||||||
|
.trade summary:hover { background: var(--surface-2); }
|
||||||
|
.trade[open] { background: var(--surface-2); }
|
||||||
|
.trade[open] summary { border-bottom: 0; }
|
||||||
|
.why { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 4px 22px 22px; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.why-card { background: var(--surface); border: 1px solid var(--rule); border-radius: 12px; padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.why-card h3 { margin: 0 !important; }
|
||||||
|
.why-card .account-lines { margin-top: 4px; }
|
||||||
|
.checks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.checks li { display: flex; align-items: flex-start; gap: 10px; }
|
||||||
|
.checks .icon { margin-top: 2px; }
|
||||||
|
.checks .ok .icon { color: var(--gain); }
|
||||||
|
.checks .warn { color: var(--attention); }
|
||||||
|
.checks .wait .icon { color: var(--text-2); }
|
||||||
|
.pager { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 18px; }
|
||||||
|
.pager .note { margin-right: auto; }
|
||||||
|
|
||||||
|
/* ---- Strategie ---- */
|
||||||
|
.stages { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
|
||||||
|
.stages li { border: 1px solid var(--rule); border-radius: 12px; padding: 16px 18px; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.stages li > strong { font-size: 15px; }
|
||||||
|
.stages li > p { color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.stages li.here { border: 2px solid var(--text); background: var(--surface-2); padding: 15px 17px; }
|
||||||
|
.stages .step { border: 1.5px solid var(--text); background: transparent; width: 24px; height: 24px; font-size: 13px; font-weight: 650; }
|
||||||
|
.stages .here .step { background: var(--text); color: var(--surface); }
|
||||||
|
.stage-count { display: flex; align-items: center; gap: 4px; margin-top: auto; padding-top: 6px; color: var(--text) !important; }
|
||||||
|
.stage-count .swatch { margin-right: 0; }
|
||||||
|
.stage-count strong { margin-left: 4px; }
|
||||||
|
.strategy { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1.15fr); padding: 0; }
|
||||||
|
.strategy > div { padding: 24px 26px; min-width: 0; display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.strategy > div + div { border-left: 1px solid var(--rule); }
|
||||||
|
.strategy-about h2 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 20px; line-height: 28px; }
|
||||||
|
.strategy-about h2 .tag { margin-left: 10px; background: var(--info-bg); color: var(--link); }
|
||||||
|
.strategy-about > p:first-of-type { font-size: 15px; line-height: 22px; }
|
||||||
|
.strategy-about ul { margin: 0; padding-left: 20px; color: var(--text-2); display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.strategy-about .note { margin-top: auto; }
|
||||||
|
.strategy-number { display: flex; align-items: center; gap: 14px; font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||||
|
.spark { display: block; width: 100%; height: 80px; }
|
||||||
|
.strategy-result .account-lines { grid-template-columns: max-content minmax(0, 1fr); column-gap: 16px; }
|
||||||
|
.strategy-result .account-lines dd { overflow-wrap: anywhere; }
|
||||||
|
.spark polyline { fill: none; stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.strategy-steps h3 { margin: 0 !important; }
|
||||||
|
.strategy-steps form { margin: 0; }
|
||||||
|
.confirm-live summary { list-style: none; align-self: flex-start; display: inline-flex; }
|
||||||
|
.confirm-live summary::-webkit-details-marker { display: none; }
|
||||||
|
.confirm-live[open] summary { margin-bottom: 12px; }
|
||||||
|
.confirm-summary { margin: 0; padding-left: 20px; display: grid; gap: 4px; }
|
||||||
|
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px 16px; align-items: end; }
|
||||||
|
.form-grid > p { grid-column: 1 / -1; }
|
||||||
|
.form-grid label { display: flex; flex-direction: column; gap: 6px; font-weight: 550; }
|
||||||
|
.form-grid .btn { justify-self: start; }
|
||||||
|
.confirm-live .form-grid { grid-template-columns: 1fr; }
|
||||||
|
.plain { border-top: 2px solid var(--text); padding-top: 18px; }
|
||||||
|
.plain > h2 { margin-bottom: 8px; }
|
||||||
|
.observing { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); margin: 0; }
|
||||||
|
.observing dt, .observing dd { margin: 0; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.observing dt { font-weight: 650; padding-right: 32px; }
|
||||||
|
.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); }
|
||||||
|
.observing form { margin: 0; flex: none; }
|
||||||
|
.attention { display: inline-flex; align-items: center; gap: 6px; }
|
||||||
|
|
||||||
|
/* ---- Rischio ---- */
|
||||||
|
.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
|
||||||
|
.risk-top .panel { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.risk-top .panel-head { margin-bottom: 0; }
|
||||||
|
.risk-top p { color: var(--text-2); }
|
||||||
|
.btn-danger-solid { background: var(--loss); border-color: var(--loss); color: var(--surface); }
|
||||||
|
.btn-danger-solid:hover { background: var(--loss); opacity: .9; }
|
||||||
|
.status-line.gain { display: flex; align-items: center; gap: 8px; color: var(--gain); font-weight: 600; font-size: 14px; white-space: normal; }
|
||||||
|
.blocks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.blocks li { display: flex; align-items: flex-start; gap: 10px; }
|
||||||
|
.blocks .icon { margin-top: 2px; }
|
||||||
|
.block-list { margin: 0; display: flex; flex-direction: column; }
|
||||||
|
.block-list dt { color: var(--text-3); font-size: 13px; padding-top: 12px; border-top: 1px solid var(--rule-inner); }
|
||||||
|
.block-list dd { margin: 0 0 12px; display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.block-list dd span { color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.limits td.wide { width: 24%; vertical-align: middle; }
|
||||||
|
.usage { display: block; position: relative; height: 6px; border-radius: 3px; background: var(--track); overflow: hidden; }
|
||||||
|
.usage span { display: block; height: 100%; border-radius: 3px; background: var(--text-2); min-width: 2px; }
|
||||||
|
.usage.high span { background: var(--attention); }
|
||||||
|
.drawdown { display: block; width: 100%; height: auto; margin-top: 12px; overflow: visible; }
|
||||||
|
.drawdown .axis { stroke: var(--rule); stroke-width: 1; }
|
||||||
|
.drawdown .tick { fill: var(--text-3); font-size: 12px; }
|
||||||
|
.drawdown .area { fill: var(--loss); opacity: .1; }
|
||||||
|
.drawdown .line { fill: none; stroke: var(--loss); stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.drawdown .dot { fill: var(--loss); }
|
||||||
|
.drawdown .label { fill: var(--text); font-size: 12.5px; font-weight: 650; }
|
||||||
|
.columns .panel .notice { margin-top: 12px; }
|
||||||
|
.never { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.never li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.never .icon { color: var(--text-2); }
|
||||||
|
.events { display: grid; grid-template-columns: 140px minmax(0, 1fr); margin: 0 0 12px; }
|
||||||
|
.events dt, .events dd { margin: 0; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
/* ---- Notizie e mercato (mockup 05) ---- */
|
||||||
|
.page-lead { margin: 0 0 20px; font-size: 15px; line-height: 22px; }
|
||||||
|
.news-columns { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 24px; align-items: start; }
|
||||||
|
.news-panel { padding: 24px 26px; }
|
||||||
|
.news-panel > .panel-head { padding-bottom: 16px; margin-bottom: 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.news-rows { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.news-rows li { display: flex; flex-direction: column; gap: 8px; padding: 18px 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.news-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin: 0; color: var(--text-3); font-size: 13.5px; }
|
||||||
|
.tag-strong { color: var(--text); font-weight: 600; }
|
||||||
|
.tag-outline { background: none; border: 1px solid var(--control); color: var(--text); font-weight: 400; }
|
||||||
|
.panel h3.news-title { margin: 0; font-size: 16px; line-height: 22px; font-weight: 600; }
|
||||||
|
.news-summary { margin: 0; color: var(--text-2); font-size: 14px; line-height: 20px; }
|
||||||
|
.news-facts { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 24px; margin: 0; color: var(--text-2); font-size: 13.5px; }
|
||||||
|
.tone { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
.tone .tone-text { color: var(--text-2); }
|
||||||
|
.tone-flat { display: inline-block; width: 10px; height: 2px; background: currentColor; }
|
||||||
|
.importance { display: inline-flex; align-items: center; gap: 8px; }
|
||||||
|
.importance-bars { display: inline-flex; gap: 2px; }
|
||||||
|
.importance-bars span { width: 5px; height: 12px; border-radius: 1.5px; background: var(--track); }
|
||||||
|
.importance-bars span.on { background: var(--text); }
|
||||||
|
.news-rows .notice { margin: 4px 0 0; }
|
||||||
|
.news-action { margin: 0; font-size: 13.5px; color: var(--text-2); }
|
||||||
|
.news-action strong, .news-rows .notice strong { font-weight: 650; color: inherit; }
|
||||||
|
.news-action strong { color: var(--text); }
|
||||||
|
.news-more { display: flex; justify-content: center; padding-top: 16px; }
|
||||||
|
.news-empty { padding: 16px 0 4px; }
|
||||||
|
.news-side .panel { padding: 22px 26px; }
|
||||||
|
.gauges { list-style: none; margin: 14px 0 0; padding: 0; display: flex; flex-direction: column; gap: 18px; }
|
||||||
|
.gauge-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; font-size: 13.5px; color: var(--text-2); }
|
||||||
|
.gauge-head strong { color: var(--text); font-size: 15px; font-weight: 650; }
|
||||||
|
.gauge-track { position: relative; height: 4px; margin: 10px 6px 6px; border-radius: 2px; background: var(--track); }
|
||||||
|
.gauge-track.centered::before { content: ""; position: absolute; left: 50%; top: -5px; width: 1px; height: 14px; background: var(--control); }
|
||||||
|
.gauge-dot { position: absolute; top: 50%; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; background: var(--text); }
|
||||||
|
.gauge-ends { display: flex; justify-content: space-between; gap: 12px; color: var(--text-3); font-size: 12.5px; }
|
||||||
|
.gauges li .hint { margin: 4px 0 0; }
|
||||||
|
.gauges-note { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--rule); }
|
||||||
|
.calendar-list { list-style: none; margin: 12px 0 0; padding: 0; }
|
||||||
|
.calendar-list li { display: flex; flex-direction: column; gap: 2px; padding: 14px 0; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||||
|
.calendar-list li:last-child { padding-bottom: 2px; }
|
||||||
|
.calendar-list strong { font-size: 14.5px; font-weight: 600; }
|
||||||
|
.attention-text { color: var(--attention); }
|
||||||
|
.source-list { list-style: none; margin: 8px 0 12px; padding: 0; }
|
||||||
|
.source-list li { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 9px 0; border-bottom: 1px solid var(--rule-inner); font-size: 14px; }
|
||||||
|
.source-list li > span:first-child { display: inline-flex; }
|
||||||
|
.source-list .muted { text-align: right; }
|
||||||
|
|
||||||
|
/* ---- Apprendimento (mockup 06) ---- */
|
||||||
|
.learning-head { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); }
|
||||||
|
.learning-state { display: flex; flex-direction: column; align-items: flex-start; gap: 14px; }
|
||||||
|
.learning-state h2 { font-size: 26px; line-height: 34px; letter-spacing: -0.015em; }
|
||||||
|
.learning-text { color: var(--text-2); font-size: 15px; line-height: 23px; max-width: 62ch; }
|
||||||
|
.learning-progress { width: 100%; max-width: 560px; }
|
||||||
|
.learning-progress .usage { height: 8px; border-radius: 4px; }
|
||||||
|
.state-badge { display: inline-flex; align-items: center; gap: 8px; padding: 4px 12px; border-radius: 999px; background: var(--surface-2); color: var(--text); font-weight: 600; font-size: 13.5px; }
|
||||||
|
.state-badge.on { background: var(--gain-bg); color: var(--gain); }
|
||||||
|
.state-badge.warn { background: var(--attention-bg); color: var(--attention); }
|
||||||
|
.learning-facts { margin: 0; display: flex; flex-direction: column; justify-content: center; }
|
||||||
|
.learning-facts > div { padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.learning-facts > div:last-child { border-bottom: 0; }
|
||||||
|
.learning-facts dt { color: var(--text-3); font-size: 13.5px; }
|
||||||
|
.learning-facts dd { margin: 0; }
|
||||||
|
.learning-facts dd strong { font-size: 16px; line-height: 24px; font-weight: 650; }
|
||||||
|
.learning-facts .learning-precision { font-size: 30px; line-height: 38px; font-weight: 650; letter-spacing: -0.02em; }
|
||||||
|
.learning-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: stretch; }
|
||||||
|
.learning-row-wide { grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); }
|
||||||
|
.learning-row .panel { padding: 24px 26px; display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.learning-row .panel > h2 { margin-bottom: 4px; }
|
||||||
|
.learning-open { align-items: start; gap: 28px; }
|
||||||
|
.calibration { display: flex; flex-direction: column; margin-top: 12px; flex: 1; }
|
||||||
|
.calibration-title, .calibration-foot { color: var(--text-2); font-size: 14px; }
|
||||||
|
.calibration-foot { text-align: center; margin-right: 20%; }
|
||||||
|
.calibration-box { position: relative; display: grid; grid-template-columns: 56px minmax(0, 1fr); height: 250px; margin: 14px 20% 0 0; }
|
||||||
|
.calibration .chart-axis { display: block; }
|
||||||
|
.calibration .base { stroke: var(--control); stroke-width: 1; }
|
||||||
|
.calibration-x { position: relative; height: 30px; margin: 8px 20% 0 56px; color: var(--text-3); font-size: 13px; }
|
||||||
|
.calibration-x span { position: absolute; transform: translateX(-50%); }
|
||||||
|
.calibration .legend { margin-top: 20px; }
|
||||||
|
.calibration-text { color: var(--text-2); margin-top: 12px; }
|
||||||
|
.point-label { position: absolute; white-space: nowrap; font-size: 13.5px; font-weight: 650; pointer-events: none; }
|
||||||
|
.point-label.below { transform: translate(12px, 8px); }
|
||||||
|
.point-label.below-left { transform: translate(calc(-100% - 10px), 8px); }
|
||||||
|
.point-label.above { transform: translate(-100%, -24px); margin-left: -8px; }
|
||||||
|
.point-label.under { transform: translate(-50%, 10px); }
|
||||||
|
.hover-dot:hover { z-index: 2; }
|
||||||
|
.hover-dot.quiet { opacity: 0; }
|
||||||
|
.hover-dot.quiet:hover { opacity: 1; }
|
||||||
|
.hover-box { display: none; position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%); padding: 6px 10px; border-radius: 8px; background: var(--text); color: var(--surface); font-size: 13px; line-height: 18px; white-space: nowrap; font-weight: 500; }
|
||||||
|
.hover-dot:hover .hover-box { display: block; }
|
||||||
|
.weights { list-style: none; margin: 12px 0 0; padding: 0; }
|
||||||
|
.weights li { display: grid; grid-template-columns: minmax(0, 215px) minmax(0, 1fr) 30px; gap: 16px; align-items: center; min-height: 31px; }
|
||||||
|
.weights strong { text-align: right; font-variant-numeric: tabular-nums; font-weight: 650; }
|
||||||
|
.weight-bar span { display: block; height: 11px; border-radius: 0 4px 4px 0; background: var(--text-2); min-width: 2px; }
|
||||||
|
.weights .rest > span:first-child { color: var(--text-3); }
|
||||||
|
.weights .rest .weight-bar span { background: var(--bench); }
|
||||||
|
.weights-text { margin-top: auto; padding-top: 18px; }
|
||||||
|
.versions { margin-top: 8px; }
|
||||||
|
.versions thead td { border-bottom: 1px solid var(--rule); }
|
||||||
|
.versions thead th { color: var(--text); font-weight: 650; font-size: 13.5px; border-bottom-color: var(--rule); }
|
||||||
|
.versions th[scope="row"] { font-weight: 400; text-align: left; font-size: 13.5px; color: var(--text-2); }
|
||||||
|
@media (min-width: 761px) { .versions thead th { white-space: nowrap; } }
|
||||||
|
.learning-row .aside { margin-top: 16px; }
|
||||||
|
.learning-row .aside strong { color: var(--text); }
|
||||||
|
.learning-row .panel > .chart-table, .learning-row .panel > form { margin-top: 14px; }
|
||||||
|
.learning-watch .panel-head { margin-bottom: 8px; }
|
||||||
|
.learning-watch .aside { margin-top: auto; }
|
||||||
|
.status-pill.gain { color: var(--gain); }
|
||||||
|
.watch-list { list-style: none; margin: 0 0 14px; padding: 0; }
|
||||||
|
.watch-list li { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid var(--rule-inner); color: var(--text-2); }
|
||||||
|
.watch-list .icon { margin-top: 2px; color: var(--text-3); }
|
||||||
|
.watch-list .ok .icon { color: var(--gain); }
|
||||||
|
.watch-list .warn, .watch-list .warn .icon { color: var(--attention); }
|
||||||
|
.weekly { margin: 0 0 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); }
|
||||||
|
.weekly-box { display: grid; grid-template-columns: minmax(0, 1fr) 76px; height: 84px; margin: 12px 0 4px 6px; }
|
||||||
|
.weekly svg .bench { fill: none; stroke: var(--bench); stroke-width: 1; }
|
||||||
|
.weekly svg .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.weekly .end-dot { width: 12px; height: 12px; margin: -6px 0 0 -6px; }
|
||||||
|
.weekly-side { position: relative; font-size: 13px; }
|
||||||
|
.weekly-side strong, .weekly-side span { position: absolute; left: 14px; line-height: 15px; white-space: nowrap; }
|
||||||
|
.weekly-side strong { transform: translateY(-60%); font-weight: 650; }
|
||||||
|
.weekly-side span { color: var(--text-3); transform: translateY(-20%); font-size: 12.5px; }
|
||||||
|
.weekly-x { display: flex; justify-content: space-between; margin: 10px 76px 0 6px; }
|
||||||
|
.found { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.found li { display: flex; flex-direction: column; gap: 5px; padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.found li:last-child { border-bottom: 0; }
|
||||||
|
.found strong { font-weight: 650; }
|
||||||
|
.found-detail { color: var(--text-2); }
|
||||||
|
.found .attention { font-size: 13px; }
|
||||||
|
.learning-open .plain h3 { margin: 18px 0 4px; }
|
||||||
|
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.learning-row, .learning-row-wide { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
.overview-row-wide, .journal-columns, .news-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; }
|
||||||
|
.service-brand { display: flex; align-items: center; gap: 14px; font-size: 22px; font-weight: 650; margin-bottom: 8px; }
|
||||||
|
.service-section { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.service-section h2 { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.service-foot { color: var(--text-3); font-size: 13px; margin-top: 8px; }
|
||||||
|
.problems td:first-child { white-space: nowrap; }
|
||||||
|
|
||||||
|
/* ---- Phone (SPEC 13.4, appendix C): 390 px and below the tablet width ---- */
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.shell { display: block; padding-bottom: 76px; }
|
||||||
|
.sidebar { display: none; }
|
||||||
|
.topbar { flex-wrap: nowrap; padding: 12px 16px; }
|
||||||
|
.topbar h1, .status-line, .pill, .currency, .topbar-actions form:not(.stop-form) { display: none; }
|
||||||
|
.topbar-title { display: flex; align-items: center; gap: 14px; }
|
||||||
|
.phone-brand { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; font-size: 18px; font-weight: 650; }
|
||||||
|
.phone-bot { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 14px; }
|
||||||
|
.btn-danger { height: 44px; }
|
||||||
|
.mode-band { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: var(--info-bg); color: var(--link); font-weight: 550; font-size: 14px; }
|
||||||
|
.stale-notice { margin: 12px 16px 0; }
|
||||||
|
.page { padding: 16px; gap: 14px; }
|
||||||
|
.panel { padding: 18px; }
|
||||||
|
.head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; }
|
||||||
|
.half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; }
|
||||||
|
.half + .half { border-left: 1px solid var(--rule); }
|
||||||
|
.segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; }
|
||||||
|
.lead { margin-top: 12px; }
|
||||||
|
.big-result { gap: 12px; }
|
||||||
|
.big-number { font-size: 46px; line-height: 48px; }
|
||||||
|
.badge { font-size: 15px; padding: 4px 10px; }
|
||||||
|
.cells { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||||
|
.chart-box { grid-template-columns: minmax(0, 1fr) 80px; height: 200px; }
|
||||||
|
.legend { flex-direction: column; gap: 4px; }
|
||||||
|
.statement { font-size: 18px; line-height: 26px; margin-top: 12px; }
|
||||||
|
.columns { grid-template-columns: 1fr; }
|
||||||
|
.row { grid-template-columns: 1fr; }
|
||||||
|
.totals { padding: 18px; }
|
||||||
|
.totals-cells { grid-template-columns: 1fr 1fr; gap: 14px; }
|
||||||
|
.total-value { font-size: 22px; line-height: 28px; }
|
||||||
|
.split-legend { gap: 6px 16px; }
|
||||||
|
.account-grid { grid-template-columns: 1fr; gap: 14px; }
|
||||||
|
.account { padding: 18px; }
|
||||||
|
.account-equity { font-size: 28px; line-height: 34px; }
|
||||||
|
.positions .wide { display: none; }
|
||||||
|
.account-value .cell-change { display: inline-flex; flex-basis: 100%; }
|
||||||
|
.panel-tools { width: 100%; justify-content: space-between; }
|
||||||
|
.facts { grid-template-columns: 1fr; gap: 2px; }
|
||||||
|
.facts dd { margin-bottom: 8px; }
|
||||||
|
.panel > h2 { flex-direction: column; align-items: flex-start; gap: 4px; }
|
||||||
|
.trades-head .cells { grid-template-columns: 1fr 1fr; }
|
||||||
|
.trades { margin: 0 -18px; }
|
||||||
|
.trade-row { grid-template-columns: minmax(0, 1fr) auto 16px; gap: 4px 12px; padding: 12px 18px; }
|
||||||
|
.trade-row > span:first-child { grid-column: 1 / -1; color: var(--text-3); font-size: 13px; }
|
||||||
|
.trade-row .wide, .trade-header, .limits .wide, .filters .btn:last-child { display: none; }
|
||||||
|
.why { grid-template-columns: 1fr; padding: 4px 18px 18px; }
|
||||||
|
.filters > label:not(.search) { flex: 1 1 140px; }
|
||||||
|
.filters select { width: 100%; }
|
||||||
|
.stages { grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||||
|
.strategy { grid-template-columns: 1fr; }
|
||||||
|
.strategy > div { padding: 18px; }
|
||||||
|
.strategy > div + div { border-left: 0; border-top: 1px solid var(--rule); }
|
||||||
|
.risk-top { grid-template-columns: 1fr; gap: 14px; }
|
||||||
|
.observing { grid-template-columns: 1fr; }
|
||||||
|
.observing dt { border-bottom: 0; padding-bottom: 0; }
|
||||||
|
.observing dd { flex-direction: column; align-items: flex-start; }
|
||||||
|
.events { grid-template-columns: 1fr; }
|
||||||
|
.events dt { border-bottom: 0; padding-bottom: 0; }
|
||||||
|
.bottombar {
|
||||||
|
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
|
||||||
|
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
|
||||||
|
}
|
||||||
|
.bottom-item {
|
||||||
|
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; min-height: 52px;
|
||||||
|
border-radius: 10px; color: var(--text-2); text-decoration: none; font-size: 11.5px; line-height: 14px;
|
||||||
|
}
|
||||||
|
.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); }
|
||||||
|
.news-panel, .news-side .panel { padding: 18px; }
|
||||||
|
.news-panel > .panel-head .segmented { display: flex; width: 100%; }
|
||||||
|
.news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
|
||||||
|
.news-columns, .news-side { gap: 14px; }
|
||||||
|
.learning-head { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.learning-state h2 { font-size: 22px; line-height: 28px; }
|
||||||
|
.learning-row { gap: 14px; }
|
||||||
|
.learning-row .panel { padding: 18px; }
|
||||||
|
.calibration-box { margin-right: 0; grid-template-columns: 42px minmax(0, 1fr); }
|
||||||
|
.calibration-x { margin-right: 0; margin-left: 42px; }
|
||||||
|
.calibration-foot { margin-right: 0; }
|
||||||
|
.calibration .legend { flex-direction: row; }
|
||||||
|
.weights li { grid-template-columns: minmax(0, 150px) minmax(0, 1fr) 26px; gap: 10px; }
|
||||||
|
.chart-table summary { min-height: 44px; display: flex; align-items: center; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
// Anubis: the few behaviours the server-rendered pages need. No libraries, no requests to other servers.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// Collapsible menu, remembered on this device.
|
||||||
|
var collapse = document.querySelector("[data-collapse]");
|
||||||
|
if (collapse) {
|
||||||
|
var sync = function () {
|
||||||
|
var closed = document.documentElement.dataset.nav === "collapsed";
|
||||||
|
collapse.setAttribute("aria-expanded", closed ? "false" : "true");
|
||||||
|
collapse.setAttribute("aria-label", closed ? "Espandi il menu" : "Comprimi il menu");
|
||||||
|
};
|
||||||
|
sync();
|
||||||
|
collapse.addEventListener("click", function () {
|
||||||
|
var closed = document.documentElement.dataset.nav !== "collapsed";
|
||||||
|
if (closed) {
|
||||||
|
document.documentElement.dataset.nav = "collapsed";
|
||||||
|
} else {
|
||||||
|
delete document.documentElement.dataset.nav;
|
||||||
|
}
|
||||||
|
try { localStorage.setItem("anubis.nav", closed ? "collapsed" : "open"); } catch (e) { /* storage blocked */ }
|
||||||
|
sync();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Selects that apply at once (currency, theme).
|
||||||
|
document.querySelectorAll("select[data-autosubmit]").forEach(function (select) {
|
||||||
|
select.addEventListener("change", function () { select.form.submit(); });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Buttons that ask before acting ("Ferma tutto").
|
||||||
|
document.querySelectorAll("[data-confirm]").forEach(function (button) {
|
||||||
|
button.addEventListener("click", function (event) {
|
||||||
|
if (!window.confirm(button.getAttribute("data-confirm"))) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// First run: PostgreSQL fields only when chosen; "Prova la connessione" without leaving the page.
|
||||||
|
var wizard = document.querySelector("[data-wizard]");
|
||||||
|
if (wizard) {
|
||||||
|
var fields = wizard.querySelector("[data-postgres]");
|
||||||
|
var engines = wizard.querySelectorAll("[data-engine]");
|
||||||
|
var showFields = function () {
|
||||||
|
if (!fields) { return; }
|
||||||
|
var pg = wizard.querySelector("[data-engine]:checked");
|
||||||
|
fields.hidden = !(pg && pg.value === "postgres");
|
||||||
|
};
|
||||||
|
engines.forEach(function (radio) { radio.addEventListener("change", showFields); });
|
||||||
|
showFields();
|
||||||
|
var test = wizard.querySelector("[data-test-connection]");
|
||||||
|
var result = wizard.querySelector("[data-test-result]");
|
||||||
|
if (test && result) {
|
||||||
|
test.addEventListener("click", function (event) {
|
||||||
|
event.preventDefault();
|
||||||
|
result.textContent = "Provo…";
|
||||||
|
fetch("/azioni/primo-avvio/prova", { method: "POST", body: new FormData(wizard), credentials: "same-origin" })
|
||||||
|
.then(function (response) { return response.json(); })
|
||||||
|
.then(function (answer) { result.textContent = answer.message; result.className = "test-result " + (answer.ok ? "gain" : "loss"); })
|
||||||
|
.catch(function () { result.textContent = "Non riesco a fare la prova adesso. Riprova tra poco."; result.className = "test-result loss"; });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Live status over the WebSocket: bot state, freshness of the data, and a discreet notice when the link drops.
|
||||||
|
var age = document.querySelector("[data-live='age']");
|
||||||
|
if (!age || !("WebSocket" in window)) { return; }
|
||||||
|
|
||||||
|
var lastAge = Number(age.getAttribute("data-age")) || 0;
|
||||||
|
var lastAt = Date.now();
|
||||||
|
var lastMessage = Date.now();
|
||||||
|
var connected = false;
|
||||||
|
var retry = 1000;
|
||||||
|
var stale = document.querySelector("[data-stale]");
|
||||||
|
var staleText = document.querySelector("[data-stale-text]");
|
||||||
|
|
||||||
|
var ago = function (seconds) {
|
||||||
|
seconds = Math.max(0, Math.floor(seconds));
|
||||||
|
if (seconds < 60) { return seconds + (seconds === 1 ? " secondo fa" : " secondi fa"); }
|
||||||
|
var minutes = Math.floor(seconds / 60);
|
||||||
|
if (minutes < 60) { return minutes + (minutes === 1 ? " minuto fa" : " minuti fa"); }
|
||||||
|
var hours = Math.floor(minutes / 60);
|
||||||
|
return hours + (hours === 1 ? " ora fa" : " ore fa");
|
||||||
|
};
|
||||||
|
|
||||||
|
var tick = function () {
|
||||||
|
var seconds = lastAge + (Date.now() - lastAt) / 1000;
|
||||||
|
age.textContent = "Dati aggiornati " + ago(seconds);
|
||||||
|
var silent = (Date.now() - lastMessage) / 1000;
|
||||||
|
if (stale && (!connected || silent > 15)) {
|
||||||
|
stale.hidden = false;
|
||||||
|
staleText.textContent = "Collegamento interrotto: i dati sono fermi da " + ago(seconds).replace(" fa", "") + ". Riprovo da solo.";
|
||||||
|
} else if (stale) {
|
||||||
|
stale.hidden = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var apply = function (status) {
|
||||||
|
lastAge = status.ageSeconds;
|
||||||
|
lastAt = Date.now();
|
||||||
|
document.querySelectorAll("[data-live='bot']").forEach(function (el) { el.setAttribute("data-state", status.bot); });
|
||||||
|
document.querySelectorAll("[data-live='bot-label']").forEach(function (el) { el.textContent = status.botLabel; });
|
||||||
|
document.querySelectorAll("[data-live='bot-short']").forEach(function (el) { el.textContent = status.botShort; });
|
||||||
|
var now = document.querySelector("[data-live='now']");
|
||||||
|
if (now) { now.textContent = status.now; }
|
||||||
|
};
|
||||||
|
|
||||||
|
var connect = function () {
|
||||||
|
var socket = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws");
|
||||||
|
socket.onopen = function () { connected = true; retry = 1000; };
|
||||||
|
socket.onmessage = function (event) {
|
||||||
|
lastMessage = Date.now();
|
||||||
|
try {
|
||||||
|
var message = JSON.parse(event.data);
|
||||||
|
if (message.type === "status") { apply(message.status); }
|
||||||
|
} catch (e) { /* ignore a malformed message */ }
|
||||||
|
};
|
||||||
|
socket.onclose = function () {
|
||||||
|
connected = false;
|
||||||
|
setTimeout(connect, retry);
|
||||||
|
retry = Math.min(retry * 2, 30000);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
connect();
|
||||||
|
setInterval(tick, 1000);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// Runs before the page paints: applies the remembered menu state so the menu does not jump (SPEC 13.4).
|
||||||
|
(function () {
|
||||||
|
try {
|
||||||
|
if (localStorage.getItem("anubis.nav") === "collapsed") {
|
||||||
|
document.documentElement.dataset.nav = "collapsed";
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Storage blocked: the menu simply starts open.
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "anubis backtest base": the honest backtests of the base strategies (SPEC 12.2, issue #44). It downloads the
|
||||||
|
/// Binance daily archives (each checked against its SHA-256) and the ECB rates into the research history, converts
|
||||||
|
/// them to euro, runs the protocol of <c>crypto_trend</c> on both universes and writes reports and outcome files.
|
||||||
|
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BacktestCommand
|
||||||
|
{
|
||||||
|
private const string Usage =
|
||||||
|
"Uso: anubis backtest base [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||||
|
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||||
|
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||||
|
HttpMessageHandler? handler = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 1 || args[0] != "base")
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rest = args[1..].ToList();
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var options = ServerOptions.Parse([.. rest.Where(a => a != "--offline")], environment);
|
||||||
|
var config = options.LoadConfig(environment);
|
||||||
|
var clock = new SystemClock();
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var to = Option(rest, "--to") is { } t
|
||||||
|
? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture)
|
||||||
|
: new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last month whose archive is published.
|
||||||
|
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "backtests"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
config.Data.Ensure();
|
||||||
|
Directory.CreateDirectory(outDir);
|
||||||
|
var store = new ResearchStore(config.Data.Research);
|
||||||
|
IReadOnlyList<FxRate> rates;
|
||||||
|
using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false))
|
||||||
|
{
|
||||||
|
http.Timeout = TimeSpan.FromMinutes(5);
|
||||||
|
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||||
|
rates = await RatesAsync(new ApiHttp(http, clock, "ecb"), config.Data.Research, rest.Contains("--offline"), output).ConfigureAwait(false);
|
||||||
|
if (!rest.Contains("--offline"))
|
||||||
|
{
|
||||||
|
var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), store, clock);
|
||||||
|
foreach (var symbol in CryptoTrendProtocol.Archives)
|
||||||
|
{
|
||||||
|
var result = await importer.ImportAsync(symbol, "1d", 2017, 8, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{symbol}: {result.Bars} barre giornaliere")).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").ConfigureAwait(false);
|
||||||
|
|
||||||
|
var outcome = await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||||
|
var notes = DataNotes(outcome, rates);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.md"),
|
||||||
|
ProtocolReport.Markdown(outcome, "crypto_trend", notes, "anubis backtest base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||||
|
foreach (var run in outcome.Runs)
|
||||||
|
{
|
||||||
|
// The full reports (curve, trades) stay with the data: the repository keeps the summary and the outcome.
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, "crypto_trend-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") })
|
||||||
|
{
|
||||||
|
var waiting = EquityProtocol.Waiting(strategy);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync("Rapporti scritti in " + outDir).ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
|
||||||
|
or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The ECB history of EUR/USD, kept next to the research data so an offline run uses the same rates.</summary>
|
||||||
|
private static async Task<IReadOnlyList<FxRate>> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(researchRoot, "ecb-eurofxref-hist.zip");
|
||||||
|
if (!offline || !File.Exists(path))
|
||||||
|
{
|
||||||
|
var zip = await http.GetBytesAsync(Ecb.History, null, null, CancellationToken.None).ConfigureAwait(false)
|
||||||
|
?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true);
|
||||||
|
await File.WriteAllBytesAsync(path, zip).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(await File.ReadAllBytesAsync(path).ConfigureAwait(false)), ["USD"]);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Cambi BCE EUR/USD: {rates.Count} giorni, dal {rates[0].Date:yyyy-MM-dd} al {rates[^1].Date:yyyy-MM-dd}."))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return rates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> DataNotes(ProtocolOutcome outcome, IReadOnlyList<FxRate> rates)
|
||||||
|
{
|
||||||
|
var broad = outcome.Runs[0].Report.Instruments;
|
||||||
|
var it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
var missing = CryptoTrendProtocol.Archives.Select(EuroHistory.SymbolOf).Where(s => broad.All(i => i.Symbol != s)).ToList();
|
||||||
|
var notes = new List<string>
|
||||||
|
{
|
||||||
|
"Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.",
|
||||||
|
string.Create(it, $"Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno ({rates.Count} giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1)."),
|
||||||
|
string.Create(it, $"{broad.Count} coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni."),
|
||||||
|
"Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.",
|
||||||
|
};
|
||||||
|
if (missing.Count > 0)
|
||||||
|
{
|
||||||
|
notes.Add("Senza archivi nel periodo, quindi non usate: " + string.Join(", ", missing) + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(List<string> args, string name)
|
||||||
|
{
|
||||||
|
var index = args.IndexOf(name);
|
||||||
|
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
@if (Docker)
|
||||||
|
{
|
||||||
|
<label for="@_id">Password della configurazione d'avvio (<code>ANUBIS_ADMIN_PASSWORD</code>)</label>
|
||||||
|
<input id="@_id" name="password" type="password" autocomplete="off" required />
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6];
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public bool Docker { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@inject ShellData Shell
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="it" data-theme="@_theme">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="light dark" />
|
||||||
|
<link rel="icon" href="/favicon.ico" />
|
||||||
|
<link rel="stylesheet" href="/assets/app.css?v=@AnubisInfo.Version" />
|
||||||
|
<script src="/assets/early.js?v=@AnubisInfo.Version"></script>
|
||||||
|
<HeadOutlet />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<Routes />
|
||||||
|
<script src="/assets/app.js?v=@AnubisInfo.Version" defer></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private string? _theme;
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var snapshot = await Shell.SnapshotAsync(CancellationToken.None);
|
||||||
|
_theme = snapshot.Theme == "auto" ? null : snapshot.Theme;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
@* A small filled triangle: the direction is never told by colour alone (SPEC 13.2). *@
|
||||||
|
<svg class="arrow" width="10" height="10" viewBox="0 0 10 10" aria-hidden="true" focusable="false">
|
||||||
|
@if (Up)
|
||||||
|
{
|
||||||
|
<path d="M5 1.5 9.3 8.5H.7Z" fill="currentColor" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<path d="M5 8.5.7 1.5h8.6Z" fill="currentColor" />
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter]
|
||||||
|
public bool Up { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
@* How often it went well against what the model said (SPEC 13.4, mockup 06): one scale, 2 px lines, faint grid, the
|
||||||
|
perfect estimate beside it, direct labels on the fullest band and on the last one, a box on hover and the table.
|
||||||
|
As in EquityChart the lines are SVG stretched to the box; texts and points are HTML placed in percent. *@
|
||||||
|
@if (Bands.Count > 0)
|
||||||
|
{
|
||||||
|
var loX = Bands.Min(b => b.From) / 10 * 10;
|
||||||
|
var hiX = (Bands.Max(b => b.To) + 9) / 10 * 10;
|
||||||
|
var loY = Math.Min(loX, (int)Math.Floor(Bands.Min(b => b.Observed)) / 10 * 10) - 5m;
|
||||||
|
var hiY = Math.Max(hiX, Bands.Max(b => b.Observed)) + 4m;
|
||||||
|
var step = hiX - loX > 60 ? 20 : 10;
|
||||||
|
var fullest = Bands.MaxBy(b => b.Cases)!;
|
||||||
|
var last = Bands[^1];
|
||||||
|
decimal X(decimal v) => (v - loX) / (hiX - loX) * 1000m;
|
||||||
|
decimal Y(decimal v) => (hiY - v) / (hiY - loY) * 1000m;
|
||||||
|
<figure class="chart calibration" aria-label="Quanto spesso è andata bene, rispetto a quello che diceva il modello">
|
||||||
|
<p class="calibration-title" aria-hidden="true">…va bene davvero</p>
|
||||||
|
<div class="calibration-box">
|
||||||
|
<div class="chart-axis" aria-hidden="true">
|
||||||
|
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||||
|
{
|
||||||
|
<span style="top:@Pct(Y(t) / 10)">@t%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="chart-plot">
|
||||||
|
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||||
|
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||||
|
{
|
||||||
|
<line class="grid" x1="0" x2="1000" y1="@Css(Y(t))" y2="@Css(Y(t))" vector-effect="non-scaling-stroke" />
|
||||||
|
}
|
||||||
|
<line class="base" x1="0" x2="1000" y1="1000" y2="1000" vector-effect="non-scaling-stroke" />
|
||||||
|
<line class="bench" x1="0" y1="@Css(Y(loX))" x2="1000" y2="@Css(Y(hiX))" vector-effect="non-scaling-stroke" />
|
||||||
|
<polyline class="equity" points="@string.Join(" ", Bands.Select(b => Css(X(b.Estimated)) + "," + Css(Y(b.Observed))))" vector-effect="non-scaling-stroke" />
|
||||||
|
</svg>
|
||||||
|
@foreach (var b in Bands)
|
||||||
|
{
|
||||||
|
<span class="end-dot hover-dot" style="left:@Pct(X(b.Estimated) / 10);top:@Pct(Y(b.Observed) / 10)"><span class="hover-box">Tra @(b.From)% e @(b.To)%<br />@Format.Number(b.Observed)% su @Cases(b)</span></span>
|
||||||
|
}
|
||||||
|
<span class="point-label @(X(fullest.Estimated) > 450m ? "below-left" : "below")" style="left:@Pct(X(fullest.Estimated) / 10);top:@Pct(Y(fullest.Observed) / 10)">@Label(fullest)</span>
|
||||||
|
@if (last != fullest)
|
||||||
|
{
|
||||||
|
<span class="point-label above" style="left:@Pct(X(last.Estimated) / 10);top:@Pct(Y(last.Observed) / 10)">@Label(last)</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="calibration-x" aria-hidden="true">
|
||||||
|
@for (var t = loX; t <= hiX; t += step)
|
||||||
|
{
|
||||||
|
<span style="left:@Pct(X(t) / 10)">@t%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<p class="calibration-foot" aria-hidden="true">Quando il modello dice…</p>
|
||||||
|
<figcaption class="legend">
|
||||||
|
<span class="key key-equity">Il modello</span>
|
||||||
|
<span class="key key-bench">Stima perfetta</span>
|
||||||
|
</figcaption>
|
||||||
|
<p class="calibration-text">@Text</p>
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Vedi i numeri in una tabella</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Quando il modello dice</th><th scope="col" class="num">Casi</th><th scope="col" class="num">È andata bene</th><th scope="col">Affidabilità</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var b in Bands)
|
||||||
|
{
|
||||||
|
<tr><td>tra @(b.From)% e @(b.To)%</td><td class="num">@Format.Number(b.Cases)</td><td class="num">@Format.Number(b.Observed)%</td><td class="@(b.Solid ? null : "attention-text")">@(b.Solid ? "conta" : "troppo pochi casi per contarci")</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</figure>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public IReadOnlyList<LearningBand> Bands { get; set; } = [];
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string Text { get; set; } = "";
|
||||||
|
|
||||||
|
private static string Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {Cases(b)}";
|
||||||
|
|
||||||
|
private static string Cases(LearningBand b) => b.Cases == 1 ? "un caso" : Format.Number(b.Cases) + " casi";
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
@inject ShellData Shell
|
||||||
|
|
||||||
|
@* Equity against the "senza bot" comparison (SPEC 13.4): one scale, 2 px lines, faint grid, direct label on the last
|
||||||
|
point, legend, and the same numbers in a table. Lines are SVG stretched to the box; texts and the end point are
|
||||||
|
HTML placed in percent, so nothing gets distorted at any width. *@
|
||||||
|
@if (Points.Count >= 2)
|
||||||
|
{
|
||||||
|
var values = Points.Select(p => Value(p.Equity)).ToList();
|
||||||
|
var bench = Points.Select(p => p.Benchmark is { } b ? Value(b) : (decimal?)null).ToList();
|
||||||
|
var all = values.Concat(bench.OfType<decimal>()).ToList();
|
||||||
|
var (lo, hi, step) = Scale(all.Min(), all.Max());
|
||||||
|
double X(int i) => i * 1000.0 / (Points.Count - 1);
|
||||||
|
double Y(decimal v) => (double)((hi - v) / (hi - lo)) * 1000.0;
|
||||||
|
string Line(IEnumerable<(int I, decimal V)> pts) => string.Join(" ", pts.Select(p => Fmt(X(p.I)) + "," + Fmt(Y(p.V))));
|
||||||
|
var equityLine = Line(values.Select((v, i) => (i, v)));
|
||||||
|
var benchLine = Line(bench.Select((v, i) => (i, v)).Where(p => p.v is not null).Select(p => (p.i, p.v!.Value)));
|
||||||
|
var last = values[^1];
|
||||||
|
<figure class="chart" aria-label="@Label">
|
||||||
|
<div class="chart-box">
|
||||||
|
<div class="chart-axis" aria-hidden="true">
|
||||||
|
@for (var t = lo; t <= hi; t += step)
|
||||||
|
{
|
||||||
|
<span style="top:@Pct(Y(t) / 10)">@Format.Number(t)</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="chart-plot">
|
||||||
|
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||||
|
@for (var t = lo; t <= hi; t += step)
|
||||||
|
{
|
||||||
|
<line class="grid" x1="0" x2="1000" y1="@Fmt(Y(t))" y2="@Fmt(Y(t))" vector-effect="non-scaling-stroke" />
|
||||||
|
}
|
||||||
|
<polygon class="area" points="0,1000 @equityLine 1000,1000" />
|
||||||
|
@if (benchLine.Length > 0)
|
||||||
|
{
|
||||||
|
<polyline class="bench" points="@benchLine" vector-effect="non-scaling-stroke" />
|
||||||
|
}
|
||||||
|
<polyline class="equity" points="@equityLine" vector-effect="non-scaling-stroke" />
|
||||||
|
</svg>
|
||||||
|
@if (bench[^1] is { } lastBench)
|
||||||
|
{
|
||||||
|
// Two labels never overlap: the lower one moves down when they are closer than one line.
|
||||||
|
var gap = Math.Abs(Y(last) - Y(lastBench)) / 10;
|
||||||
|
var benchTop = gap < 7 ? Y(last) / 10 + (Y(lastBench) >= Y(last) ? 7 : -7) : Y(lastBench) / 10;
|
||||||
|
<span class="end-dot bench-dot" style="left:100%;top:@Pct(Y(lastBench) / 10)"></span>
|
||||||
|
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Text(Points[^1].Benchmark!.Value, 0)</span>
|
||||||
|
}
|
||||||
|
<span class="end-dot" style="left:100%;top:@Pct(Y(last) / 10)"></span>
|
||||||
|
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Text(Points[^1].Equity, 0)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<figcaption class="legend">
|
||||||
|
<span class="key key-equity">@EquityLabel</span>
|
||||||
|
@if (benchLine.Length > 0)
|
||||||
|
{
|
||||||
|
<span class="key key-bench">@BenchmarkLabel</span>
|
||||||
|
}
|
||||||
|
</figcaption>
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Vedi i numeri in una tabella</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">@EquityColumn</th><th scope="col" class="num">@BenchmarkColumn</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var p in Points.AsEnumerable().Reverse())
|
||||||
|
{
|
||||||
|
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Text(p.Equity)</td><td class="num">@(p.Benchmark is { } b ? Text(b) : "—")</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</figure>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public IReadOnlyList<EquityPoint> Points { get; set; } = [];
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string Currency { get; set; } = "EUR";
|
||||||
|
|
||||||
|
/// <summary>True when the amounts are already in <see cref="Currency"/> (a backtest report): no conversion from euro.</summary>
|
||||||
|
[Parameter]
|
||||||
|
public bool Native { get; set; }
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string Label { get; set; } = "Patrimonio nel tempo, con il bot e senza";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string EquityLabel { get; set; } = "Con Anubis";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string BenchmarkLabel { get; set; } = "Senza bot: Bitcoin e S&P 500 comprati e tenuti";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string EquityColumn { get; set; } = "Con il bot";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string BenchmarkColumn { get; set; } = "Senza bot";
|
||||||
|
|
||||||
|
private decimal Value(decimal amount) => Native ? amount : Shell.Convert(amount, Currency);
|
||||||
|
|
||||||
|
private string Text(decimal amount, int decimals = 2) => Native ? Format.Money(amount, Currency, decimals: decimals) : Shell.Money(amount, Currency, decimals: decimals);
|
||||||
|
|
||||||
|
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||||
|
|
||||||
|
// Round steps (1, 2, 2.5, 3, 5 times a power of ten) giving three to five grid lines.
|
||||||
|
internal static (decimal Lo, decimal Hi, decimal Step) Scale(decimal min, decimal max)
|
||||||
|
{
|
||||||
|
if (max <= min)
|
||||||
|
{
|
||||||
|
max = min + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var raw = (double)(max - min) / 4;
|
||||||
|
var power = Math.Pow(10, Math.Floor(Math.Log10(raw)));
|
||||||
|
var step = new[] { 1, 2, 2.5, 3, 5, 10 }.Select(m => m * power).First(s => s >= raw);
|
||||||
|
var stepValue = (decimal)step;
|
||||||
|
var lo = Math.Floor(min / stepValue) * stepValue;
|
||||||
|
var hi = Math.Ceiling(max / stepValue) * stepValue;
|
||||||
|
return (lo, hi == lo ? lo + stepValue : hi, stepValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
@* Line icons drawn for Anubis: 24 grid, stroke 2, round ends (appendix C). Decorative: the text next to them says it all. *@
|
||||||
|
<svg class="icon @Class" width="@Size" height="@Size" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
|
||||||
|
@switch (Name)
|
||||||
|
{
|
||||||
|
case "grid":
|
||||||
|
<rect x="3.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="3.5" y="13.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="13.5" width="7" height="7" rx="1.5" />
|
||||||
|
break;
|
||||||
|
case "card":
|
||||||
|
<rect x="3" y="5.5" width="18" height="13" rx="2.5" /><path d="M3 10h18M16 14.5h2" />
|
||||||
|
break;
|
||||||
|
case "arrows":
|
||||||
|
<path d="M5 8h14M15 4l4 4-4 4M19 16H5M9 12l-4 4 4 4" />
|
||||||
|
break;
|
||||||
|
case "layers":
|
||||||
|
<path d="M12 3 3 8l9 5 9-5-9-5Z" /><path d="m3 12.5 9 5 9-5" /><path d="m3 16.5 9 5 9-5" />
|
||||||
|
break;
|
||||||
|
case "news":
|
||||||
|
<rect x="3.5" y="4" width="17" height="16" rx="2.5" /><path d="M7.5 9h9M7.5 12.5h9M7.5 16h5" />
|
||||||
|
break;
|
||||||
|
case "network":
|
||||||
|
<circle cx="5.5" cy="5.5" r="2.2" /><circle cx="18.5" cy="5.5" r="2.2" /><circle cx="12" cy="18.5" r="2.2" /><path d="M7.5 6.5 11 16.4M16.5 6.5 13 16.4M7.7 5.5h8.6" />
|
||||||
|
break;
|
||||||
|
case "shield":
|
||||||
|
<path d="M12 3 5 6v5.5c0 4.4 3 8 7 9.5 4-1.5 7-5.1 7-9.5V6l-7-3Z" /><path d="m9 12 2.2 2.2L15.5 10" />
|
||||||
|
break;
|
||||||
|
case "list":
|
||||||
|
<path d="M9 6h11M9 12h11M9 18h11" /><circle cx="4.5" cy="6" r="0.6" /><circle cx="4.5" cy="12" r="0.6" /><circle cx="4.5" cy="18" r="0.6" />
|
||||||
|
break;
|
||||||
|
case "flask":
|
||||||
|
<path d="M9.5 3h5M10 3v6.2L4.8 18.3A1.8 1.8 0 0 0 6.4 21h11.2a1.8 1.8 0 0 0 1.6-2.7L14 9.2V3" /><path d="M7.3 15h9.4" />
|
||||||
|
break;
|
||||||
|
case "sliders":
|
||||||
|
<path d="M4 7h9M17 7h3M4 17h3M11 17h9" /><circle cx="15" cy="7" r="2" /><circle cx="9" cy="17" r="2" />
|
||||||
|
break;
|
||||||
|
case "dots":
|
||||||
|
<circle cx="5.5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="18.5" cy="12" r="1" />
|
||||||
|
break;
|
||||||
|
case "download":
|
||||||
|
<path d="M12 4v11M7 10.5l5 5 5-5M5 19.5h14" />
|
||||||
|
break;
|
||||||
|
case "collapse":
|
||||||
|
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
|
||||||
|
break;
|
||||||
|
case "expand":
|
||||||
|
<path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
|
||||||
|
break;
|
||||||
|
case "pause":
|
||||||
|
<path d="M9.5 6v12M14.5 6v12" />
|
||||||
|
break;
|
||||||
|
case "play":
|
||||||
|
<path d="M8 5.5v13l10-6.5-10-6.5Z" />
|
||||||
|
break;
|
||||||
|
case "stop":
|
||||||
|
<path d="M8.3 3h7.4L21 8.3v7.4L15.7 21H8.3L3 15.7V8.3L8.3 3Z" /><rect x="9.5" y="9.5" width="5" height="5" rx="0.6" />
|
||||||
|
break;
|
||||||
|
case "chevron":
|
||||||
|
<path d="m6 9 6 6 6-6" />
|
||||||
|
break;
|
||||||
|
case "clock":
|
||||||
|
<circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" />
|
||||||
|
break;
|
||||||
|
case "half":
|
||||||
|
<path d="M12 3.5a8.5 8.5 0 0 0 0 17Z" fill="currentColor" />
|
||||||
|
break;
|
||||||
|
case "next":
|
||||||
|
<path d="M8 3.5h1a8.5 8.5 0 0 1 0 17H8Z" />
|
||||||
|
break;
|
||||||
|
case "alert":
|
||||||
|
<path d="M12 4 2.8 19.5h18.4L12 4Z" /><path d="M12 10v4M12 17h.01" />
|
||||||
|
break;
|
||||||
|
case "info":
|
||||||
|
<circle cx="12" cy="12" r="8.5" /><path d="M12 11v5M12 8h.01" />
|
||||||
|
break;
|
||||||
|
case "check":
|
||||||
|
<circle cx="12" cy="12" r="8.5" /><path d="m8.5 12 2.4 2.4 4.6-4.8" />
|
||||||
|
break;
|
||||||
|
case "database":
|
||||||
|
<ellipse cx="12" cy="6" rx="7.5" ry="2.8" /><path d="M4.5 6v12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8V6M4.5 12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8" />
|
||||||
|
break;
|
||||||
|
case "lock":
|
||||||
|
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
|
||||||
|
break;
|
||||||
|
case "search":
|
||||||
|
<circle cx="11" cy="11" r="6.5" /><path d="m16 16 4 4" />
|
||||||
|
break;
|
||||||
|
case "ban":
|
||||||
|
<circle cx="12" cy="12" r="8.5" /><path d="m6 6 12 12" />
|
||||||
|
break;
|
||||||
|
case "tick":
|
||||||
|
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
||||||
|
break;
|
||||||
|
case "eye":
|
||||||
|
<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z" /><circle cx="12" cy="12" r="2.8" />
|
||||||
|
break;
|
||||||
|
case "logout":
|
||||||
|
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public int Size { get; set; } = 20;
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string? Class { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
@inject AnubisHost Host
|
||||||
|
@inject IClock Clock
|
||||||
|
|
||||||
|
@* SPEC 15.1: database and data folder disagree. The user chooses; Docker asks the startup password because users
|
||||||
|
and sessions live in the database that is missing, desktop accepts choices only from the computer itself. *@
|
||||||
|
@{
|
||||||
|
var verdict = Status.Identity!.Verdict;
|
||||||
|
var data = Host.Config.Data;
|
||||||
|
var docker = Host.Config.Platform == PlatformKind.Docker;
|
||||||
|
var canChoose = docker || Local;
|
||||||
|
}
|
||||||
|
|
||||||
|
@switch (verdict)
|
||||||
|
{
|
||||||
|
case IdentityVerdict.EmptyDatabase:
|
||||||
|
<p>Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento: se partisse, comincerebbe da zero e i conti risulterebbero diversi dal registro.</p>
|
||||||
|
break;
|
||||||
|
case IdentityVerdict.DifferentInstallation:
|
||||||
|
<p>Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.</p>
|
||||||
|
break;
|
||||||
|
case IdentityVerdict.StaleDatabase:
|
||||||
|
<p>È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.</p>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||||
|
<dt>Cartella dei dati</dt><dd>@data.Root</dd>
|
||||||
|
@if (Status.Identity.File is { } file)
|
||||||
|
{
|
||||||
|
<dt>Installazione della cartella</dt><dd>@file.InstallationId.ToString("D")[..8], nata il @Format.ShortDate(file.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
|
||||||
|
}
|
||||||
|
@if (Status.Identity.Row is { } row)
|
||||||
|
{
|
||||||
|
<dt>Installazione del database</dt><dd>@row.Id.ToString("D")[..8], nata il @Format.ShortDate(row.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<p class="hint">La soluzione più sicura spesso è correggere la configurazione perché punti al database giusto. Altrimenti scegli qui sotto. Dopo un ripristino o un'importazione il bot riparte protetto: "Ferma tutto" acceso finché non confermi.</p>
|
||||||
|
|
||||||
|
@if (!canChoose)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="status"><Icon Name="lock" Size="16" />Queste scelte si fanno solo dal computer su cui gira Anubis.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@if (verdict == IdentityVerdict.EmptyDatabase)
|
||||||
|
{
|
||||||
|
var backups = new Backups(data, Clock).List();
|
||||||
|
var imports = ServiceChoices.ImportFolders(data);
|
||||||
|
<section class="service-section">
|
||||||
|
<h2>Ripristina un salvataggio</h2>
|
||||||
|
@if (backups.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/servizio/ripristina" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="salvataggio">Salvataggio</label>
|
||||||
|
<select id="salvataggio" name="salvataggio">
|
||||||
|
@foreach (var backup in backups)
|
||||||
|
{
|
||||||
|
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<AdminPassword Docker="docker" />
|
||||||
|
<button class="btn btn-primary" type="submit">Ripristina</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="service-section">
|
||||||
|
<h2>Importa un archivio</h2>
|
||||||
|
@if (imports.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/servizio/importa" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="archivio">Archivio</label>
|
||||||
|
<select id="archivio" name="archivio">
|
||||||
|
@foreach (var folder in imports)
|
||||||
|
{
|
||||||
|
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<AdminPassword Docker="docker" />
|
||||||
|
<button class="btn btn-primary" type="submit">Importa</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="service-section">
|
||||||
|
<h2>Comincia da capo</h2>
|
||||||
|
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
|
||||||
|
<form method="post" action="/azioni/servizio/da-capo" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<AdminPassword Docker="docker" />
|
||||||
|
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<section class="service-section">
|
||||||
|
<h2>Usa comunque questo database</h2>
|
||||||
|
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
|
||||||
|
<form method="post" action="/azioni/servizio/usa-questo" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<AdminPassword Docker="docker" />
|
||||||
|
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public HostStatus Status { get; set; } = null!;
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public bool Local { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
@inherits LoadedLayout
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
@* The shell of SPEC 13.4: menu on the left (collapsible, remembered), top bar with state and commands, on phones a
|
||||||
|
bottom bar with five entries. Rendered on the server; app.js keeps state and freshness live over the WebSocket. *@
|
||||||
|
<div class="shell" data-shell>
|
||||||
|
<nav class="sidebar" aria-label="Menu principale">
|
||||||
|
<div class="brand">
|
||||||
|
<a class="brand-link" href="/">
|
||||||
|
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="28" height="28" />
|
||||||
|
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="28" height="28" />
|
||||||
|
<span class="brand-name">Anubis</span>
|
||||||
|
</a>
|
||||||
|
<button type="button" class="icon-button collapse" data-collapse aria-label="Comprimi il menu" aria-expanded="true">
|
||||||
|
<Icon Name="collapse" Class="when-open" /><Icon Name="expand" Class="when-closed" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
@foreach (var group in Menu.Groups)
|
||||||
|
{
|
||||||
|
<ul class="nav-group">
|
||||||
|
@foreach (var item in group)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<a class="nav-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)" title="@item.Label">
|
||||||
|
<Icon Name="@item.Icon" /><span class="nav-label">@item.Label</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="main">
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="topbar-title">
|
||||||
|
<a class="phone-brand" href="/">
|
||||||
|
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="24" height="24" />
|
||||||
|
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="24" height="24" />
|
||||||
|
<span>Anubis</span>
|
||||||
|
</a>
|
||||||
|
<span class="phone-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-short">@_shell.BotShort</span></span>
|
||||||
|
<h1>@Menu.Title(_path)</h1>
|
||||||
|
<p class="status-line">
|
||||||
|
<span data-live="now">@_shell.Now</span>. <span data-live="age" data-age="@_shell.AgeSeconds">Dati aggiornati @Format.Ago(TimeSpan.FromSeconds(_shell.AgeSeconds))</span>.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="topbar-actions">
|
||||||
|
<span class="pill pill-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-label">@_shell.BotLabel</span></span>
|
||||||
|
<span class="pill pill-mode"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</span>
|
||||||
|
<form class="currency" method="post" action="/azioni/impostazioni/appearance.currency">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="@_back" />
|
||||||
|
<label class="sr-only" for="valuta">Valuta di visualizzazione</label>
|
||||||
|
<select id="valuta" name="valore" data-autosubmit>
|
||||||
|
<option value="EUR" selected="@(_shell.Currency == "EUR")">EUR</option>
|
||||||
|
<option value="USD" selected="@(_shell.Currency == "USD")">USD</option>
|
||||||
|
</select>
|
||||||
|
<Icon Name="chevron" Size="16" Class="select-chevron" />
|
||||||
|
<noscript><button class="btn btn-small" type="submit">Cambia</button></noscript>
|
||||||
|
</form>
|
||||||
|
@if (_shell.Bot == "paused")
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
|
||||||
|
}
|
||||||
|
else if (_shell.Bot == "active")
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
|
||||||
|
}
|
||||||
|
<form class="stop-form" method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn btn-danger" type="submit" data-confirm="Ferma tutto: il bot non apre né gestisce nuove operazioni finché non lo riattivi dalla pagina Rischio. Confermi?" disabled="@(_shell.Bot == "stopped")"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div class="mode-band"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</div>
|
||||||
|
<div class="stale-notice" data-stale hidden role="status"><Icon Name="alert" Size="16" /><span data-stale-text>Collegamento interrotto.</span></div>
|
||||||
|
|
||||||
|
<main class="page" id="contenuto">
|
||||||
|
@Body
|
||||||
|
<footer class="page-footer">
|
||||||
|
@if (Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p>Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Anubis @AnubisInfo.Version</p>
|
||||||
|
}
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="bottombar" aria-label="Menu del telefono">
|
||||||
|
@foreach (var item in Menu.Phone)
|
||||||
|
{
|
||||||
|
<a class="bottom-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)">
|
||||||
|
<Icon Name="@item.Icon" Size="22" /><span>@item.Label</span>
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private ShellSnapshot _shell = null!;
|
||||||
|
private string _path = "/";
|
||||||
|
private string _back = "/";
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
_shell = await Shell.SnapshotAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
|
||||||
|
var uri = new Uri(Navigation.Uri);
|
||||||
|
_path = uri.AbsolutePath;
|
||||||
|
_back = uri.PathAndQuery;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsActive(string path) => path == "/" ? _path == "/" : _path.StartsWith(path, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
@inherits LayoutComponentBase
|
||||||
|
@inject ShellData Shell
|
||||||
|
|
||||||
|
@* Pages outside the shell: sign-in, first run, first access, error page. *@
|
||||||
|
<div class="service">
|
||||||
|
<div class="service-box">
|
||||||
|
<div class="service-brand">
|
||||||
|
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="36" height="36" />
|
||||||
|
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="36" height="36" />
|
||||||
|
<span>Anubis</span>
|
||||||
|
</div>
|
||||||
|
@Body
|
||||||
|
<p class="service-foot">Anubis @AnubisInfo.Version@(Shell.IsDemo ? " · modalità dimostrativa" : "")</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
|
||||||
|
namespace Anubis.Server.Components;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A component that reads its data before drawing anything. With static rendering, a plain <c>OnInitializedAsync</c>
|
||||||
|
/// that really waits (PostgreSQL does; SQLite answers at once) lets Blazor draw the component once with its fields
|
||||||
|
/// still empty. Here the data are loaded first, then the component renders once.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class LoadedComponent : ComponentBase
|
||||||
|
{
|
||||||
|
private bool _loaded;
|
||||||
|
|
||||||
|
public override async Task SetParametersAsync(ParameterView parameters)
|
||||||
|
{
|
||||||
|
parameters.SetParameterProperties(this);
|
||||||
|
if (!_loaded)
|
||||||
|
{
|
||||||
|
_loaded = true;
|
||||||
|
await LoadAsync().ConfigureAwait(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads what the component shows. Parameters, cascading values and query values are already set.</summary>
|
||||||
|
protected abstract Task LoadAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The same for the layout.</summary>
|
||||||
|
public abstract class LoadedLayout : LayoutComponentBase
|
||||||
|
{
|
||||||
|
private bool _loaded;
|
||||||
|
|
||||||
|
public override async Task SetParametersAsync(ParameterView parameters)
|
||||||
|
{
|
||||||
|
parameters.SetParameterProperties(this);
|
||||||
|
if (!_loaded)
|
||||||
|
{
|
||||||
|
_loaded = true;
|
||||||
|
await LoadAsync().ConfigureAwait(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc cref="LoadedComponent.LoadAsync"/>
|
||||||
|
protected abstract Task LoadAsync();
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
namespace Anubis.Server.Components;
|
||||||
|
|
||||||
|
internal sealed record MenuItem(string Path, string Label, string Icon, string Title);
|
||||||
|
|
||||||
|
/// <summary>The screens of SPEC 13.6 in the order of the mockups.</summary>
|
||||||
|
internal static class Menu
|
||||||
|
{
|
||||||
|
public static readonly MenuItem Overview = new("/", "Panoramica", "grid", "Panoramica");
|
||||||
|
public static readonly MenuItem Accounts = new("/conti", "Conti e posizioni", "card", "Conti e posizioni");
|
||||||
|
public static readonly MenuItem Trades = new("/operazioni", "Operazioni", "arrows", "Operazioni");
|
||||||
|
public static readonly MenuItem Strategies = new("/strategie", "Strategie", "layers", "Strategie");
|
||||||
|
public static readonly MenuItem News = new("/notizie", "Notizie e mercato", "news", "Notizie e mercato");
|
||||||
|
public static readonly MenuItem Learning = new("/apprendimento", "Apprendimento", "network", "Apprendimento");
|
||||||
|
public static readonly MenuItem Risk = new("/rischio", "Rischio", "shield", "Rischio");
|
||||||
|
public static readonly MenuItem Journal = new("/diario", "Diario e sistema", "list", "Diario e sistema");
|
||||||
|
public static readonly MenuItem Lab = new("/laboratorio", "Laboratorio", "flask", "Laboratorio");
|
||||||
|
public static readonly MenuItem Settings = new("/impostazioni", "Impostazioni", "sliders", "Impostazioni");
|
||||||
|
public static readonly MenuItem More = new("/altro", "Altro", "dots", "Altro");
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<IReadOnlyList<MenuItem>> Groups =
|
||||||
|
[
|
||||||
|
[Overview, Accounts, Trades],
|
||||||
|
[Strategies, News, Learning],
|
||||||
|
[Risk, Journal, Lab, Settings],
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>The bottom bar of the phone (SPEC 13.4).</summary>
|
||||||
|
public static readonly IReadOnlyList<MenuItem> Phone =
|
||||||
|
[
|
||||||
|
Overview,
|
||||||
|
Accounts with { Label = "Conti" },
|
||||||
|
Journal with { Label = "Diario" },
|
||||||
|
Risk,
|
||||||
|
More,
|
||||||
|
];
|
||||||
|
|
||||||
|
public static string Title(string path) =>
|
||||||
|
Groups.SelectMany(g => g).Append(More).FirstOrDefault(i => i.Path == "/" ? path == "/" : path.StartsWith(i.Path, StringComparison.Ordinal))?.Title ?? "Anubis";
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
@page "/accesso"
|
||||||
|
@layout ServiceLayout
|
||||||
|
@attribute [AllowAnonymous]
|
||||||
|
|
||||||
|
<PageTitle>Accesso · Anubis</PageTitle>
|
||||||
|
|
||||||
|
<h1>Accedi</h1>
|
||||||
|
@if (Message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
<form method="post" action="/azioni/accesso" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="@(Ritorno is { } r && Forms.IsLocalPath(r) ? r : "/")" />
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus />
|
||||||
|
@if (Fattore == "1")
|
||||||
|
{
|
||||||
|
<label for="codice">Codice dell'app di autenticazione</label>
|
||||||
|
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||||
|
<p class="hint">Sei cifre, cambiano ogni 30 secondi. Scrivi di nuovo anche la password.</p>
|
||||||
|
}
|
||||||
|
<button class="btn btn-primary" type="submit">Accedi</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "minuti")]
|
||||||
|
public string? Minuti { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "fattore")]
|
||||||
|
public string? Fattore { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ritorno")]
|
||||||
|
public string? Ritorno { get; set; }
|
||||||
|
|
||||||
|
private string? Message => Errore switch
|
||||||
|
{
|
||||||
|
"password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.",
|
||||||
|
"codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.",
|
||||||
|
"attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/altro"
|
||||||
|
@inject ShellData Shell
|
||||||
|
|
||||||
|
<PageTitle>Altro · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@* On the phone: the screens that do not fit the bottom bar, the pause and the currency (SPEC 13.4). *@
|
||||||
|
<section class="panel">
|
||||||
|
<ul class="more-list">
|
||||||
|
@foreach (var item in Menu.Groups.SelectMany(g => g).Where(i => !Menu.Phone.Any(p => p.Path == i.Path)))
|
||||||
|
{
|
||||||
|
<li><a href="@item.Path"><Icon Name="@item.Icon" />@item.Label</a></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section class="panel">
|
||||||
|
<h2>Comandi</h2>
|
||||||
|
<div class="form-inline">
|
||||||
|
@if (_shell.Bot == "active")
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
|
||||||
|
}
|
||||||
|
else if (_shell.Bot == "paused")
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
|
||||||
|
}
|
||||||
|
<form method="post" action="/azioni/impostazioni/appearance.currency">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/altro" />
|
||||||
|
<input type="hidden" name="valore" value="@(_shell.Currency == "EUR" ? "USD" : "EUR")" />
|
||||||
|
<button class="btn" type="submit">Mostra in @(_shell.Currency == "EUR" ? "dollari" : "euro")</button>
|
||||||
|
</form>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/esci"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private ShellSnapshot _shell = null!;
|
||||||
|
|
||||||
|
protected override async Task LoadAsync() => _shell = await Shell.SnapshotAsync(CancellationToken.None);
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/apprendimento"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@using Anubis.Learning
|
||||||
|
|
||||||
|
<PageTitle>Apprendimento · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var s = v.Summary;
|
||||||
|
var c = _currency;
|
||||||
|
}
|
||||||
|
<p class="lead page-lead">Il modello impara dall'esito di ogni segnale.</p>
|
||||||
|
@if (Ok == "promozione")
|
||||||
|
{
|
||||||
|
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />Promozione annullata: è tornata in carica la versione precedente.</p>
|
||||||
|
}
|
||||||
|
else if (Errore is not null)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@(Errore == "motore" ? "Nella modalità dimostrativa non si cambia nulla." : "Non c'è nessuna promozione da annullare.")</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel head-block learning-head" aria-labelledby="stato">
|
||||||
|
<div class="half learning-state">
|
||||||
|
<span class="state-badge @(s.State is LearningStates.Aside or LearningStates.Manual ? "warn" : s.State == LearningStates.Active ? "on" : null)"><Icon Name="@BadgeIcon(s.State)" Size="16" />@Badge(s.State)</span>
|
||||||
|
<h2 id="stato">@v.Title</h2>
|
||||||
|
<p class="learning-text">@v.Text</p>
|
||||||
|
@if (s.State != LearningStates.None)
|
||||||
|
{
|
||||||
|
<div class="limit learning-progress">
|
||||||
|
@if (s.Signals < s.Needed)
|
||||||
|
{
|
||||||
|
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@s.Signals</strong> <span class="muted">su @s.Needed necessari</span></span></div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@Format.Number(s.Signals)</strong> <span class="muted">(ne servivano @s.Needed)</span></span></div>
|
||||||
|
}
|
||||||
|
<span class="usage"><span style="width: @Css(Math.Min(100m, s.Signals * 100m / Math.Max(1, s.Needed)))%"></span></span>
|
||||||
|
@if (v.Pace is { } pace)
|
||||||
|
{
|
||||||
|
<span class="note">@pace</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (v.Missing.Count > 0)
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var m in v.Missing)
|
||||||
|
{
|
||||||
|
<li class="wait"><Icon Name="clock" Size="16" />@m</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (s.State == LearningStates.Manual)
|
||||||
|
{
|
||||||
|
<p><a href="/impostazioni#modello">Vai a Impostazioni</a></p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<dl class="half learning-facts">
|
||||||
|
<div>
|
||||||
|
<dt>Previsioni azzeccate su casi mai visti</dt>
|
||||||
|
<dd class="learning-precision">@(s.Precision is { } precision ? precision + "%" : "—")</dd>
|
||||||
|
<dd class="note">@(s.Precision is null ? "Si misura al primo addestramento" : "Tirando a caso sarebbe il 50%")</dd>
|
||||||
|
</div>
|
||||||
|
<div><dt>Ultimo addestramento</dt><dd><strong>@Capital(v.LastTraining)</strong></dd></div>
|
||||||
|
<div><dt>@s.NextLabel</dt><dd><strong>@Capital(s.NextCheck)</strong></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="learning-row">
|
||||||
|
<section class="panel" aria-labelledby="fiducia">
|
||||||
|
<h2 id="fiducia">Ci si può fidare delle sue probabilità?</h2>
|
||||||
|
@if (v.Bands.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">@v.BandsText Qui vedrai quante volte va bene davvero quando il modello dice che una cosa è probabile.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Più i punti stanno sulla linea, più la stima corrisponde ai fatti.@(v.BandsFromHistory ? " Per ora sono i casi storici che non aveva studiato: quelli dal vivo sono ancora troppo pochi." : "")</p>
|
||||||
|
<CalibrationChart Bands="v.Bands" Text="@v.BandsText" />
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel learning-weights" aria-labelledby="indizi">
|
||||||
|
<h2 id="indizi">Cosa guarda di più</h2>
|
||||||
|
@if (v.Champion is null)
|
||||||
|
{
|
||||||
|
<p class="note">Si vedrà con il primo modello.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Quanto pesa ogni informazione nelle sue stime, su 100.</p>
|
||||||
|
@if (v.Weights.Count > 0)
|
||||||
|
{
|
||||||
|
var most = v.Weights.Max(w => w.Share);
|
||||||
|
<ul class="weights">
|
||||||
|
@foreach (var w in v.Weights)
|
||||||
|
{
|
||||||
|
<li class="@(w.Rest ? "rest" : null)"><span>@w.Name</span><span class="weight-bar" aria-hidden="true"><span style="width: @Css(w.Share * 100m / most)%"></span></span><strong>@w.Share</strong></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<p class="note weights-text">@v.WeightsText</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="learning-row learning-row-wide">
|
||||||
|
<section class="panel" aria-labelledby="versioni">
|
||||||
|
<h2 id="versioni">Il modello in carica e lo sfidante</h2>
|
||||||
|
<p class="note">Lo sfidante gira in ombra accanto al modello in carica. Ne prende il posto solo se è chiaramente migliore.</p>
|
||||||
|
@if (v.Champion is { } now)
|
||||||
|
{
|
||||||
|
var other = v.Challenger;
|
||||||
|
var same = other is null || other.GainWithout == now.GainWithout;
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table versions">
|
||||||
|
<thead><tr><td></td><th scope="col" class="num">In carica, versione @now.Version</th>@if (other is not null){<th scope="col" class="num">Sfidante, versione @other.Version</th>}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row">Addestrato</th><td class="num">@now.Trained</td>@if (other is not null){<td class="num">@other.Trained</td>}</tr>
|
||||||
|
<tr><th scope="row">Casi studiati</th><td class="num">@Format.Number(now.Examples)</td>@if (other is not null){<td class="num">@Format.Number(other.Examples)</td>}</tr>
|
||||||
|
<tr><th scope="row">Previsioni azzeccate su casi mai visti</th><td class="num"><strong>@Share(now.Precision)</strong></td>@if (other is not null){<td class="num"><strong>@Share(other.Precision)</strong></td>}</tr>
|
||||||
|
<tr><th scope="row">Errore sulle probabilità <span class="muted">(più basso è meglio)</span></th><td class="num">@Error(now.Error)</td>@if (other is not null){<td class="num">@Error(other.Error)</td>}</tr>
|
||||||
|
<tr><th scope="row">Guadagno medio per operazione se filtrasse lui @if (same && now.GainWithout is { } without){<span class="muted">(senza filtro: @Shell.Money(without, c, withSign: true))</span>}</th>
|
||||||
|
<td class="num">@Gain(now, same, c)</td>@if (other is not null){<td class="num">@Gain(other, same, c)</td>}</tr>
|
||||||
|
@if (other is not null)
|
||||||
|
{
|
||||||
|
<tr><th scope="row">Casi di confronto diretto</th><td class="num muted">non serve</td><td class="num">@Format.Number(v.Pairs) su @v.PairsNeeded</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (v.GainOnReference)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna strategia con capitale affidato ha ancora casi: il guadagno è calcolato su tutte, con il capitale di riferimento.</p>
|
||||||
|
}
|
||||||
|
<p class="aside"><strong>@v.TrialTitle</strong> @v.TrialText</p>
|
||||||
|
@if (v.Choice is { } choice)
|
||||||
|
{
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Come è stato scelto il modello in carica</summary>
|
||||||
|
<p class="note">@choice Sono tutte prove su casi che il modello non aveva studiato; contano anche quelle scartate.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Tipo di modello</th><th scope="col" class="num">Previsioni azzeccate</th><th scope="col" class="num">Errore</th><th scope="col" class="num">Guadagno per operazione</th><th scope="col">Esito</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var a in v.Attempts)
|
||||||
|
{
|
||||||
|
<tr><td>@a.Learner</td><td class="num">@Share(a.Precision)</td><td class="num">@Error(a.Error)</td><td class="num nowrap">@Shell.Money(a.Gain, c, withSign: true)</td><td>@(a.Chosen ? "scelto" : "non scelto")</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
@if (v.UndoTo is { } back && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn" type="submit" data-confirm="Torna in carica la versione @back e la versione @v.Champion!.Version viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||||
|
<span class="hint">Tornerebbe in carica la versione @back.</span>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel learning-watch" aria-labelledby="sorveglianza">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="sorveglianza">Sorveglianza</h2>
|
||||||
|
@if (v.Checked)
|
||||||
|
{
|
||||||
|
<span class="status-pill @(v.Anomaly ? "attention" : "gain")"><Icon Name="@(v.Anomaly ? "alert" : "check")" Size="16" />@(v.Anomaly ? "Anomalia" : "Nessuna anomalia")</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (!v.Checked)
|
||||||
|
{
|
||||||
|
<p class="note">Il controllo gira ogni notte alle 03:00: confronta le stime con gli esiti e il mercato di oggi con quello su cui ha studiato.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="watch-list">
|
||||||
|
@foreach (var check in v.Checks)
|
||||||
|
{
|
||||||
|
<li class="@check.State"><Icon Name="@(check.State switch { "ok" => "tick", "warn" => "alert", _ => "clock" })" Size="16" /><span>@check.Text</span></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<WeeklyPrecision Weeks="v.Weeks" />
|
||||||
|
}
|
||||||
|
<p class="aside">Se la precisione cala, il modello viene messo da parte da solo e le strategie proseguono senza di lui.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="learning-row learning-open">
|
||||||
|
<section class="plain" aria-labelledby="imparato">
|
||||||
|
<h2 id="imparato">Cosa ha imparato finora</h2>
|
||||||
|
@if (v.Found.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Ancora niente: le relazioni tra indizi ed esiti si cercano ogni notte, quando i casi bastano per un confronto.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="found">
|
||||||
|
@foreach (var d in v.Found)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<strong>@d.Title</strong>
|
||||||
|
<span class="found-detail">@d.Detail</span>
|
||||||
|
<span class="@(d.Cases < 20 ? "attention" : "note")">@if (d.Cases < 20){<Icon Name="alert" Size="16" />}@(d.Cases == 1 ? "Un caso" : Format.Number(d.Cases) + " casi"): @d.Trust</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (v.News.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Cosa succede ai prezzi dopo una notizia</h3>
|
||||||
|
<p class="note">Rendimento medio dalla prima chiusura dopo la notizia. È solo un'informazione: non cambia nessuna regola.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Tipo di notizia</th><th scope="col" class="num">Dopo 1 giorno</th><th scope="col" class="num">Dopo 5 giorni</th><th scope="col">Casi</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var n in v.News)
|
||||||
|
{
|
||||||
|
<tr><td>@NewsEventNames.Label(n.Kind)</td><td class="num">@Move(n.OneDay)</td><td class="num">@Move(n.FiveDays)</td><td class="@(n.Cases < 20 ? "attention-text" : null)">@n.Cases: @n.Trust</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="plain" aria-labelledby="storia">
|
||||||
|
<h2 id="storia">Storia</h2>
|
||||||
|
@if (v.Story.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">La storia comincia con il primo modello.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Story.Take(LearningView.StoryRows))
|
||||||
|
{
|
||||||
|
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
@if (v.Story.Count > LearningView.StoryRows)
|
||||||
|
{
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Mostra i @(v.Story.Count - LearningView.StoryRows) eventi precedenti</summary>
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Story.Skip(LearningView.StoryRows))
|
||||||
|
{
|
||||||
|
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private LearningView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
_currency = Shell.Effective((await Host.Services!.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await LearningView.LoadAsync(Host, Shell, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Gain(LearningVersion version, bool same, string currency) => version.Gain is not { } gain ? "—"
|
||||||
|
: Shell.Money(gain, currency, withSign: true) + (same || version.GainWithout is not { } without ? "" : $" (senza: {Shell.Money(without, currency, withSign: true)})");
|
||||||
|
|
||||||
|
private static string Badge(string state) => state switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "Non ancora partito",
|
||||||
|
LearningStates.Active => "Attivo",
|
||||||
|
LearningStates.Aside => "Messo da parte",
|
||||||
|
LearningStates.Manual => "Messo da parte da te",
|
||||||
|
_ => "In osservazione",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string BadgeIcon(string state) => state switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "clock",
|
||||||
|
LearningStates.Active => "check",
|
||||||
|
LearningStates.Aside => "alert",
|
||||||
|
LearningStates.Manual => "pause",
|
||||||
|
_ => "eye",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Share(int? points) => points is { } p ? p + "%" : "—";
|
||||||
|
|
||||||
|
private static string Error(decimal? value) => value is { } e ? Format.Number(e, 3) : "—";
|
||||||
|
|
||||||
|
private static string Move(double value) => Format.Percent((decimal)Math.Round(value * 100, 2), 2, withSign: true);
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
@@ -0,0 +1,414 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/conti"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
@using Anubis.Data
|
||||||
|
|
||||||
|
<PageTitle>Conti e posizioni · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
}
|
||||||
|
@if (!v.HasAccounts)
|
||||||
|
{
|
||||||
|
<Pending Title="Nessun conto ancora.">Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova dei broker compaiono quando ne aggiungi le chiavi in <a href="/impostazioni#conti">Impostazioni</a>.</Pending>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@if (_message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice @(_ok ? "notice-gain" : "notice-loss")" role="status"><Icon Name="@(_ok ? "check" : "alert")" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
var shares = Format.Shares([.. v.Slices.Select(s => s.Eur), v.CashEur]);
|
||||||
|
var winners = v.Positions.Count(p => p.ResultEur >= 0);
|
||||||
|
<section class="panel totals" aria-label="Totale dei conti">
|
||||||
|
<div class="totals-cells">
|
||||||
|
<div class="cell">
|
||||||
|
<span class="cell-label">Totale dei conti</span>
|
||||||
|
<span class="total-value">@Shell.Money(v.TotalEur, c)</span>
|
||||||
|
<span class="cell-change @(v.ResultEur >= 0 ? "gain" : "loss")"><Arrow Up="v.ResultEur >= 0" />@Shell.Money(v.ResultEur, c, withSign: true) dall'avvio</span>
|
||||||
|
</div>
|
||||||
|
<div class="cell">
|
||||||
|
<span class="cell-label">Investito</span>
|
||||||
|
<span class="total-value">@Shell.Money(v.InvestedEur, c)</span>
|
||||||
|
<span class="cell-note">@Format.Percent(Part(v.InvestedEur, v.TotalEur)) del totale</span>
|
||||||
|
</div>
|
||||||
|
<div class="cell">
|
||||||
|
<span class="cell-label">Liquidità</span>
|
||||||
|
<span class="total-value">@Shell.Money(v.CashEur, c)</span>
|
||||||
|
<span class="cell-note">@Format.Percent(Part(v.CashEur, v.TotalEur)) del totale</span>
|
||||||
|
</div>
|
||||||
|
<div class="cell">
|
||||||
|
<span class="cell-label">Risultato delle posizioni aperte</span>
|
||||||
|
<span class="total-value">@Shell.Money(v.OpenResultEur, c, withSign: true)</span>
|
||||||
|
<span class="cell-note">@(v.Positions.Count == 0 ? "Nessuna posizione aperta" : $"{winners} in guadagno, {v.Positions.Count - winners} in perdita")</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="split-bar" role="img" aria-label="Divisione del totale tra strategie e liquidità">
|
||||||
|
@for (var i = 0; i < v.Slices.Count; i++)
|
||||||
|
{
|
||||||
|
if (shares[i] > 0)
|
||||||
|
{
|
||||||
|
<span style="width: @Css(shares[i])%; background: @v.Slices[i].Color"></span>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (shares[^1] > 0)
|
||||||
|
{
|
||||||
|
<span style="width: @Css(shares[^1])%; background: var(--cash)"></span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<ul class="split-legend">
|
||||||
|
@for (var i = 0; i < v.Slices.Count; i++)
|
||||||
|
{
|
||||||
|
<li><span class="swatch" style="background: @v.Slices[i].Color"></span>@v.Slices[i].Label <strong>@Format.Percent(shares[i])</strong></li>
|
||||||
|
}
|
||||||
|
<li><span class="swatch" style="background: var(--cash)"></span>Liquidità <strong>@Format.Percent(shares[^1])</strong></li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="account-grid">
|
||||||
|
@foreach (var a in v.Accounts)
|
||||||
|
{
|
||||||
|
var state = a.State;
|
||||||
|
var up = a.Result >= 0;
|
||||||
|
var usd = a.Currency == "USD";
|
||||||
|
<section class="panel account" aria-label="@a.Name">
|
||||||
|
<div class="account-head">
|
||||||
|
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
|
||||||
|
<span class="link-state @(state.LastOutcome == ReconcileOutcomes.Unreachable ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
|
||||||
|
</div>
|
||||||
|
<div class="account-value">
|
||||||
|
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
|
||||||
|
@if (usd)
|
||||||
|
{
|
||||||
|
<span class="account-native">@Format.Money(a.Equity, "USD")</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>
|
||||||
|
<dl class="account-lines">
|
||||||
|
<dt>Liquidità in @(usd ? "dollari" : "euro")</dt>
|
||||||
|
<dd><strong>@Shell.Money(a.Eur(a.Cash), c)</strong>@if (usd) {<span class="native"> @Format.Money(a.Cash, "USD")</span>}</dd>
|
||||||
|
<dt>Investito in @Holdings(a)</dt>
|
||||||
|
<dd><strong>@Shell.Money(a.InvestedEur, c)</strong>@if (usd) {<span class="native"> @Format.Money(a.Invested, "USD")</span>}</dd>
|
||||||
|
<dt>Guadagni già incassati</dt>
|
||||||
|
<dd><strong>@Shell.Money(a.Eur(a.Realized), c, withSign: true)</strong></dd>
|
||||||
|
<dt>Guadagni sulle posizioni aperte</dt>
|
||||||
|
<dd><strong>@Shell.Money(a.Eur(a.Unrealized), c, withSign: true)</strong></dd>
|
||||||
|
<dt>Commissioni pagate</dt>
|
||||||
|
<dd><strong>@Shell.Money(a.Eur(a.Fees), c)</strong></dd>
|
||||||
|
</dl>
|
||||||
|
@if (state.IsPrudent)
|
||||||
|
{
|
||||||
|
<div class="notice notice-attention prudent">
|
||||||
|
<Icon Name="alert" Size="16" />
|
||||||
|
<div>
|
||||||
|
@if (state.ModeReason == Reconciler.KeyReason)
|
||||||
|
{
|
||||||
|
<p>La chiave di questo conto permette i prelievi: niente nuovi acquisti finché non la sostituisci con una senza prelievo in <a href="/impostazioni#conti">Impostazioni</a>. Vendite e stop proseguono.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Modalità prudente dalle @Time(state.ModeSince): niente nuovi acquisti, vendite e stop proseguono.</p>
|
||||||
|
<ul class="differences">
|
||||||
|
@foreach (var d in state.Differences)
|
||||||
|
{
|
||||||
|
<li>@d.Message</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p>Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:</p>
|
||||||
|
<div class="choices">
|
||||||
|
<form method="post" action="/azioni/conti/@a.Id/allinea"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Il registro prende i numeri del conto, con una riga di rettifica che resta nel diario. Confermi?">Allinea il registro al conto</button></form>
|
||||||
|
<form method="post" action="/azioni/conti/@a.Id/escludi"><AntiforgeryToken /><button class="btn btn-small" type="submit">Lascia fuori ciò che non è del bot</button></form>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Se entro 15 minuti si spiega da sola il conto torna normale; altrimenti qui potrai scegliere se allineare il registro o lasciare fuori la differenza.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<ul class="account-facts">
|
||||||
|
@if (a.Environment == TradingEnvironments.Simulation)
|
||||||
|
{
|
||||||
|
<li><Icon Name="flask" Size="16" />Simulazione interna: prezzi veri, ordini finti</li>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<li><Icon Name="flask" Size="16" />Conto di prova del broker: ordini veri su denaro finto</li>
|
||||||
|
}
|
||||||
|
@if (state.KeyCanWithdraw == true)
|
||||||
|
{
|
||||||
|
<li class="loss"><Icon Name="alert" Size="16" />La chiave permette i prelievi: va sostituita</li>
|
||||||
|
}
|
||||||
|
else if (state.KeyCheckedAt is not null)
|
||||||
|
{
|
||||||
|
<li><Icon Name="check" Size="16" />La chiave può solo leggere e fare ordini: i prelievi sono disattivati</li>
|
||||||
|
}
|
||||||
|
@if (usd)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />@(v.MarketOpen ? $"Mercato aperto: chiude alle {Time(v.MarketNext)}." : $"Mercato chiuso: apre alle {Time(v.MarketNext)}.") @RateText(v, withSource: false)</li>
|
||||||
|
}
|
||||||
|
@if (state.LastReconciledAt is null)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />Primo controllo con il registro entro 5 minuti</li>
|
||||||
|
}
|
||||||
|
else if (state.LastOutcome is ReconcileOutcomes.Different)
|
||||||
|
{
|
||||||
|
<li class="attention"><Icon Name="alert" Size="16" />Differenza tra conto e registro (controllo delle @Time(state.LastReconciledAt))</li>
|
||||||
|
}
|
||||||
|
else if (state.LastOutcome is ReconcileOutcomes.Unreachable)
|
||||||
|
{
|
||||||
|
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo tentativo alle @Time(state.LastReconciledAt))</li>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<li><Icon Name="check" Size="16" />@(a.Environment == TradingEnvironments.Simulation ? "Registro interno coerente" : "Conto e registro interno coincidono") (controllo delle @Time(state.LastReconciledAt))</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
var shownPositions = v.Positions.Where(p => _filter is null || p.Broker == _filter).ToList();
|
||||||
|
<section class="panel" aria-labelledby="posizioni">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="posizioni">Posizioni aperte</h2>
|
||||||
|
<div class="panel-tools">
|
||||||
|
<nav class="segmented" aria-label="Conto">
|
||||||
|
<a href="/conti" class="@(_filter is null ? "on" : null)" aria-current="@(_filter is null ? "true" : null)">Tutti i conti</a>
|
||||||
|
@foreach (var a in v.Accounts)
|
||||||
|
{
|
||||||
|
<a href="/conti?conto=@a.Broker" class="@(_filter == a.Broker ? "on" : null)" aria-current="@(_filter == a.Broker ? "true" : null)">@a.Name</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
<a class="btn" href="/api/conti/posizioni.csv@(_filter is null ? "" : "?conto=" + _filter)" download><Icon Name="download" Size="18" />Esporta CSV</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (shownPositions.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna posizione aperta@(_filter is null ? "" : " su questo conto").</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table positions">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Strumento</th>
|
||||||
|
<th scope="col" class="wide">Conto</th>
|
||||||
|
<th scope="col" class="wide">Strategia</th>
|
||||||
|
<th scope="col" class="num wide">Quantità</th>
|
||||||
|
<th scope="col" class="num wide">Prezzo medio</th>
|
||||||
|
<th scope="col" class="num wide">Prezzo ora</th>
|
||||||
|
<th scope="col" class="num">Valore</th>
|
||||||
|
<th scope="col" class="num">Risultato</th>
|
||||||
|
<th scope="col" class="num wide">Stop</th>
|
||||||
|
<th scope="col" class="num wide">Aperta da</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var p in shownPositions)
|
||||||
|
{
|
||||||
|
var gain = p.ResultEur >= 0;
|
||||||
|
<tr>
|
||||||
|
<th scope="row"><strong>@p.Symbol</strong> <span class="muted">@p.Name</span></th>
|
||||||
|
<td class="wide">@(p.Broker == Venues.Alpaca ? "Alpaca" : "OKX")</td>
|
||||||
|
<td class="nowrap wide"><span class="swatch round" style="background: var(--s-@p.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(p.Strategy)</td>
|
||||||
|
<td class="num wide">@Format.Quantity(p.Quantity)</td>
|
||||||
|
<td class="num wide">@Format.Money(p.Average, p.Currency)</td>
|
||||||
|
<td class="num wide">@Format.Money(p.Last, p.Currency)</td>
|
||||||
|
<td class="num"><strong>@Shell.Money(p.ValueEur, c)</strong></td>
|
||||||
|
<td class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(p.ResultEur, c, withSign: true)<span class="cell-extra"> (@Format.Percent(p.Percent, 2, withSign: true))</span></strong></td>
|
||||||
|
<td class="num wide">@(p.Stop is { } stop ? Format.Money(stop, p.Currency, decimals: AccountsView.StopDecimals(stop)) : "—")</td>
|
||||||
|
<td class="num wide nowrap">@Age(p.OpenedAt)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<th scope="row">Totale</th>
|
||||||
|
<td class="wide"></td><td class="wide"></td><td class="wide"></td><td class="wide"></td><td class="wide"></td>
|
||||||
|
<td class="num"><strong>@Shell.Money(shownPositions.Sum(p => p.ValueEur), c)</strong></td>
|
||||||
|
<td class="num @(shownPositions.Sum(p => p.ResultEur) >= 0 ? "gain" : "loss")"><strong>@Shell.Money(shownPositions.Sum(p => p.ResultEur), c, withSign: true)</strong></td>
|
||||||
|
<td class="wide"></td><td class="wide"></td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="columns">
|
||||||
|
<section class="panel" aria-labelledby="ordini">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="ordini">Ordini in attesa</h2>
|
||||||
|
<span class="note">@(v.PendingOthers == 0 ? (v.Pending.Count == 0 ? "Nessun ordine aperto" : "Solo stop di protezione: nessun acquisto in coda") : $"{v.PendingOthers} {(v.PendingOthers == 1 ? "ordine" : "ordini")} in corso oltre agli stop")</span>
|
||||||
|
</div>
|
||||||
|
@if (v.Pending.Count > 0)
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table pending">
|
||||||
|
<thead><tr><th scope="col">Ordine</th><th scope="col">Dove</th><th scope="col" class="num">Scatta a</th><th scope="col">Stato</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var o in v.Pending)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<th scope="row">@o.Action <strong>@o.Subject</strong></th>
|
||||||
|
<td>@o.Where</td>
|
||||||
|
<td class="num @(o.Level == "vedi tabella sopra" ? "muted" : null)">@o.Level</td>
|
||||||
|
<td><span class="order-state">@if (o.Waiting) {<Icon Name="clock" Size="16" />} else {<span class="dot"></span>}@o.Status</span></td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (v.AlpacaStops)
|
||||||
|
{
|
||||||
|
<p class="aside">Le azioni intere hanno uno stop permanente sul broker, che resta attivo anche a bot spento. Sulle frazioni il broker accetta solo ordini che valgono un giorno: quelli li rimetto a ogni apertura e, a mercato chiuso, li sorveglio io.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="valute">
|
||||||
|
<h2 id="valute">In quale valuta sono i soldi</h2>
|
||||||
|
@{
|
||||||
|
var dollars = v.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity));
|
||||||
|
var euros = v.TotalEur - dollars;
|
||||||
|
var parts = Format.Shares([dollars, euros]);
|
||||||
|
}
|
||||||
|
<div class="split-bar slim" role="img" aria-label="Dollari @Format.Percent(parts[0]), euro @Format.Percent(parts[1])">
|
||||||
|
@if (parts[0] > 0) {<span style="width: @Css(parts[0])%; background: var(--text-2)"></span>}
|
||||||
|
@if (parts[1] > 0) {<span style="width: @Css(parts[1])%; background: var(--cash)"></span>}
|
||||||
|
</div>
|
||||||
|
<dl class="currency-lines">
|
||||||
|
<dt><span class="swatch" style="background: var(--text-2)"></span>Dollari (conto Alpaca)</dt><dd><strong>@Shell.Money(dollars, c)</strong> <span class="muted">@Format.Percent(parts[0])</span></dd>
|
||||||
|
<dt><span class="swatch" style="background: var(--cash)"></span>Euro e crypto (conto OKX)</dt><dd><strong>@Shell.Money(euros, c)</strong> <span class="muted">@Format.Percent(parts[1])</span></dd>
|
||||||
|
</dl>
|
||||||
|
<p class="note">@RateText(v)@(v.FxEffect is { } fx && fx != 0 ? $" Effetto del cambio sul risultato in euro: {Format.Money(fx, "EUR", withSign: true)}." : "")</p>
|
||||||
|
@if (dollars > 0)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention fx-warning"><Icon Name="alert" Size="16" />Se il dollaro perde il 5% sull'euro, il totale scende di circa @Format.Money(Math.Round(dollars * 0.05m), "EUR", decimals: 0) anche a prezzi fermi.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (v.Residues.Count > 0)
|
||||||
|
{
|
||||||
|
<section class="panel" aria-labelledby="residui">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="residui">Residui sotto il minimo vendibile</h2>
|
||||||
|
<span class="note">Restano sul conto ma non sono più del bot: tolti dal registro al valore di mercato</span>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Strumento</th><th scope="col">Conto</th><th scope="col" class="num">Quantità</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Dal</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var r in v.Residues)
|
||||||
|
{
|
||||||
|
<tr><th scope="row">@r.Symbol</th><td>@r.Broker</td><td class="num">@Format.Quantity(r.Quantity)</td><td class="num">@Format.Money(r.Value, r.Currency)</td><td class="num">@Format.ShortDate(r.At, Shell.Now, Shell.Zone, withTime: false)</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private AccountsView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
private string? _filter;
|
||||||
|
private string? _message;
|
||||||
|
private bool _ok;
|
||||||
|
private Dictionary<Guid, int>? _latency;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "conto")]
|
||||||
|
public string? Conto { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await AccountsView.LoadAsync(services, Clock, Shell.Zone, ct);
|
||||||
|
_filter = Conto is Venues.Okx or Venues.Alpaca ? Conto : null;
|
||||||
|
(_message, _ok) = (Ok, Errore) switch
|
||||||
|
{
|
||||||
|
("allinea", _) => ("Fatto: il registro ha preso i numeri del conto e il conto è tornato normale.", true),
|
||||||
|
("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true),
|
||||||
|
(_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false),
|
||||||
|
(_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false),
|
||||||
|
(_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false),
|
||||||
|
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
|
||||||
|
_ => (null, false),
|
||||||
|
};
|
||||||
|
using var aggregates = Shell.Aggregates();
|
||||||
|
if (aggregates is not null)
|
||||||
|
{
|
||||||
|
var names = aggregates.RootElement.GetProperty("conti").EnumerateArray().Select(x => x.GetProperty("risposta_ms").GetInt32()).ToList();
|
||||||
|
_latency = _view.Accounts.Select((a, i) => (a.Id, i)).Where(x => x.i < names.Count).ToDictionary(x => x.Id, x => names[x.i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Connection(AccountCard a)
|
||||||
|
{
|
||||||
|
if (a.State.LastOutcome == ReconcileOutcomes.Unreachable)
|
||||||
|
{
|
||||||
|
return "Il broker non risponde";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_latency?.GetValueOrDefault(a.Id) is > 0 and var ms)
|
||||||
|
{
|
||||||
|
return $"Connesso, risposta in {ms} ms";
|
||||||
|
}
|
||||||
|
|
||||||
|
return a.Environment == TradingEnvironments.Simulation ? "Attivo, nel simulatore" : "Connesso";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Holdings(AccountCard a) => (a.Broker, a.Holdings) switch
|
||||||
|
{
|
||||||
|
(_, 0) => "nulla",
|
||||||
|
(Venues.Alpaca, 1) => "1 azione",
|
||||||
|
(Venues.Alpaca, var n) => $"{n} azioni",
|
||||||
|
(_, 1) => "1 moneta",
|
||||||
|
(_, var n) => $"{n} monete",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string RateText(AccountsView v, bool withSource = true) => v.UsdRate is { } rate
|
||||||
|
? $"Cambio usato: 1 € = {Format.Quantity(rate)} $" + (withSource ? $" (BCE, {AccountsView.DayMonth(new DateTimeOffset(v.RateDay!.Value.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero))})." : ".")
|
||||||
|
: "Manca ancora il cambio euro/dollaro della BCE: i dollari restano nella loro valuta.";
|
||||||
|
|
||||||
|
private static decimal Part(decimal part, decimal total) => total == 0 ? 0 : part / total * 100m;
|
||||||
|
|
||||||
|
private static string Css(decimal percent) => percent.ToString("0.###", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private string Time(DateTimeOffset? moment) => moment is { } m ? TimeZoneInfo.ConvertTime(m, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture) : "—";
|
||||||
|
|
||||||
|
private string Age(DateTimeOffset opened)
|
||||||
|
{
|
||||||
|
var days = (int)Math.Floor((Shell.Now - opened).TotalDays);
|
||||||
|
return days switch
|
||||||
|
{
|
||||||
|
< 1 => "oggi",
|
||||||
|
1 => "1 giorno",
|
||||||
|
_ => $"{days} giorni",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/diario"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
|
||||||
|
<PageTitle>Diario e sistema · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
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 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>
|
||||||
|
}
|
||||||
|
@if (d.IsEmpty && d.Search is null)
|
||||||
|
{
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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 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 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 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;
|
||||||
|
_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 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,854 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/impostazioni"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject SecondFactorDrafts Drafts
|
||||||
|
@inject Anubis.Core.IClock Clock
|
||||||
|
@using Anubis.Data
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
|
<PageTitle>Impostazioni · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@* SPEC 13.5: appearance, accounts and keys, data, security, system. The other sections arrive with their phases. *@
|
||||||
|
@if (Ok is { } ok)
|
||||||
|
{
|
||||||
|
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />@(ok switch
|
||||||
|
{
|
||||||
|
"password" => "Password cambiata. Le altre sessioni sono state chiuse.",
|
||||||
|
"due-fattori" => "Secondo fattore attivato.",
|
||||||
|
"due-fattori-tolti" => "Secondo fattore disattivato.",
|
||||||
|
"salvataggio" => "Salvataggio fatto.",
|
||||||
|
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
|
||||||
|
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
|
||||||
|
"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.",
|
||||||
|
"fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.",
|
||||||
|
"chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.",
|
||||||
|
"chiave-tolta" => "Chiave tolta.",
|
||||||
|
"apprendimento" => "Impostazioni del modello salvate: valgono dalle prossime operazioni. Quelle già rimpicciolite restano così fino alla chiusura.",
|
||||||
|
"promozione" => "Promozione annullata: è tornata in carica la versione precedente.",
|
||||||
|
|
||||||
|
_ => "Fatto.",
|
||||||
|
})</p>
|
||||||
|
}
|
||||||
|
@if (ErrorText is { } error)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@error</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<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="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#modello">Modello</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<section class="panel" id="aspetto">
|
||||||
|
<h2>Aspetto</h2>
|
||||||
|
@foreach (var setting in _appearance)
|
||||||
|
{
|
||||||
|
var definition = SettingsStore.Definition(setting.Key);
|
||||||
|
<form method="post" action="/azioni/impostazioni/@setting.Key" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni#aspetto" />
|
||||||
|
<label for="@setting.Key">@definition.Label</label>
|
||||||
|
<select id="@setting.Key" name="valore" disabled="@setting.ReadOnly" data-autosubmit>
|
||||||
|
@foreach (var value in definition.Allowed!)
|
||||||
|
{
|
||||||
|
<option value="@value" selected="@(value == setting.Value)">@Label(value)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
@if (setting.ReadOnly)
|
||||||
|
{
|
||||||
|
<span class="hint">Fissato da @setting.Source: si cambia lì.</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<button class="btn btn-small" type="submit">Salva</button>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
<p class="hint">Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="conti">
|
||||||
|
<h2>Conti e chiavi</h2>
|
||||||
|
<p class="hint">In questa fase uso solo denaro finto: il simulatore interno è sempre acceso e, con le chiavi dei conti di prova, le strategie passano ai conti di prova dei broker. Le chiavi di conti veri non servono e non vanno inserite.</p>
|
||||||
|
@foreach (var b in _brokers)
|
||||||
|
{
|
||||||
|
<h3>@b.Title</h3>
|
||||||
|
<dl class="facts">
|
||||||
|
@foreach (var k in b.Keys)
|
||||||
|
{
|
||||||
|
<dt>@k.Label</dt><dd>@KeyState(k.Status)</dd>
|
||||||
|
}
|
||||||
|
@if (b.State is { KeyCheckedAt: { } checkedAt } state)
|
||||||
|
{
|
||||||
|
<dt>Permessi</dt>
|
||||||
|
<dd class="@(state.KeyCanWithdraw == true ? "loss" : null)">@(state.KeyCanWithdraw == true ? "Permette i prelievi: va sostituita, intanto niente nuovi acquisti" : state.KeyCanTrade == true ? "Legge e fa ordini, nessun prelievo" : "Solo lettura") (verificati @Inline(Format.ShortDate(checkedAt, Shell.Now, Shell.Zone)))</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
@if (Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p class="hint">Nella modalità dimostrativa chiavi e capitale non si cambiano.</p>
|
||||||
|
}
|
||||||
|
else if (b.Keys.Any(k => k.Status.FromEnvironment))
|
||||||
|
{
|
||||||
|
<p class="hint">Le chiavi arrivano dalle variabili d'ambiente e valgono più di quelle salvate qui: si cambiano nella configurazione del container.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/chiavi/@b.Broker" class="form" autocomplete="off">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@foreach (var k in b.Keys)
|
||||||
|
{
|
||||||
|
<label for="k-@k.Name">@k.Label</label>
|
||||||
|
<input id="k-@k.Name" name="@k.Name" type="password" autocomplete="off" spellcheck="false" maxlength="512" required />
|
||||||
|
}
|
||||||
|
<button class="btn" type="submit">Verifica e salva</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint">Non le rimostro mai. Prima di salvarle chiedo al broker cosa possono fare: una chiave che permette i prelievi la rifiuto. Dopo il salvataggio il motore riparte da solo, in pochi secondi.</p>
|
||||||
|
@if (b.Keys.Any(k => k.Status.IsSet))
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/chiavi/@b.Broker/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Tolgo le chiavi di @b.Short? Le posizioni sul conto di prova restano lì, ma il bot non le segue più finché non le rimetti.">Togli le chiavi</button></form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<h4>Capitale affidato a @b.Short</h4>
|
||||||
|
@if (b.Entrusted is { } e)
|
||||||
|
{
|
||||||
|
<p>@Format.Money(e.AmountEur, "EUR")@(e.Currency == "EUR" ? "" : $", cioè {Format.Money(e.Amount, e.Currency)} al cambio di {Format.Quantity(e.FxRate)}"), deciso @Inline(Format.ShortDate(e.At, Shell.Now, Shell.Zone)) da @e.ChangedBy.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Nessun capitale affidato: le strategie di @b.Short osservano soltanto.</p>
|
||||||
|
}
|
||||||
|
@if (b.Strategies.Count > 0)
|
||||||
|
{
|
||||||
|
<ul class="plain">
|
||||||
|
@foreach (var s in b.Strategies)
|
||||||
|
{
|
||||||
|
<li>@StrategyNames.Label(s.Strategy, withMarket: true): quota @Format.Percent(s.Share * 100m, 0), capitale @Format.Money(s.Capital, s.Currency), liquidità @Format.Money(s.Cash, s.Currency)</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/capitale/@b.Broker" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="euro-@b.Broker">Nuovo importo in euro</label>
|
||||||
|
<input id="euro-@b.Broker" name="euro" inputmode="decimal" autocomplete="off" value="@(b.Entrusted is { } cur ? Format.Quantity(cur.AmountEur) : "")" required />
|
||||||
|
<button class="btn btn-small" type="submit">Salva</button>
|
||||||
|
</form>
|
||||||
|
<p class="hint">Si divide tra le strategie del conto secondo le quote@(b.Broker == Venues.Alpaca ? ", in dollari al cambio BCE del giorno" : ""). Ridurlo non vende nulla: se una strategia ha investito più di quanto le resterebbe, aspetto che venda.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="rischio">
|
||||||
|
<h2>Rischio</h2>
|
||||||
|
<p class="note">I limiti valgono per tutte le strategie insieme. Abbassarli è sempre possibile. @(_anyLive ? "Una strategia usa soldi veri: per alzarne uno servono la frase e la password." : "Finché nessuna strategia usa soldi veri, puoi anche alzarli.")</p>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/rischio/limiti" class="form-grid limits-form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@foreach (var l in _limits)
|
||||||
|
{
|
||||||
|
<label>@l.Label<input name="@l.Key" value="@l.Value" inputmode="decimal" autocomplete="off" readonly="@l.ReadOnly" /></label>
|
||||||
|
}
|
||||||
|
@if (_anyLive)
|
||||||
|
{
|
||||||
|
<label>Per alzare un limite scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
}
|
||||||
|
<button class="btn" type="submit">Salva i limiti</button>
|
||||||
|
</form>
|
||||||
|
<h3>Protezione day trade</h3>
|
||||||
|
<form method="post" action="/azioni/rischio/@Anubis.Risk.RiskSettings.PdtGuard.Key" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="pdt">Per un conto Alpaca sotto i 25.000 $: al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
|
||||||
|
<select id="pdt" name="valore" data-autosubmit>
|
||||||
|
<option value="off" selected="@(_pdt == "off")">Spenta</option>
|
||||||
|
<option value="on" selected="@(_pdt == "on")">Accesa</option>
|
||||||
|
</select>
|
||||||
|
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||||
|
</form>
|
||||||
|
<h3>Scenari «Se succedesse domani»</h3>
|
||||||
|
<form method="post" action="/azioni/rischio/@Anubis.Risk.Scenarios.Setting.Key" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="scenari">Uno per riga: descrizione; variazione delle crypto %; delle azioni USA %; del dollaro sull'euro %. Per esempio «Le crypto perdono il 20% in un giorno; -20; 0; 0».</label>
|
||||||
|
<textarea id="scenari" name="valore" rows="5" spellcheck="false">@_scenarios</textarea>
|
||||||
|
<button class="btn" type="submit">Salva gli scenari</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="facts">
|
||||||
|
@foreach (var l in _limits)
|
||||||
|
{
|
||||||
|
<dt>@l.Label</dt><dd>@l.Value</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
</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>
|
||||||
|
@if (Host.Services!.MarketData is not { } market)
|
||||||
|
{
|
||||||
|
<p class="note">@(Shell.IsDemo ? "Nella modalità dimostrativa i dati di mercato non si scaricano." : "La raccolta dei dati di mercato è spenta (ANUBIS_MARKET_DATA).")</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Prezzi crypto in diretta</dt><dd>@(market.LiveConnected ? "collegati" : "non collegati")</dd>
|
||||||
|
<dt>Ultimo giro dello storico</dt><dd>@(market.LastHistoryRun is { } run ? Format.ShortDate(run, Shell.Now, Shell.Zone) : "in corso o non ancora fatto")</dd>
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
@if (_sources.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Fonti</h3>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Fonte</th><th scope="col">Stato</th><th scope="col">Ultima risposta</th><th scope="col">Note</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var s in _sources)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td>@SourceName(s.Source)</td>
|
||||||
|
<td>@(!s.Enabled ? "spenta" : s.LastError is null ? "attiva" : "in errore")</td>
|
||||||
|
<td class="nowrap">@(s.LastSuccessAt is { } at ? Format.ShortDate(at, Shell.Now, Shell.Zone) : "—")</td>
|
||||||
|
<td>@(s.LastError ?? s.Note)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<p class="hint"><a href="/api/data/quality?format=md&days=30">Rapporto sulla qualità dei dati degli ultimi 30 giorni</a></p>
|
||||||
|
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="notizie">
|
||||||
|
<h2>Notizie e calendario</h2>
|
||||||
|
<p class="hint">Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.</p>
|
||||||
|
|
||||||
|
<h3>Regole</h3>
|
||||||
|
@foreach (var rule in _newsRules)
|
||||||
|
{
|
||||||
|
var definition = SettingsStore.Definition(rule.Key);
|
||||||
|
<form method="post" action="/azioni/impostazioni/@rule.Key" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||||
|
<label for="@rule.Key">@definition.Label</label>
|
||||||
|
<select id="@rule.Key" name="valore" disabled="@(rule.ReadOnly || Shell.IsDemo)" data-autosubmit>
|
||||||
|
<option value="on" selected="@(rule.Value != "off")">Accesa</option>
|
||||||
|
<option value="off" selected="@(rule.Value == "off")">Spenta</option>
|
||||||
|
</select>
|
||||||
|
@if (rule.ReadOnly)
|
||||||
|
{
|
||||||
|
<span class="hint">Fissato da @rule.Source: si cambia lì.</span>
|
||||||
|
}
|
||||||
|
else if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>Fonti delle notizie</h3>
|
||||||
|
@if (_newsSources.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Le fonti compaiono qui dopo il primo giro delle notizie, che parte con i dati di mercato.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="hint">Una notizia da una sola fonte non affidabile non cambia nulla finché un'altra fonte non la conferma.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Fonte</th><th scope="col">Leggo</th><th scope="col">Affidabile</th><th scope="col">Ultima lettura</th><th scope="col">Stato</th><th scope="col"><span class="sr-only">Salva</span></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var f in _newsSources)
|
||||||
|
{
|
||||||
|
var form = "fonte-" + f.Id.ToString("N");
|
||||||
|
<tr>
|
||||||
|
<td>@f.Name</td>
|
||||||
|
<td><input type="checkbox" name="attiva" form="@form" checked="@f.Enabled" disabled="@Shell.IsDemo" aria-label="Leggo @f.Name" /></td>
|
||||||
|
<td><input type="checkbox" name="affidabile" form="@form" checked="@f.Trusted" disabled="@Shell.IsDemo" aria-label="@f.Name è affidabile" /></td>
|
||||||
|
<td class="nowrap">@(f.LastOkAt is { } at ? Format.ShortDate(at, Shell.Now, Shell.Zone) : "—")</td>
|
||||||
|
<td>@(!f.Enabled ? "spenta" : f.LastError is { } problem ? "non risponde: " + problem : "risponde")</td>
|
||||||
|
<td>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form id="@form" method="post" action="/azioni/notizie/fonti/@f.Id"><AntiforgeryToken /><button class="btn btn-small" type="submit">Salva</button></form>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>Modello linguistico</h3>
|
||||||
|
<p class="hint">Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.</p>
|
||||||
|
@DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico")
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.Provider.Key, "servizio", "Servizio", null)
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.Model.Key, "modello", "Modello", null)
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.Address.Key, "indirizzo", "Indirizzo (vuoto per quello solito del servizio)", null)
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.PriceIn.Key, "prezzo-letti", "Dollari per milione di token letti", 4)
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.PriceOut.Key, "prezzo-scritti", "Dollari per milione di token scritti", 4)
|
||||||
|
@ModelSetting(Anubis.News.NewsModelSettings.DailyCap.Key, "tetto", "Tetto di spesa al giorno (€)", 2)
|
||||||
|
<p class="note">I prezzi in dollari li conto come euro: la spesa calcolata è un po' più alta di quella vera, mai più bassa. Il tetto vale da mezzanotte a mezzanotte; prima di ogni richiesta controllo che anche il caso peggiore ci stia dentro.</p>
|
||||||
|
|
||||||
|
<h3>Calendario</h3>
|
||||||
|
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
|
||||||
|
@DataKey("FINNHUB_API_KEY", "Chiave di Finnhub")
|
||||||
|
@DataKey("FRED_API_KEY", "Chiave di FRED")
|
||||||
|
<h3>Riunioni di Fed e BCE</h3>
|
||||||
|
<form method="post" action="/azioni/impostazioni/@SettingsStore.CentralBankMeetings.Key" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||||
|
<label for="riunioni">Un giorno di decisione per riga, per esempio «FED 2027-01-27» o «BCE 2027-02-04». Aggiungi le date del nuovo anno quando le banche le pubblicano.</label>
|
||||||
|
<textarea id="riunioni" name="valore" rows="8" spellcheck="false" readonly="@_meetings.ReadOnly">@_meetings.Value</textarea>
|
||||||
|
<button class="btn" type="submit">Salva l'elenco</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="modello">
|
||||||
|
<h2>Modello</h2>
|
||||||
|
<p class="hint">Il modello non compra mai e non ingrandisce niente: quando avrà superato le sue prove potrà solo rimpicciolire, o non fare, un acquisto che giudica debole. Quanto debole lo decidi qui, in punti di probabilità sotto la frequenza con cui la strategia guadagna di solito. <a href="/apprendimento">Cosa sta facendo</a></p>
|
||||||
|
<form method="post" action="/azioni/modello" class="form-grid">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@foreach (var m in _model)
|
||||||
|
{
|
||||||
|
var definition = SettingsStore.Definition(m.Key);
|
||||||
|
<label>@ModelLabel(m.Key)
|
||||||
|
<select name="@m.Key" disabled="@(m.ReadOnly || Shell.IsDemo)">
|
||||||
|
@foreach (var choice in definition.Allowed!)
|
||||||
|
{
|
||||||
|
<option value="@choice" selected="@(choice == m.Value)">@ModelChoice(m.Key, choice)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
@if (m.ReadOnly)
|
||||||
|
{
|
||||||
|
<span class="hint">Fissato da @m.Source: si cambia lì.</span>
|
||||||
|
}
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
@if (_anyLive)
|
||||||
|
{
|
||||||
|
<p class="note">Una strategia usa soldi veri: per rimpicciolire meno, o mettere da parte il modello, servono la frase e la password.</p>
|
||||||
|
<label>Scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
}
|
||||||
|
<button class="btn" type="submit">Salva</button>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
<h3>Ultima promozione</h3>
|
||||||
|
@if (_undoTo is { } undo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni" />
|
||||||
|
<button class="btn" type="submit" data-confirm="Torna in carica la versione @undo e quella di adesso viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||||
|
<span class="hint">Tornerebbe in carica la versione @undo.</span>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna promozione da annullare.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="sicurezza">
|
||||||
|
<h2>Sicurezza</h2>
|
||||||
|
@if (Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p class="hint">Nella modalità dimostrativa password e secondo fattore non si cambiano.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<h3>Password</h3>
|
||||||
|
<form method="post" action="/azioni/password" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="attuale">Password attuale</label>
|
||||||
|
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
|
||||||
|
<label for="nuova">Nuova password</label>
|
||||||
|
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
<label for="conferma">Scrivila di nuovo</label>
|
||||||
|
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
<button class="btn" type="submit">Cambia password</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<h3>Secondo fattore</h3>
|
||||||
|
@if (_hasSecondFactor)
|
||||||
|
{
|
||||||
|
<p>Attivo: all'accesso chiedo anche il codice dell'app. Servirà anche per attivare i soldi veri.</p>
|
||||||
|
<form method="post" action="/azioni/due-fattori/disattiva" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="password-2fa">Per disattivarlo: password</label>
|
||||||
|
<input id="password-2fa" name="password" type="password" autocomplete="current-password" required />
|
||||||
|
<label for="codice-2fa">Codice dell'app</label>
|
||||||
|
<input id="codice-2fa" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||||
|
<button class="btn" type="submit">Disattiva il secondo fattore</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Facoltativo: un codice di sei cifre da un'app di autenticazione (per esempio quella del tuo gestore di password), oltre alla password.</p>
|
||||||
|
<ol class="steps">
|
||||||
|
<li>Nell'app scegli "aggiungi con chiave" e scrivi questa chiave: <code class="secret">@_draft</code></li>
|
||||||
|
<li>Oppure, se l'app accetta un indirizzo, usa: <code class="secret">@_draftUri</code></li>
|
||||||
|
<li>Scrivi qui il codice che l'app mostra.</li>
|
||||||
|
</ol>
|
||||||
|
<form method="post" action="/azioni/due-fattori/attiva" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="codice">Codice</label>
|
||||||
|
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||||
|
<button class="btn" type="submit">Attiva il secondo fattore</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
<form method="post" action="/azioni/esci" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="sistema">
|
||||||
|
<h2>Sistema</h2>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")</dd>
|
||||||
|
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||||
|
<dt>Cartella dei dati</dt><dd>@Host.Config.Data.Root</dd>
|
||||||
|
<dt>Chiave dei segreti</dt><dd>@Host.Config.SecretKey.Description</dd>
|
||||||
|
<dt>Fuso orario</dt><dd>@Host.Config.TimeZone.Id</dd>
|
||||||
|
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
|
||||||
|
</dl>
|
||||||
|
<p class="hint">
|
||||||
|
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||||
|
{
|
||||||
|
@:Motore e connessione del database si cambiano solo nella configurazione del container.
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@:Motore e connessione del database stanno in config.toml, nella cartella dei dati. Lo spostamento su un altro database arriva con l'applicazione desktop.
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h3>Salvataggi</h3>
|
||||||
|
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
|
||||||
|
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
|
||||||
|
@if (_backups.Count > 0)
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Perché</th><th scope="col">Cartella</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var b in _backups)
|
||||||
|
{
|
||||||
|
<tr><td class="nowrap">@Format.ShortDate(b.TakenAt, Shell.Now, Shell.Zone)</td><td>@b.Reason</td><td><code>@b.Name</code></td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="modifiche">
|
||||||
|
<h2>Registro delle modifiche</h2>
|
||||||
|
@if (_history.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna modifica finora.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Voce</th><th scope="col">Prima</th><th scope="col">Dopo</th><th scope="col">Chi</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var h in _history)
|
||||||
|
{
|
||||||
|
<tr><td class="nowrap">@Format.ShortDate(h.At, Shell.Now, Shell.Zone)</td><td>@h.Key</td><td>@Label(h.OldValue)</td><td>@Label(h.NewValue)</td><td>@h.ChangedBy</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private readonly List<SettingValue> _appearance = [];
|
||||||
|
private readonly List<BrokerSetup> _brokers = [];
|
||||||
|
|
||||||
|
private sealed record BrokerKey(string Name, string Label, SecretStatus Status);
|
||||||
|
|
||||||
|
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
||||||
|
IReadOnlyList<StrategyCapital> Strategies);
|
||||||
|
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
|
||||||
|
private readonly List<LimitField> _limits = [];
|
||||||
|
private bool _anyLive;
|
||||||
|
private string _pdt = "off";
|
||||||
|
private string _scenarios = "";
|
||||||
|
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
||||||
|
|
||||||
|
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||||
|
private readonly List<SettingValue> _newsRules = [];
|
||||||
|
private readonly List<SettingValue> _model = [];
|
||||||
|
private int? _undoTo;
|
||||||
|
private readonly Dictionary<string, SettingValue> _llm = [];
|
||||||
|
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
|
||||||
|
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
|
||||||
|
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;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Theme.Key, ct));
|
||||||
|
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Currency.Key, ct));
|
||||||
|
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||||
|
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||||
|
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||||
|
foreach (var rule in Anubis.News.NewsRuleSettings.All)
|
||||||
|
{
|
||||||
|
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var setting in Anubis.Learning.LearningSettings.All)
|
||||||
|
{
|
||||||
|
_model.Add(await services.Settings.GetAsync(setting.Key, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
_undoTo = Shell.IsDemo ? null : await new Anubis.Learning.ModelStore(services.Db).UndoToAsync(ct);
|
||||||
|
foreach (var setting in Anubis.News.NewsModelSettings.All)
|
||||||
|
{
|
||||||
|
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
|
||||||
|
}
|
||||||
|
_newsSources = await new Anubis.News.NewsStore(services.Db, Clock).ListSourcesAsync(ct);
|
||||||
|
foreach (var name in Forms.DataKeys)
|
||||||
|
{
|
||||||
|
_dataKeys[name] = await services.Secrets.StatusAsync(name, ct);
|
||||||
|
}
|
||||||
|
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||||
|
{
|
||||||
|
var value = await services.Settings.GetAsync(definition.Key, ct);
|
||||||
|
_limits.Add(new LimitField(definition.Key, definition.Label, value.Value, value.ReadOnly));
|
||||||
|
}
|
||||||
|
|
||||||
|
_pdt = (await services.Settings.GetAsync(Anubis.Risk.RiskSettings.PdtGuard.Key, ct)).Value;
|
||||||
|
_scenarios = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, ct)).Value;
|
||||||
|
_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);
|
||||||
|
foreach (var (broker, title, name) in new[] { (Venues.Okx, "OKX Europe · conto demo", "OKX"), (Venues.Alpaca, "Alpaca · conto di prova (paper)", "Alpaca") })
|
||||||
|
{
|
||||||
|
var keys = new List<BrokerKey>();
|
||||||
|
foreach (var (secret, label) in TradingService.KeyFields(broker))
|
||||||
|
{
|
||||||
|
keys.Add(new BrokerKey(secret, label, await services.Secrets.StatusAsync(secret, ct)));
|
||||||
|
}
|
||||||
|
|
||||||
|
var demoAccount = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts WHERE broker = @b AND environment = 'demo'", r => (Guid?)r.Id("id"), ("b", broker)), ct);
|
||||||
|
var state = demoAccount is { } id ? await reconciler.StateAsync(id, ct) : null;
|
||||||
|
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct)));
|
||||||
|
}
|
||||||
|
var user = HttpContext!.User;
|
||||||
|
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
|
||||||
|
if (!_hasSecondFactor && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
var secret = Drafts.For(CurrentUser.Session(user));
|
||||||
|
_draft = Base32.Encode(secret);
|
||||||
|
_draftUri = Totp.Uri("Anubis", AccessStore.AdminName, secret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? ErrorText => Errore switch
|
||||||
|
{
|
||||||
|
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
|
||||||
|
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
|
||||||
|
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
|
||||||
|
"impostazione" => "Questa impostazione non si può cambiare così.",
|
||||||
|
"riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».",
|
||||||
|
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||||
|
"motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.",
|
||||||
|
"conto" => "Conto sconosciuto.",
|
||||||
|
"ambiente" => "Le chiavi di questo conto arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.",
|
||||||
|
"chiavi-vuote" => "Servono tutti i campi della chiave.",
|
||||||
|
"chiavi-rifiutate" => "Il broker non ha accettato la chiave, o non ha risposto. Controlla di aver copiato la chiave del conto di prova e riprova. Non ho salvato nulla.",
|
||||||
|
"prelievo" => "Questa chiave permette i prelievi: non la salvo. Creane una senza il permesso di prelievo.",
|
||||||
|
"sola-lettura" => "Questa chiave può solo leggere: per lavorare sul conto di prova serve anche il permesso di fare ordini. Non l'ho salvata.",
|
||||||
|
"importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.",
|
||||||
|
"cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.",
|
||||||
|
"capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.",
|
||||||
|
"limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.",
|
||||||
|
"ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.",
|
||||||
|
"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.",
|
||||||
|
"fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.",
|
||||||
|
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
|
||||||
|
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
|
||||||
|
"promozione" => "Non c'è nessuna promozione da annullare.",
|
||||||
|
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
|
||||||
|
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
|
||||||
|
|
||||||
|
_ => PasswordMessages.For(Errore),
|
||||||
|
};
|
||||||
|
|
||||||
|
// A key of SPEC 13.5 that is not a broker's: its state, a field to replace it, a button to take it away. Never the value.
|
||||||
|
// One setting of the language model: a choice for the service, a field for the others; amounts shown in Italian.
|
||||||
|
private RenderFragment ModelSetting(string key, string id, string label, int? decimals)
|
||||||
|
{
|
||||||
|
var definition = SettingsStore.Definition(key);
|
||||||
|
var value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null);
|
||||||
|
var locked = value.ReadOnly || Shell.IsDemo;
|
||||||
|
var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value;
|
||||||
|
var provider = _llm.GetValueOrDefault(Anubis.News.NewsModelSettings.Provider.Key)?.Value ?? Anubis.News.NewsModelProviders.Anthropic;
|
||||||
|
return @<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||||
|
<label for="@id">@label</label>
|
||||||
|
@if (definition.Allowed is { } choices)
|
||||||
|
{
|
||||||
|
<select id="@id" name="valore" disabled="@locked" data-autosubmit>
|
||||||
|
@foreach (var choice in choices)
|
||||||
|
{
|
||||||
|
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
@if (!locked)
|
||||||
|
{
|
||||||
|
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<input id="@id" name="valore" inputmode="@(decimals is null ? "text" : "decimal")" autocomplete="off" spellcheck="false" value="@shown"
|
||||||
|
placeholder="@(key == Anubis.News.NewsModelSettings.Address.Key ? Anubis.News.NewsModelProviders.DefaultAddress(provider).ToString() : null)"
|
||||||
|
readonly="@locked" required="@(key != Anubis.News.NewsModelSettings.Address.Key)" />
|
||||||
|
@if (!locked)
|
||||||
|
{
|
||||||
|
<button class="btn btn-small" type="submit">Salva</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (value.ReadOnly)
|
||||||
|
{
|
||||||
|
<span class="hint">Fissato da @value.Source: si cambia lì.</span>
|
||||||
|
}
|
||||||
|
</form>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ModelLabel(string key) => key == Anubis.Learning.LearningSettings.Full.Key ? "Acquisto intero fino a"
|
||||||
|
: key == Anubis.Learning.LearningSettings.Zero.Key ? "Nessun acquisto da" : "Il modello";
|
||||||
|
|
||||||
|
private static string ModelChoice(string key, string choice) => key == Anubis.Learning.LearningSettings.Aside.Key
|
||||||
|
? choice == "on" ? "Messo da parte: non conta" : "Al suo posto"
|
||||||
|
: choice == "0" ? "Solo alla frequenza di sempre o sopra" : choice + " punti sotto";
|
||||||
|
|
||||||
|
private static string ProviderName(string provider) => provider switch
|
||||||
|
{
|
||||||
|
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
|
||||||
|
Anubis.News.NewsModelProviders.OpenAi => "Compatibile con OpenAI",
|
||||||
|
Anubis.News.NewsModelProviders.Ollama => "Ollama, sul tuo computer o in rete",
|
||||||
|
_ => provider,
|
||||||
|
};
|
||||||
|
|
||||||
|
private RenderFragment DataKey(string name, string label)
|
||||||
|
{
|
||||||
|
var status = _dataKeys.GetValueOrDefault(name) ?? new SecretStatus(name, false, false, null);
|
||||||
|
var id = "k-" + name.ToLowerInvariant();
|
||||||
|
return @<div class="data-key">
|
||||||
|
<p><strong>@label</strong>: @KeyState(status).</p>
|
||||||
|
@if (status.FromEnvironment)
|
||||||
|
{
|
||||||
|
<p class="hint">Si cambia nella configurazione del container (@name).</p>
|
||||||
|
}
|
||||||
|
else if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/chiavi-dati/@name" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="@id">@(status.IsSet ? "Nuova chiave" : "Chiave")</label>
|
||||||
|
<input id="@id" name="chiave" type="password" autocomplete="off" spellcheck="false" maxlength="512" required />
|
||||||
|
<button class="btn btn-small" type="submit">Salva</button>
|
||||||
|
</form>
|
||||||
|
@if (status.IsSet)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/chiavi-dati/@name/togli" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn btn-small btn-danger" type="submit" data-confirm="Tolgo la chiave: quello che la usa smette di funzionare finché non ne metti un'altra. Confermi?">Togli la chiave</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string KeyState(SecretStatus status) => status switch
|
||||||
|
{
|
||||||
|
{ FromEnvironment: true } => "Dalle variabili d'ambiente",
|
||||||
|
{ IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)),
|
||||||
|
{ IsSet: true } => "Impostata",
|
||||||
|
_ => "Non impostata",
|
||||||
|
};
|
||||||
|
|
||||||
|
// "Oggi 08:20" inside a sentence reads "oggi 08:20".
|
||||||
|
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||||
|
|
||||||
|
private static string SourceName(string source) => source switch
|
||||||
|
{
|
||||||
|
"okx" => "OKX Europe (crypto)",
|
||||||
|
"alpaca" => "Alpaca (azioni, conto di prova)",
|
||||||
|
"storico" => "Storico giornaliero delle crypto",
|
||||||
|
"storico_azioni" => "Storico giornaliero delle azioni",
|
||||||
|
"binance" => "Archivi Binance (ricerca)",
|
||||||
|
"ecb" => "Cambi della BCE",
|
||||||
|
"forexfactory" => "Calendario economico (Forex Factory)",
|
||||||
|
"fred" => "Date dei dati USA (FRED)",
|
||||||
|
"finnhub" => "Date delle trimestrali (Finnhub)",
|
||||||
|
"central_banks" => "Riunioni di Fed e BCE",
|
||||||
|
"alternative.me" => "Indice di paura e avidità",
|
||||||
|
"cboe" => "VIX (Cboe)",
|
||||||
|
"okx_derivatives" => "Funding e interesse aperto di BTC (OKX)",
|
||||||
|
_ => source,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Label(string? value) => value switch
|
||||||
|
{
|
||||||
|
null => "—",
|
||||||
|
"auto" => "Come il sistema",
|
||||||
|
"light" => "Chiaro",
|
||||||
|
"dark" => "Scuro",
|
||||||
|
"EUR" => "Euro (EUR)",
|
||||||
|
"USD" => "Dollaro (USD)",
|
||||||
|
"active" => "Attivo",
|
||||||
|
"paused" => "In pausa",
|
||||||
|
"stopped" => "Fermo",
|
||||||
|
_ => value.Trim('"'),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/laboratorio"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Backtest
|
||||||
|
@using Anubis.Data
|
||||||
|
@using Anubis.Learning
|
||||||
|
@using Anubis.Strategies
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
|
<PageTitle>Laboratorio · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@if (_running)
|
||||||
|
{
|
||||||
|
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (_message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (_lab is null)
|
||||||
|
{
|
||||||
|
<Pending Title="Il laboratorio non esegue test in questa modalità.">Nella modalità dimostrativa i test sul passato non partono: avvia Anubis normalmente per provare una strategia.</Pending>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="prove">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="prove">Test eseguiti</h2>
|
||||||
|
@if (_trials.Count(t => t.Status == TrialStatuses.Done) >= 2)
|
||||||
|
{
|
||||||
|
<form method="get" action="/laboratorio/confronto" class="form-inline">
|
||||||
|
<label for="a" class="sr-only">Primo test</label>
|
||||||
|
<select id="a" name="a">
|
||||||
|
@foreach (var t in _trials.Where(t => t.Status == TrialStatuses.Done))
|
||||||
|
{
|
||||||
|
<option value="@t.Id">@Title(t)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<label for="b" class="sr-only">Secondo test</label>
|
||||||
|
<select id="b" name="b">
|
||||||
|
@foreach (var (t, i) in _trials.Where(t => t.Status == TrialStatuses.Done).Select((t, i) => (t, i)))
|
||||||
|
{
|
||||||
|
<option value="@t.Id" selected="@(i == 1)">@Title(t)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<button class="btn btn-small" type="submit">Confronta</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (_trials.Count == 0)
|
||||||
|
{
|
||||||
|
<div class="empty">
|
||||||
|
<p class="empty-title">Nessun test eseguito.</p>
|
||||||
|
<p>Ogni test prova una strategia su un periodo passato, con tutte le combinazioni della sua griglia di parametri, costi realistici e poi doppi e tripli, e le convalide del protocollo anti-illusioni. Il piano si scrive prima di vedere i risultati e resta nel registro.</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Pianificato</th>
|
||||||
|
<th scope="col">Strategia</th>
|
||||||
|
<th scope="col">Dati</th>
|
||||||
|
<th scope="col" class="num">Varianti</th>
|
||||||
|
<th scope="col">Stato</th>
|
||||||
|
<th scope="col">Esito</th>
|
||||||
|
<th scope="col" class="num">Risultato netto</th>
|
||||||
|
<th scope="col" class="num">Sharpe</th>
|
||||||
|
<th scope="col" class="num">Calo massimo</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var t in _trials)
|
||||||
|
{
|
||||||
|
var s = t.Summary;
|
||||||
|
<tr>
|
||||||
|
<td class="nowrap"><a href="/laboratorio/@t.Id">@Format.ShortDate(t.CreatedAt, Shell.Now, Shell.Zone)</a></td>
|
||||||
|
<td>@Name(t.Strategy)</td>
|
||||||
|
<td>@LabText.Symbols(t.Plan.Data.Symbols)<br /><span class="muted">@LabText.Period(t.Plan.Data.From, t.Plan.Data.To)</span></td>
|
||||||
|
<td class="num">@t.Variants</td>
|
||||||
|
<td>@LabText.Status(t, _lab?.Progress(t.Id))</td>
|
||||||
|
<td>
|
||||||
|
@if (t.Verdict is { } verdict)
|
||||||
|
{
|
||||||
|
<span class="tag @(verdict == TrialVerdicts.Passed ? "gain" : "loss")">@LabText.Verdict(verdict)</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@LabText.Missing
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="num">@(s is null ? LabText.Missing : LabText.Money(s.NetResult, s.Currency, withSign: true))</td>
|
||||||
|
<td class="num">@(s is null ? LabText.Missing : LabText.Number(s.Sharpe))</td>
|
||||||
|
<td class="num">@(s is null ? LabText.Missing : LabText.Percent(s.MaxDrawdown))</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (_lab is not null)
|
||||||
|
{
|
||||||
|
var family = _family;
|
||||||
|
<section class="panel" id="nuovo" aria-labelledby="nuovo-titolo">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="nuovo-titolo">Nuovo test</h2>
|
||||||
|
<nav class="segmented" aria-label="Strategia">
|
||||||
|
@foreach (var f in StrategyCatalog.All)
|
||||||
|
{
|
||||||
|
<a href="/laboratorio?strategia=@f.Id#nuovo" class="@(f.Id == family.Id ? "on" : null)" aria-current="@(f.Id == family.Id ? "true" : null)">@f.Name</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
<p>@family.Description</p>
|
||||||
|
<form method="post" action="/azioni/laboratorio" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="strategia" value="@family.Id" />
|
||||||
|
<label for="origine">Dati</label>
|
||||||
|
<select id="origine" name="origine">
|
||||||
|
<option value="@TrialSources.Database">Barre giornaliere raccolte da Anubis</option>
|
||||||
|
<option value="@TrialSources.Research">Storico di ricerca (archivi Binance dal 2017)</option>
|
||||||
|
</select>
|
||||||
|
<label for="mercato">Mercato, per le barre raccolte</label>
|
||||||
|
<select id="mercato" name="mercato">
|
||||||
|
<option value="@Venues.Okx">Crypto su OKX, in euro</option>
|
||||||
|
<option value="@Venues.Alpaca">Azioni USA su Alpaca, in dollari</option>
|
||||||
|
</select>
|
||||||
|
<label for="strumenti">Strumenti, separati da virgole</label>
|
||||||
|
<input id="strumenti" name="strumenti" autocomplete="off" spellcheck="false" maxlength="400" placeholder="BTC-EUR, ETH-EUR" required />
|
||||||
|
<p class="hint">Simboli del mercato scelto: BTC-EUR su OKX, AAPL su Alpaca, BTCUSDT nello storico di ricerca. @Research()</p>
|
||||||
|
<div class="row">
|
||||||
|
<div>
|
||||||
|
<label for="dal">Dal</label>
|
||||||
|
<input id="dal" name="dal" type="date" value="@_from.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)" required />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="al">Al</label>
|
||||||
|
<input id="al" name="al" type="date" value="@_to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)" required />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label for="capitale">Capitale iniziale, nella valuta degli strumenti</label>
|
||||||
|
<input id="capitale" name="capitale" inputmode="decimal" autocomplete="off" value="10.000" required />
|
||||||
|
@if (family.Parameters.Count > 0)
|
||||||
|
{
|
||||||
|
<fieldset>
|
||||||
|
<legend>Griglia dei parametri</legend>
|
||||||
|
@foreach (var p in family.Parameters)
|
||||||
|
{
|
||||||
|
<label for="griglia-@p.Name">@p.Label</label>
|
||||||
|
<input id="griglia-@p.Name" name="griglia_@p.Name" autocomplete="off" spellcheck="false" maxlength="200" value="@string.Join(", ", p.Grid.Select(v => v.ToString(CultureInfo.InvariantCulture)))" />
|
||||||
|
<p class="hint">Da @p.Min.ToString(CultureInfo.InvariantCulture) a @p.Max.ToString(CultureInfo.InvariantCulture), valori separati da virgole; ogni combinazione è una variante.</p>
|
||||||
|
}
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
<p class="hint">Soglie del protocollo, fissate nel piano: risultato netto positivo anche con costi doppi, Deflated Sharpe Ratio almeno 0,90, probabilità di sovra-adattamento non oltre 0,40 con più varianti, calo massimo non oltre il 25%.</p>
|
||||||
|
<button class="btn btn-primary" type="submit">Scrivi il piano e avvia il test</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="migliorie">
|
||||||
|
<h2 id="migliorie">Migliorie in osservazione</h2>
|
||||||
|
<div class="empty">
|
||||||
|
<p class="empty-title">Nessuna miglioria in osservazione.</p>
|
||||||
|
<p>Le modifiche che potrebbero migliorare il risultato o ridurre i costi si calcolano in ombra accanto alle regole in vigore e compaiono qui con l'effetto che avrebbero avuto. Arrivano con la Fase 9.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="stime">
|
||||||
|
<h2 id="stime">Stime di costo da confermare</h2>
|
||||||
|
<p class="hint">Scostamento contato da simulatore e backtest: @string.Join("; ", SlippageTiers.All.Select(t => SlippageTiers.Label(t) + " " + Bp(_table.Of(t)))). Ogni mese si confronta con le esecuzioni ottenute dai broker, mai con quelle del simulatore. Una stima sale da sola; scende solo se viene da soldi veri e la confermi tu.</p>
|
||||||
|
@if (_costs.Where(c => c.Status == CostStatuses.Pending).ToList() is { Count: > 0 } pending)
|
||||||
|
{
|
||||||
|
@foreach (var c in pending)
|
||||||
|
{
|
||||||
|
<div class="row">
|
||||||
|
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (quasi certamente tra @Bp(c.LowBp) e @Bp(c.HighBp)). Un punto base è un centesimo di punto percentuale.</span></p>
|
||||||
|
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||||
|
<form method="post" action="/azioni/stime-di-costo/@c.Id/rifiuta" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Rifiuta</button></form>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="empty">
|
||||||
|
<p class="empty-title">Nessuna stima da confermare.</p>
|
||||||
|
<p>Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma.</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (_costs.Where(c => c.Status != CostStatuses.Pending).Reverse().Take(10).ToList() is { Count: > 0 } past)
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<caption class="sr-only">Stime di scostamento già decise</caption>
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Strumenti</th><th scope="col" class="num">Prima</th><th scope="col" class="num">Stima</th><th scope="col" class="num">Esecuzioni</th><th scope="col">Esito</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var c in past)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td class="nowrap">@Format.ShortDate(c.DecidedAt ?? c.CreatedAt, Shell.Now, Shell.Zone)</td>
|
||||||
|
<td>@Capital(SlippageTiers.Label(c.Tier))</td>
|
||||||
|
<td class="num">@Bp(c.PreviousBp)</td>
|
||||||
|
<td class="num">@Bp(c.Bp)</td>
|
||||||
|
<td class="num">@c.Cases</td>
|
||||||
|
<td>@Outcome(c.Status)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private Laboratory? _lab;
|
||||||
|
private IReadOnlyList<Trial> _trials = [];
|
||||||
|
private IStrategyFamily _family = StrategyCatalog.All[0];
|
||||||
|
private bool _running;
|
||||||
|
private string? _message;
|
||||||
|
private DateOnly _from;
|
||||||
|
private DateOnly _to;
|
||||||
|
private IReadOnlyList<string> _research = [];
|
||||||
|
private IReadOnlyList<CostEstimate> _costs = [];
|
||||||
|
private SlippageTable _table = SlippageTable.Standard;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "strategia")]
|
||||||
|
public string? Strategia { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_lab = services.Lab;
|
||||||
|
_trials = await new TrialStore(services.Db, Clock).ListAsync(100, ct);
|
||||||
|
var costs = new CostBook(services.Db, Clock);
|
||||||
|
_costs = await costs.ListAsync(ct);
|
||||||
|
_table = await costs.TableAsync(ct);
|
||||||
|
_running = _trials.Any(t => !t.IsFinished);
|
||||||
|
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||||
|
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||||
|
_to = today.AddDays(-1);
|
||||||
|
_from = _to.AddYears(-3);
|
||||||
|
_research = new ResearchStore(Host.Config.Data.Research).Series()
|
||||||
|
.Where(s => s.Timeframe == Timeframes.Day)
|
||||||
|
.Select(s => s.Symbol)
|
||||||
|
.Order(StringComparer.Ordinal)
|
||||||
|
.ToList();
|
||||||
|
_message = Errore switch
|
||||||
|
{
|
||||||
|
null => null,
|
||||||
|
"stima" => "Quella stima non aspetta più una conferma.",
|
||||||
|
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
||||||
|
TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.",
|
||||||
|
TrialRequestErrors.Source => "Scegli da dove prendere i dati e, per le barre raccolte, il mercato.",
|
||||||
|
TrialRequestErrors.Symbols => $"Indica da 1 a {Laboratory.MaxSymbols} strumenti, separati da virgole.",
|
||||||
|
TrialRequestErrors.Dates => "Controlla le date: l'inizio deve venire prima della fine.",
|
||||||
|
TrialRequestErrors.Capital => "Il capitale iniziale deve essere un importo tra 1 e 10.000.000.",
|
||||||
|
TrialRequestErrors.Grid => "Un valore della griglia non si legge o è fuori dall'intervallo del parametro: usa numeri separati da virgole, con il punto per i decimali.",
|
||||||
|
TrialRequestErrors.Combinations => $"La griglia non dà combinazioni valide, oppure ne dà più di {Laboratory.MaxVariants}: restringila.",
|
||||||
|
_ => "Non è stato possibile avviare il test: riprova.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Bp(decimal bp) => Format.Quantity(Math.Round(bp, 1)) + " punti base";
|
||||||
|
|
||||||
|
private static string Capital(string text) => char.ToUpper(text[0], System.Globalization.CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Outcome(string status) => status switch
|
||||||
|
{
|
||||||
|
CostStatuses.Applied => "Salita da sola",
|
||||||
|
CostStatuses.Confirmed => "Confermata da te",
|
||||||
|
CostStatuses.Refused => "Rifiutata da te",
|
||||||
|
_ => "Superata dal mese dopo",
|
||||||
|
};
|
||||||
|
|
||||||
|
private string Research() => _research.Count == 0
|
||||||
|
? "Lo storico di ricerca è vuoto: lo riempie la raccolta dei dati."
|
||||||
|
: "Nello storico di ricerca: " + LabText.Symbols(_research) + ".";
|
||||||
|
|
||||||
|
private static string Name(string strategy) => StrategyCatalog.Find(strategy)?.Name ?? strategy;
|
||||||
|
|
||||||
|
private string Title(Trial t) => $"{Name(t.Strategy)}, {LabText.Symbols(t.Plan.Data.Symbols)}, {Format.ShortDate(t.CreatedAt, Shell.Now, Shell.Zone)}";
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/laboratorio/confronto"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Backtest
|
||||||
|
@using Anubis.Strategies
|
||||||
|
|
||||||
|
<PageTitle>Confronto tra test · Anubis</PageTitle>
|
||||||
|
|
||||||
|
<p><a href="/laboratorio">← Laboratorio</a></p>
|
||||||
|
|
||||||
|
@if (_a is null || _b is null)
|
||||||
|
{
|
||||||
|
<Pending Title="Servono due test completati.">Scegli due test conclusi dall'elenco del <a href="/laboratorio">Laboratorio</a>.</Pending>
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
@{
|
||||||
|
var a = _a.Value;
|
||||||
|
var b = _b.Value;
|
||||||
|
var ra = a.Report;
|
||||||
|
var rb = b.Report;
|
||||||
|
}
|
||||||
|
<section class="panel" aria-labelledby="confronto">
|
||||||
|
<h2 id="confronto">Confronto tra due test</h2>
|
||||||
|
@if (ra.DataFingerprint != rb.DataFingerprint)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="note"><Icon Name="info" Size="16" />I due test hanno letto dati diversi (strumenti, periodo o valuta): il confronto è indicativo.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="notice notice-gain" role="note"><Icon Name="check" Size="16" />Stessi dati per entrambi: le differenze vengono dalla strategia, dalla griglia o dalle soglie.</p>
|
||||||
|
}
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col"></th>
|
||||||
|
<th scope="col"><a href="/laboratorio/@a.Trial.Id">@Name(a)</a></th>
|
||||||
|
<th scope="col"><a href="/laboratorio/@b.Trial.Id">@Name(b)</a></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@Row("Esito", x => LabText.Verdict(x.Trial.Verdict))
|
||||||
|
@Row("Dati", x => LabText.Symbols(x.Trial.Plan.Data.Symbols) + ", " + LabText.Period(x.Trial.Plan.Data.From, x.Trial.Plan.Data.To))
|
||||||
|
@Row("Variante scelta", x => LabText.Parameters(x.Report.Chosen) + $" (di {x.Trial.Variants})")
|
||||||
|
@Row("Risultato netto", x => LabText.Money(x.Report.Metrics.NetResult, x.Report.Currency, withSign: true))
|
||||||
|
@Row("Con costi doppi", x => x.Report.Costs.FirstOrDefault(k => k.Multiplier == 2m) is { } k ? LabText.Money(k.NetResult, x.Report.Currency, withSign: true) : LabText.Missing)
|
||||||
|
@Row("Rendimento annuo", x => LabText.Percent(x.Report.Metrics.AnnualReturn, 1, true))
|
||||||
|
@Row("Comprare e tenere, annuo", x => LabText.Percent(x.Report.Benchmark.AnnualReturn, 1, true))
|
||||||
|
@Row("Volatilità annua", x => LabText.Percent(x.Report.Metrics.Volatility))
|
||||||
|
@Row("Sharpe annuo", x => LabText.Number(x.Report.Metrics.Sharpe))
|
||||||
|
@Row("Calo massimo", x => LabText.Percent(x.Report.Metrics.MaxDrawdown))
|
||||||
|
@Row("Operazioni chiuse", x => x.Report.Metrics.Trades.ToString(CultureInfo.InvariantCulture))
|
||||||
|
@Row("Operazioni in guadagno", x => x.Report.Metrics.Trades == 0 ? LabText.Missing : LabText.Percent(x.Report.Metrics.WinRate, 0))
|
||||||
|
@Row("Rapporto guadagni/perdite", x => LabText.Number(x.Report.Metrics.ProfitFactor))
|
||||||
|
@Row("Deflated Sharpe Ratio", x => LabText.Number(x.Report.DeflatedSharpe.Value))
|
||||||
|
@Row("Probabilità di sovra-adattamento", x => x.Report.Overfitting is { } p ? LabText.Number(p.Probability) : "non si applica")
|
||||||
|
@Row("Finestre che avanzano, rendimento", x => x.Report.WalkForward is { } w ? LabText.Percent(w.Return, 1, true) : LabText.Missing)
|
||||||
|
@Row("Decisioni cambiate dai dati futuri", x => x.Report.LookAhead.Changed.ToString(CultureInfo.InvariantCulture))
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private (Trial Trial, BacktestReport Report)? _a;
|
||||||
|
private (Trial Trial, BacktestReport Report)? _b;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
// Text, not Guid: a malformed value must give "servono due test", not an error page.
|
||||||
|
[SupplyParameterFromQuery(Name = "a")]
|
||||||
|
public string? A { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "b")]
|
||||||
|
public string? B { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var store = new TrialStore(Host.Services!.Db, Clock);
|
||||||
|
_a = await ReadAsync(store, A, ct);
|
||||||
|
_b = await ReadAsync(store, B, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, string? id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!Guid.TryParse(id, out var key) || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (trial, BacktestReport.FromJson(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Name((Trial Trial, BacktestReport Report) x) =>
|
||||||
|
$"{StrategyCatalog.Find(x.Trial.Strategy)?.Name ?? x.Trial.Strategy}, {Format.ShortDate(x.Trial.CreatedAt, Shell.Now, Shell.Zone)}";
|
||||||
|
|
||||||
|
private RenderFragment Row(string label, Func<(Trial Trial, BacktestReport Report), string> value) => __builder =>
|
||||||
|
{
|
||||||
|
<tr><th scope="row">@label</th><td>@value(_a!.Value)</td><td>@value(_b!.Value)</td></tr>
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/laboratorio/{Id:guid}"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Backtest
|
||||||
|
@using Anubis.Strategies
|
||||||
|
|
||||||
|
<PageTitle>Test del laboratorio · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@if (_trial is null)
|
||||||
|
{
|
||||||
|
<Pending Title="Test non trovato.">Torna al <a href="/laboratorio">Laboratorio</a> per l'elenco dei test.</Pending>
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
@{
|
||||||
|
var t = _trial;
|
||||||
|
var plan = t.Plan;
|
||||||
|
var r = _report;
|
||||||
|
}
|
||||||
|
@if (!t.IsFinished)
|
||||||
|
{
|
||||||
|
<HeadContent><meta http-equiv="refresh" content="3" /></HeadContent>
|
||||||
|
}
|
||||||
|
|
||||||
|
<p><a href="/laboratorio">← Laboratorio</a></p>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="titolo">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="titolo">@Name(t.Strategy) su @LabText.Symbols(plan.Data.Symbols)</h2>
|
||||||
|
@if (t.Verdict is { } verdict)
|
||||||
|
{
|
||||||
|
<span class="badge @(verdict == TrialVerdicts.Passed ? "badge-gain" : "badge-loss")"><Icon Name="@(verdict == TrialVerdicts.Passed ? "check" : "alert")" Size="18" />@LabText.Verdict(verdict)</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="tag">@LabText.Status(t, _progress)</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Dati</dt>
|
||||||
|
<dd>@LabText.Source(plan.Data), @LabText.Period(plan.Data.From, plan.Data.To)</dd>
|
||||||
|
<dt>Varianti provate</dt>
|
||||||
|
<dd>@t.Variants (@string.Join("; ", plan.Grid.Select(g => g.Key + " " + string.Join(", ", g.Value.Select(v => v.ToString(CultureInfo.InvariantCulture))))))</dd>
|
||||||
|
<dt>Capitale iniziale</dt>
|
||||||
|
<dd>@(r is null ? Format.Number(plan.InitialCapital, 2) : Format.Money(plan.InitialCapital, r.Currency))</dd>
|
||||||
|
<dt>Piano scritto</dt>
|
||||||
|
<dd>@Format.LongDateTime(t.CreatedAt, Shell.Zone), prima dei risultati. Impronta @Short(t.PlanHash)</dd>
|
||||||
|
@if (t.FinishedAt is { } finished)
|
||||||
|
{
|
||||||
|
<dt>Concluso</dt>
|
||||||
|
<dd>@Format.LongDateTime(finished, Shell.Zone)@(r is null ? "" : $", in {LabText.Number(r.Seconds, 1)} secondi")</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
@if (t.Status == TrialStatuses.Failed)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />Il test non è riuscito: @t.Error</p>
|
||||||
|
}
|
||||||
|
else if (!t.IsFinished)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="status"><Icon Name="clock" Size="16" />@(t.Status == TrialStatuses.Planned ? "In coda: parte appena finisce il test precedente." : "In corso" + (_progress is null ? "." : ": " + _progress + ".")) La pagina si aggiorna da sola.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (r is not null)
|
||||||
|
{
|
||||||
|
var c = r.Currency;
|
||||||
|
var m = r.Metrics;
|
||||||
|
var b = r.Benchmark;
|
||||||
|
<section class="panel" aria-labelledby="esito">
|
||||||
|
<h2 id="esito">Esito del protocollo</h2>
|
||||||
|
<p>Variante scelta: <strong>@LabText.Parameters(r.Chosen)</strong>, la migliore zona della griglia e non il singolo punto migliore.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Controllo</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Soglia</th><th scope="col">Esito</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var check in r.Checks)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td>@check.Name</td>
|
||||||
|
<td class="num">@LabText.CheckValue(check, c)</td>
|
||||||
|
<td class="num">@LabText.CheckThreshold(check, c)</td>
|
||||||
|
<td>
|
||||||
|
@switch (check.Passed)
|
||||||
|
{
|
||||||
|
case true:
|
||||||
|
<span class="tag gain">Superato</span>
|
||||||
|
break;
|
||||||
|
case false:
|
||||||
|
<span class="tag loss">Non superato</span>
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
<span class="tag">Non si applica</span>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="risultato">
|
||||||
|
<h2 id="risultato">Risultato della variante scelta</h2>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col"></th><th scope="col" class="num">Variante scelta</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row">Risultato netto</th><td class="num">@LabText.Money(m.NetResult, c, withSign: true)</td><td class="num">@LabText.Money(b.NetResult, c, withSign: true)</td></tr>
|
||||||
|
<tr><th scope="row">Rendimento totale</th><td class="num">@LabText.Percent(m.TotalReturn, 1, true)</td><td class="num">@LabText.Percent(b.TotalReturn, 1, true)</td></tr>
|
||||||
|
<tr><th scope="row">Rendimento annuo</th><td class="num">@LabText.Percent(m.AnnualReturn, 1, true)</td><td class="num">@LabText.Percent(b.AnnualReturn, 1, true)</td></tr>
|
||||||
|
<tr><th scope="row">Volatilità annua</th><td class="num">@LabText.Percent(m.Volatility)</td><td class="num">@LabText.Percent(b.Volatility)</td></tr>
|
||||||
|
<tr><th scope="row">Sharpe annuo</th><td class="num">@LabText.Number(m.Sharpe)</td><td class="num">@LabText.Number(b.Sharpe)</td></tr>
|
||||||
|
<tr><th scope="row">Calo massimo</th><td class="num">@LabText.Percent(m.MaxDrawdown)</td><td class="num">@LabText.Percent(b.MaxDrawdown)</td></tr>
|
||||||
|
<tr><th scope="row">Operazioni chiuse</th><td class="num">@m.Trades</td><td class="num">@LabText.Missing</td></tr>
|
||||||
|
<tr><th scope="row">Operazioni in guadagno</th><td class="num">@(m.Trades == 0 ? LabText.Missing : LabText.Percent(m.WinRate, 0))</td><td class="num">@LabText.Missing</td></tr>
|
||||||
|
<tr><th scope="row">Rapporto guadagni/perdite</th><td class="num">@(m.ProfitFactor is { } pf ? LabText.Number(pf) : m.Trades > 0 ? "nessuna perdita" : LabText.Missing)</td><td class="num">@LabText.Missing</td></tr>
|
||||||
|
<tr><th scope="row">Guadagno e perdita medi</th><td class="num">@LabText.Money(m.AverageWin, c, true) / @LabText.Money(m.AverageLoss, c, true)</td><td class="num">@LabText.Missing</td></tr>
|
||||||
|
<tr><th scope="row">Commissioni</th><td class="num">@LabText.Money(m.Fees, c)</td><td class="num">@LabText.Money(b.Fees, c)</td></tr>
|
||||||
|
<tr><th scope="row">Tempo investito, in media</th><td class="num">@LabText.Percent(m.Exposure, 0)</td><td class="num">@LabText.Percent(b.Exposure, 0)</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<EquityChart Points="_curve" Currency="@c" Native="true" Label="Patrimonio della variante scelta e di comprare e tenere" EquityLabel="Variante scelta" BenchmarkLabel="Comprare e tenere gli stessi strumenti" EquityColumn="Variante scelta" BenchmarkColumn="Comprare e tenere" />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="anni">
|
||||||
|
<h2 id="anni">Risultato per anno</h2>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Anno</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var y in m.Years)
|
||||||
|
{
|
||||||
|
var bh = b.Years.FirstOrDefault(x => x.Year == y.Year);
|
||||||
|
<tr><td>@y.Year</td><td class="num">@LabText.Money(y.Result, c, true)</td><td class="num">@LabText.Percent(y.Return, 1, true)</td><td class="num">@(bh is null ? LabText.Missing : LabText.Percent(bh.Return, 1, true))</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="costi">
|
||||||
|
<h2 id="costi">Sensibilità ai costi</h2>
|
||||||
|
<p>Commissioni e scostamento moltiplicati: una strategia che muore con i costi doppi non passa.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Costi</th><th scope="col" class="num">Risultato netto</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Sharpe</th><th scope="col" class="num">Calo massimo</th><th scope="col" class="num">Commissioni</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var k in r.Costs)
|
||||||
|
{
|
||||||
|
<tr><td>@(k.Multiplier == 1m ? "realistici" : $"× {Format.Number(k.Multiplier)}")</td><td class="num">@LabText.Money(k.NetResult, c, true)</td><td class="num">@LabText.Percent(k.TotalReturn, 1, true)</td><td class="num">@LabText.Number(k.Sharpe)</td><td class="num">@LabText.Percent(k.MaxDrawdown)</td><td class="num">@LabText.Money(k.Fees, c)</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="convalide">
|
||||||
|
<h2 id="convalide">Convalide</h2>
|
||||||
|
<h3>Sharpe corretto per il numero di prove</h3>
|
||||||
|
@{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); }
|
||||||
|
<p>Deflated Sharpe Ratio <strong>@LabText.Number(d.Value)</strong>: la probabilità che lo Sharpe della variante scelta (@LabText.Number(d.Sharpe * annual) all'anno) superi quello che il migliore di @d.Trials tentativi mostrerebbe per caso (@LabText.Number(d.Benchmark * annual) all'anno). Contati tutti i test di questa strategia: @r.TrialsCounted varianti. Su @d.Observations sedute, asimmetria @LabText.Number(d.Skewness), curtosi @LabText.Number(d.Kurtosis).</p>
|
||||||
|
|
||||||
|
<h3>Probabilità di sovra-adattamento</h3>
|
||||||
|
@if (r.Overfitting is { } pbo)
|
||||||
|
{
|
||||||
|
<p>PBO <strong>@LabText.Number(pbo.Probability)</strong>: in @Format.Number(pbo.Combinations) divisioni del periodo in due metà, la quota di volte in cui la variante migliore in una metà è finita nella metà peggiore dell'altra. Con @pbo.Variants varianti e @pbo.Groups blocchi.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Con una sola variante non c'è nulla da scegliere, quindi nulla da sovra-adattare: il controllo non si applica.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>Finestre che avanzano</h3>
|
||||||
|
@if (r.WalkForward is { } wf)
|
||||||
|
{
|
||||||
|
<p>Ogni finestra sceglie la variante sui dati precedenti e la giudica su quelli successivi, mai visti. Rendimento fuori campione complessivo <strong>@LabText.Percent(wf.Return, 1, true)</strong>, Sharpe @LabText.Number(wf.Sharpe * annual) all'anno; @wf.Purge sedute tolte tra addestramento e prova.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Finestra</th><th scope="col">Scelta su</th><th scope="col">Provata su</th><th scope="col">Variante</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Sharpe</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var w in wf.Windows)
|
||||||
|
{
|
||||||
|
<tr><td>@w.Window</td><td class="nowrap">@LabText.Period(w.TrainFrom, w.TrainTo)</td><td class="nowrap">@LabText.Period(w.TestFrom, w.TestTo)</td><td>@LabText.Parameters(w.Chosen)</td><td class="num">@LabText.Percent(w.Return, 1, true)</td><td class="num">@LabText.Number(w.Sharpe * annual)</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Periodo troppo breve per le finestre.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>K-fold purgato combinatorio</h3>
|
||||||
|
@if (r.Combinatorial is { } cv)
|
||||||
|
{
|
||||||
|
<p>@cv.Groups blocchi, @cv.TestGroups alla volta in prova: @cv.Splits divisioni e @cv.PathSharpes.Count percorsi completi fuori campione, con @cv.Purge sedute tolte prima di ogni blocco di prova e @cv.Embargo dopo. Sharpe medio dei percorsi @LabText.Number(cv.MeanSharpe * annual) all'anno, il peggiore @LabText.Number(cv.WorstSharpe * annual); percorsi in positivo @LabText.Percent(cv.PositiveShare, 0).</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p>Periodo troppo breve per i blocchi.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>Nessuno sguardo in avanti</h3>
|
||||||
|
<p>
|
||||||
|
Il test è stato rifatto con i dati tagliati al @string.Join(", ", r.LookAhead.Cutoffs.Select(x => LabText.Day(x))): delle @r.LookAhead.Decisions decisioni confrontate,
|
||||||
|
@(r.LookAhead.Changed == 0 ? "nessuna è cambiata." : $"{r.LookAhead.Changed} sono cambiate: la strategia guarda dati che al momento della decisione non esistevano.")
|
||||||
|
</p>
|
||||||
|
@if (r.LookAhead.Examples.Count > 0)
|
||||||
|
{
|
||||||
|
<ul>
|
||||||
|
@foreach (var e in r.LookAhead.Examples)
|
||||||
|
{
|
||||||
|
<li><code>@e</code></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="griglia">
|
||||||
|
<h2 id="griglia">Tutte le varianti</h2>
|
||||||
|
<p>Ogni variante vale il suo Sharpe, ma non più della media della sua zona (lei e le vicine nella griglia): si preferisce una collina larga a un picco isolato.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Parametri</th><th scope="col" class="num">Sharpe annuo</th><th scope="col" class="num">Punteggio di zona</th><th scope="col" class="num">Risultato netto</th><th scope="col" class="num">Calo massimo</th><th scope="col" class="num">Operazioni</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var v in r.Variants)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td>@LabText.Parameters(v.Parameters)@if (v.Chosen) {<span class="tag"> scelta</span>}</td>
|
||||||
|
<td class="num">@LabText.Number(v.Sharpe * annual)</td>
|
||||||
|
<td class="num">@LabText.Number(v.PlateauScore * annual)</td>
|
||||||
|
<td class="num">@LabText.Money(v.NetResult, c, true)</td>
|
||||||
|
<td class="num">@LabText.Percent(v.MaxDrawdown)</td>
|
||||||
|
<td class="num">@v.Trades</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="limiti">
|
||||||
|
<h2 id="limiti">Cosa questo test non considera</h2>
|
||||||
|
<ul>
|
||||||
|
@foreach (var l in r.Limitations)
|
||||||
|
{
|
||||||
|
<li>@l</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (r.Notes.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Decisioni e ordini non eseguiti come chiesto</h3>
|
||||||
|
<ul>
|
||||||
|
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
|
||||||
|
{
|
||||||
|
<li>@LabText.Note(reason): @count</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<h3>Dati usati</h3>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Strumento</th><th scope="col">Origine</th><th scope="col">Periodo</th><th scope="col" class="num">Barre</th><th scope="col" class="num">Azioni societarie</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var i in r.Instruments)
|
||||||
|
{
|
||||||
|
<tr><td>@i.Symbol</td><td>@i.Source</td><td class="nowrap">@LabText.Day(i.First) – @LabText.Day(i.Last)</td><td class="num">@i.Bars</td><td class="num">@i.Actions</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="hint">Impronta dei dati @Short(r.DataFingerprint): due test con la stessa impronta hanno letto esattamente gli stessi dati. Motore versione @plan.Engine, strategia versione @r.StrategyVersion.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (r.Trades.Count > 0)
|
||||||
|
{
|
||||||
|
<section class="panel" aria-labelledby="operazioni">
|
||||||
|
<h2 id="operazioni">Operazioni della variante scelta</h2>
|
||||||
|
<details>
|
||||||
|
<summary>Vedi le ultime @r.Trades.Count operazioni</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Strumento</th><th scope="col">Aperta</th><th scope="col">Chiusa</th><th scope="col" class="num">Investito</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Commissioni</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var tr in r.Trades.Reverse())
|
||||||
|
{
|
||||||
|
<tr><td>@tr.Symbol</td><td class="nowrap">@LabText.Day(tr.Opened)</td><td class="nowrap">@(tr.Closed is { } closed ? LabText.Day(closed) : "aperta")</td><td class="num">@LabText.Money(tr.Invested, c)</td><td class="num @(tr.Result >= 0 ? "gain" : "loss")">@LabText.Money(tr.Result, c, true)</td><td class="num">@LabText.Money(tr.Fees, c)</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private Trial? _trial;
|
||||||
|
private BacktestReport? _report;
|
||||||
|
private string? _progress;
|
||||||
|
private IReadOnlyList<Anubis.Server.EquityPoint> _curve = [];
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
var store = new TrialStore(services.Db, Clock);
|
||||||
|
_trial = await store.GetAsync(Id, ct);
|
||||||
|
if (_trial is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_progress = services.Lab?.Progress(Id);
|
||||||
|
if (await store.ReportJsonAsync(Id, ct) is { } json)
|
||||||
|
{
|
||||||
|
_report = BacktestReport.FromJson(json);
|
||||||
|
_curve = _report.Curve.Select(p => new Anubis.Server.EquityPoint(new DateTimeOffset(p.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), p.Day, p.Equity, p.Benchmark)).ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Name(string strategy) => StrategyCatalog.Find(strategy)?.Name ?? strategy;
|
||||||
|
|
||||||
|
private static string Short(string hash) => hash.Length > 12 ? hash[..12] : hash;
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/notizie"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@using Anubis.News
|
||||||
|
|
||||||
|
<PageTitle>Notizie e mercato · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var rows = Filtered(v.Board.Rows).ToList();
|
||||||
|
var count = _filter switch
|
||||||
|
{
|
||||||
|
"effetto" => v.Board.Active,
|
||||||
|
"posizioni" => v.Board.OnPositions,
|
||||||
|
_ => v.Board.Read,
|
||||||
|
};
|
||||||
|
var shown = _all ? rows : rows.Take(Shown).ToList();
|
||||||
|
}
|
||||||
|
<p class="lead page-lead">@Lead(v)</p>
|
||||||
|
|
||||||
|
<div class="news-columns">
|
||||||
|
<section class="panel news-panel" aria-labelledby="letto">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="letto">Cosa ho letto e cosa ne ho fatto</h2>
|
||||||
|
<nav class="segmented" aria-label="Filtro delle notizie">
|
||||||
|
<a class="@(_filter == "effetto" ? "on" : null)" href="/notizie?filtro=effetto" aria-current="@(_filter == "effetto" ? "page" : null)">Con effetto, @v.Board.Active</a>
|
||||||
|
<a class="@(_filter == "posizioni" ? "on" : null)" href="/notizie?filtro=posizioni" aria-current="@(_filter == "posizioni" ? "page" : null)">Sulle tue posizioni, @v.Board.OnPositions</a>
|
||||||
|
<a class="@(_filter == "tutte" ? "on" : null)" href="/notizie?filtro=tutte" aria-current="@(_filter == "tutte" ? "page" : null)">Tutte, @v.Board.Read</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
@if (rows.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note news-empty">@Empty(v)</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="news-rows">
|
||||||
|
@foreach (var n in shown)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<p class="news-meta">
|
||||||
|
<span>@Format.ShortDate(n.At, Shell.Now, Shell.Zone)@(n.Publisher.Length > 0 ? ", da " + n.Publisher : "")</span>
|
||||||
|
<span class="tag tag-strong">@n.About</span>
|
||||||
|
@if (n.SingleSource)
|
||||||
|
{
|
||||||
|
<span class="tag tag-outline">Una sola fonte</span>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
<h3 class="news-title">@n.Title</h3>
|
||||||
|
@if (n.Summary is { } summary)
|
||||||
|
{
|
||||||
|
<p class="news-summary"><span class="sr-only">Riassunto del modello linguistico: </span>@summary</p>
|
||||||
|
}
|
||||||
|
<p class="news-facts">
|
||||||
|
<span class="tone @(n.Direction < 0 ? "loss" : n.Direction > 0 ? "gain" : null)">
|
||||||
|
@if (n.Direction == 0)
|
||||||
|
{
|
||||||
|
<span class="tone-flat" aria-hidden="true"></span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<Arrow Up="@(n.Direction > 0)" />
|
||||||
|
}
|
||||||
|
<span class="tone-text">@n.Tone</span>
|
||||||
|
</span>
|
||||||
|
<span class="importance">
|
||||||
|
<span class="importance-bars" aria-hidden="true">
|
||||||
|
@for (var i = 1; i <= 5; i++)
|
||||||
|
{
|
||||||
|
<span class="@(i <= n.Importance ? "on" : null)"></span>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
Importanza @n.Importance su 5
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
@if (n.Active)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" /><span><strong>Cosa ho fatto:</strong> @Inline(n.Action)</span></p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="news-action"><strong>Cosa ho fatto:</strong> @Inline(n.Action)</p>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (!_all && count > shown.Count)
|
||||||
|
{
|
||||||
|
<div class="news-more"><a class="btn" href="/notizie?filtro=@_filter&tutte=1">Mostra le altre @(count - shown.Count)</a></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="journal-side news-side">
|
||||||
|
<section class="panel" aria-labelledby="umore">
|
||||||
|
<h2 id="umore">Umore del mercato</h2>
|
||||||
|
<ul class="gauges">
|
||||||
|
@foreach (var g in v.Mood)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<div class="gauge-head">
|
||||||
|
<span>@g.Label</span>
|
||||||
|
@if (g.Value is { } value)
|
||||||
|
{
|
||||||
|
<span><strong>@value</strong> @g.Words</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">non ancora letto</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="gauge-track @(g.Centered ? "centered" : null)" aria-hidden="true">
|
||||||
|
@if (g.Position is { } position)
|
||||||
|
{
|
||||||
|
<span class="gauge-dot" style="left: @Css(position * 100)%"></span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="gauge-ends"><span>@g.Left</span><span>@g.Right</span></div>
|
||||||
|
@if (g.Stale is { } stale)
|
||||||
|
{
|
||||||
|
<p class="hint">Ultimo valore @stale.</p>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<p class="note gauges-note">Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.</p>
|
||||||
|
<p class="hint">@Anubis.Data.FearGreed.Attribution.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="calendario">
|
||||||
|
<h2 id="calendario">In calendario</h2>
|
||||||
|
@if (v.Calendar.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessun evento importante nei prossimi giorni.@(Shell.IsDemo || v.Collecting ? "" : " Il calendario si scarica con i dati di mercato.")</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="calendar-list">
|
||||||
|
@foreach (var e in v.Calendar)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<span class="muted">@e.When</span>
|
||||||
|
<strong>@e.Title</strong>
|
||||||
|
<span class="@(e.Matters ? "attention-text" : "muted")">@e.Effect</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="plain" aria-labelledby="fonti">
|
||||||
|
<h2 id="fonti">Da dove leggo</h2>
|
||||||
|
@if (v.Sources.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Non leggo ancora nessuna fonte. Le notizie si scaricano con i dati di mercato.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="source-list">
|
||||||
|
@foreach (var s in v.Sources)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<span class="@(s.Ok ? "gain" : "loss")"><Icon Name="@(s.Ok ? "check" : "alert")" Size="16" /></span>
|
||||||
|
<span>@s.Name</span>
|
||||||
|
<span class="muted">@s.Frequency</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<p class="note">@v.Spending</p>
|
||||||
|
<p class="hint"><a href="/impostazioni#notizie">Fonti e regole nelle impostazioni</a></p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
/// <summary>The rows shown before "Mostra le altre", as in the mockup.</summary>
|
||||||
|
private const int Shown = 6;
|
||||||
|
|
||||||
|
private NewsView _view = null!;
|
||||||
|
private string _filter = "posizioni";
|
||||||
|
private bool _all;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "filtro")]
|
||||||
|
public string? Filtro { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "tutte")]
|
||||||
|
public string? Tutte { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
_view = await NewsView.LoadAsync(Host, Shell, ct);
|
||||||
|
|
||||||
|
// Without positions the default filter would be empty: then all the news.
|
||||||
|
_filter = Filtro is "effetto" or "posizioni" or "tutte" ? Filtro : _view.Board.OnPositions > 0 ? "posizioni" : "tutte";
|
||||||
|
_all = Tutte == "1";
|
||||||
|
}
|
||||||
|
|
||||||
|
private IEnumerable<NewsBoardRow> Filtered(IEnumerable<NewsBoardRow> rows) => _filter switch
|
||||||
|
{
|
||||||
|
"effetto" => rows.Where(r => r.Active),
|
||||||
|
"posizioni" => rows.Where(r => r.OnPositions),
|
||||||
|
_ => rows,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Lead(NewsView v)
|
||||||
|
{
|
||||||
|
var read = v.Board.Read == 1 ? "1 notizia letta" : $"{v.Board.Read} notizie lette";
|
||||||
|
var active = v.Board.Active switch
|
||||||
|
{
|
||||||
|
0 => "nessuna con un effetto in corso",
|
||||||
|
1 => "1 con un effetto in corso",
|
||||||
|
var n => $"{n} con un effetto in corso",
|
||||||
|
};
|
||||||
|
return $"{read} nelle ultime 24 ore, {active}.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Empty(NewsView v) => _filter switch
|
||||||
|
{
|
||||||
|
"effetto" => "Nessuna notizia ha un effetto in corso: compro e vendo come dicono le strategie.",
|
||||||
|
"posizioni" => "Nessuna notizia sulle tue posizioni nelle ultime 24 ore.",
|
||||||
|
_ when !v.Collecting && !Shell.IsDemo => "Non leggo ancora notizie: la raccolta parte con i dati di mercato. Le fonti si scelgono nelle impostazioni.",
|
||||||
|
_ => "Nessuna notizia nelle ultime 24 ore.",
|
||||||
|
};
|
||||||
|
|
||||||
|
// "Niente. Confermano…" reads "niente. Confermano…" after "Cosa ho fatto:".
|
||||||
|
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||||
|
|
||||||
|
private static string Css(double value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/operazioni"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
|
<PageTitle>Operazioni · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
var f = _filter;
|
||||||
|
}
|
||||||
|
@if (v.Total == 0)
|
||||||
|
{
|
||||||
|
<Pending Title="Ancora nessuna operazione chiusa.">Qui compare ogni operazione quando si chiude: quanto ha reso, quanto è durata e perché il bot ha comprato e venduto. Le strategie in osservazione non operano: le vedi in <a href="/strategie">Strategie</a>.</Pending>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<section class="panel head-block trades-head" aria-label="Il bilancio delle operazioni">
|
||||||
|
<div class="half">
|
||||||
|
<p class="lead">Per ogni euro perso ne ha guadagnati</p>
|
||||||
|
<p class="big-number">@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")</p>
|
||||||
|
<p class="note">Guadagni incassati finora: <strong class="@(v.Net >= 0 ? "gain" : "loss")">@Shell.Money(v.Net, c, withSign: true)</strong>@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")</p>
|
||||||
|
<dl class="cells">
|
||||||
|
<div><dt>In guadagno</dt><dd><strong>@v.Winners su @v.Matching</strong><span>@Format.Percent(v.Matching == 0 ? 0 : (decimal)v.Winners / v.Matching * 100m)</span></dd></div>
|
||||||
|
<div><dt>Guadagno medio</dt><dd><strong>@(v.Winners == 0 ? "—" : Shell.Money(v.Gains / v.Winners, c, withSign: true))</strong><span>su @v.Winners @(v.Winners == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||||
|
<div><dt>Perdita media</dt><dd><strong>@(v.Losers == 0 ? "—" : Shell.Money(v.Losses / v.Losers, c, withSign: true))</strong><span>su @v.Losers @(v.Losers == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||||
|
<div><dt>Commissioni</dt><dd><strong>@Shell.Money(v.Fees, c)</strong><span>già tolte</span></dd></div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="half">
|
||||||
|
<h2>Risultato di ogni operazione <span class="note">dalla prima all'ultima; in alto i guadagni, in basso le perdite</span></h2>
|
||||||
|
@if (v.Bars.Count > 0)
|
||||||
|
{
|
||||||
|
var max = Math.Max(1m, v.Bars.Max(b => Math.Abs(b.Eur)));
|
||||||
|
var width = 600m / v.Bars.Count;
|
||||||
|
var best = v.Bars.MaxBy(b => b.Eur);
|
||||||
|
var worst = v.Bars.MinBy(b => b.Eur);
|
||||||
|
<svg class="result-bars" viewBox="0 0 600 180" preserveAspectRatio="none" role="img" aria-label="Risultato di ogni operazione: la migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol">
|
||||||
|
<line x1="0" x2="600" y1="90" y2="90" class="axis" />
|
||||||
|
@for (var i = 0; i < v.Bars.Count; i++)
|
||||||
|
{
|
||||||
|
var b = v.Bars[i];
|
||||||
|
var h = Math.Abs(b.Eur) / max * 70m;
|
||||||
|
<rect x="@Css(i * width + width * 0.15m)" y="@Css(b.Eur >= 0 ? 90 - h : 90)" width="@Css(width * 0.7m)" height="@Css(Math.Max(h, 0.5m))" class="@(b.Eur >= 0 ? "gain" : "loss")" />
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
<p class="note bars-scale"><span>@Day(v.Bars[0].At)</span><span>@Day(v.Bars[^1].At)</span></p>
|
||||||
|
<p class="note">La migliore <strong class="gain">@Shell.Money(best.Eur, c, withSign: true)</strong> su @best.Symbol, la peggiore <strong class="loss">@Shell.Money(worst.Eur, c, withSign: true)</strong> su @worst.Symbol.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="elenco">
|
||||||
|
<h2 id="elenco" class="visually-hidden">Operazioni chiuse</h2>
|
||||||
|
<form class="filters" method="get" action="/operazioni">
|
||||||
|
<label class="search"><Icon Name="search" Size="16" /><span class="visually-hidden">Cerca uno strumento</span><input type="search" name="cerca" value="@f.Search" placeholder="Cerca uno strumento" /></label>
|
||||||
|
<label><span class="visually-hidden">Conto</span>
|
||||||
|
<select name="conto" data-autosubmit>
|
||||||
|
<option value="">Tutti i conti</option>
|
||||||
|
@foreach (var (id, name) in v.Accounts)
|
||||||
|
{
|
||||||
|
<option value="@id" selected="@(f.Account == id)">@name</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Strategia</span>
|
||||||
|
<select name="strategia" data-autosubmit>
|
||||||
|
<option value="">Tutte le strategie</option>
|
||||||
|
@foreach (var s in v.Strategies)
|
||||||
|
{
|
||||||
|
<option value="@s" selected="@(f.Strategy == s)">@StrategyNames.Label(s)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Esito</span>
|
||||||
|
<select name="esito" data-autosubmit>
|
||||||
|
@foreach (var (key, label) in TradeFilter.Results)
|
||||||
|
{
|
||||||
|
<option value="@key" selected="@((f.Result ?? "") == key)">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Periodo</span>
|
||||||
|
<select name="periodo" data-autosubmit>
|
||||||
|
@foreach (var (key, label) in TradeFilter.Periods)
|
||||||
|
{
|
||||||
|
<option value="@key" selected="@(f.Period == key)">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<noscript><button class="btn" type="submit">Filtra</button></noscript>
|
||||||
|
<a class="btn" href="/api/operazioni.csv@(f.Query(1))" download><Icon Name="download" Size="18" />Esporta CSV</a>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@if (v.Rows.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="trades" role="list">
|
||||||
|
<div class="trade-row trade-header" aria-hidden="true">
|
||||||
|
<span>Chiusa</span><span>Strumento</span><span class="wide">Strategia</span><span class="wide">Durata</span><span class="num wide">Entrata e uscita</span><span class="num">Risultato</span><span class="wide">Perché è stata chiusa</span>
|
||||||
|
</div>
|
||||||
|
@foreach (var t in v.Rows)
|
||||||
|
{
|
||||||
|
var gain = t.RealizedEur >= 0;
|
||||||
|
<details class="trade" role="listitem">
|
||||||
|
<summary class="trade-row">
|
||||||
|
<span class="nowrap">@When(t.ClosedAt)</span>
|
||||||
|
<span><strong>@t.Symbol</strong> <span class="muted">@t.Name</span></span>
|
||||||
|
<span class="wide nowrap"><span class="swatch round" style="background: var(--s-@t.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(t.Strategy)</span>
|
||||||
|
<span class="wide">@Duration(t)</span>
|
||||||
|
<span class="num wide nowrap">@Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4) → @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</span>
|
||||||
|
<span class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(t.RealizedEur, c, withSign: true)</strong> <span class="cell-extra">(@Format.Percent(t.Percent, 2, withSign: true))</span></span>
|
||||||
|
<span class="wide">@t.ExitReason</span>
|
||||||
|
</summary>
|
||||||
|
<div class="why">
|
||||||
|
<div class="why-card">
|
||||||
|
<h3>Perché l'ho comprata</h3>
|
||||||
|
@if (t.Bought.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var line in t.Bought)
|
||||||
|
{
|
||||||
|
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="why-card">
|
||||||
|
<h3>Perché l'ho venduta</h3>
|
||||||
|
@if (t.Sold.Count == 0)
|
||||||
|
{
|
||||||
|
<p>@t.ExitReason.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var line in t.Sold)
|
||||||
|
{
|
||||||
|
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<dl class="account-lines">
|
||||||
|
<dt>Comprata @Long(t.OpenedAt)</dt><dd><strong>@Format.Quantity(t.Quantity) a @Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4)</strong></dd>
|
||||||
|
<dt>Venduta @Long(t.ClosedAt)</dt><dd><strong>a @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</strong></dd>
|
||||||
|
<dt>Differenza dal prezzo atteso</dt><dd><strong>@Slip(t.EntrySlipBp) e @Slip(t.ExitSlipBp)</strong></dd>
|
||||||
|
<dt>Commissioni</dt><dd><strong>@Format.Money(t.Fees, t.Currency)</strong></dd>
|
||||||
|
<dt>Conto</dt><dd>@t.Account</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
var pages = (v.Matching + TradeFilter.PageSize - 1) / TradeFilter.PageSize;
|
||||||
|
<div class="pager">
|
||||||
|
<span class="note">Mostrate @v.Rows.Count di @v.Matching</span>
|
||||||
|
@if (f.Page > 1)
|
||||||
|
{
|
||||||
|
<a class="btn" href="/operazioni@(f.Query(f.Page - 1))">Più recenti</a>
|
||||||
|
}
|
||||||
|
@if (f.Page < pages)
|
||||||
|
{
|
||||||
|
<a class="btn" href="/operazioni@(f.Query(f.Page + 1))">Più vecchie</a>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private TradesView _view = null!;
|
||||||
|
private TradeFilter _filter = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "cerca")] public string? Cerca { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "conto")] public string? Conto { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "strategia")] public string? Strategia { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "esito")] public string? Esito { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "periodo")] public string? Periodo { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "pagina")] public string? Pagina { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_filter = TradeFilter.Parse(Cerca, Conto, Strategia, Esito, Periodo, Pagina);
|
||||||
|
_view = await TradesView.LoadAsync(services, Clock, _filter, null, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private string When(DateTimeOffset at) => Capital(Local(at, "ddd d MMM, HH:mm"));
|
||||||
|
|
||||||
|
private string Day(DateTimeOffset at) => Local(at, "d MMM");
|
||||||
|
|
||||||
|
private string Long(DateTimeOffset at) => Local(at, "dddd d MMMM, HH:mm");
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Duration(TradeRow t)
|
||||||
|
{
|
||||||
|
var days = (int)Math.Round((t.ClosedAt - t.OpenedAt).TotalDays);
|
||||||
|
return days switch
|
||||||
|
{
|
||||||
|
< 1 => "in giornata",
|
||||||
|
1 => "1 giorno",
|
||||||
|
_ => $"{days} giorni",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Slip(decimal? bp) => bp is { } b ? Format.Percent(b / 100m, 2) : "—";
|
||||||
|
}
|
||||||
@@ -0,0 +1,500 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@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)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>Primo passo: decidi quanto capitale affidare al bot in <a href="/impostazioni#conti">Impostazioni, Conti e chiavi</a>. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.</span></p>
|
||||||
|
}
|
||||||
|
<section class="panel head-block" aria-label="Il punto della situazione">
|
||||||
|
<div class="half half-past">
|
||||||
|
<div class="half-head">
|
||||||
|
<h2><Icon Name="half" Size="18" />Finora</h2>
|
||||||
|
@if (o.HasData)
|
||||||
|
{
|
||||||
|
<nav class="segmented" aria-label="Periodo">
|
||||||
|
@foreach (var (key, label) in Overview.Periods)
|
||||||
|
{
|
||||||
|
<a href="@(key == "avvio" ? "/" : "/?periodo=" + key)" class="@(key == _period ? "on" : null)" aria-current="@(key == _period ? "true" : null)">@label</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (!o.HasData)
|
||||||
|
{
|
||||||
|
<div class="empty">
|
||||||
|
<p class="empty-title">Ancora nessun risultato da mostrare.</p>
|
||||||
|
<p>Il patrimonio comincia a essere registrato quando colleghi un conto. Da quel giorno qui vedrai quanto stai guadagnando o perdendo, al netto dei costi, e il confronto con chi non usa il bot.</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var gain = o.Result.Amount >= 0;
|
||||||
|
<p class="lead">@(gain ? "Sei in profitto di" : "Sei in perdita di")</p>
|
||||||
|
<div class="big-result">
|
||||||
|
<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>
|
||||||
|
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)))
|
||||||
|
{
|
||||||
|
var up = cell.Amount >= 0;
|
||||||
|
var label = cell.Label.StartsWith("Ultimi ", StringComparison.Ordinal) ? cell.Label["Ultimi ".Length..] : cell.Label;
|
||||||
|
<div class="cell @(i >= 3 ? "cell-extra" : null)">
|
||||||
|
<span class="cell-label">@if (label != cell.Label) {<span class="long">Ultimi </span>}@label</span>
|
||||||
|
<span class="cell-value">@Shell.Money(cell.Amount, c, withSign: true)</span>
|
||||||
|
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(cell.Percent, 2, withSign: true)</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<EquityChart Points="o.Series" Currency="c" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="half half-next">
|
||||||
|
<div class="half-head">
|
||||||
|
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
|
||||||
|
@if (_runningDays is { } days)
|
||||||
|
{
|
||||||
|
<span class="note desk-only">Attivo da @days giorni senza interruzioni</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<p class="statement">@Statement(o)</p>
|
||||||
|
@if (p.NextDecision is { } decision)
|
||||||
|
{
|
||||||
|
<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">
|
||||||
|
@for (var i = 0; i < moves.Count; i++)
|
||||||
|
{
|
||||||
|
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>
|
||||||
|
}
|
||||||
|
<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">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
|
||||||
|
{
|
||||||
|
<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))
|
||||||
|
{
|
||||||
|
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 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 è spenta insieme ai dati di mercato. Quando la accendi, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.</p>
|
||||||
|
}
|
||||||
|
else if (p.News.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna notizia sulle tue posizioni nelle ultime 24 ore, e nessuna restrizione in corso.</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>
|
||||||
|
@{ var m = p.Learning; }
|
||||||
|
<p><strong>@m.Sentence</strong></p>
|
||||||
|
@if (m.State == LearningStates.Observation)
|
||||||
|
{
|
||||||
|
<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>
|
||||||
|
}
|
||||||
|
@if (m.State == LearningStates.None)
|
||||||
|
{
|
||||||
|
<p class="note">@m.NextLabel: @m.NextCheck.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="tile-facts">
|
||||||
|
<dt>Previsioni azzeccate</dt><dd>@(m.Precision is { } hit ? $"{hit}% su dati mai visti" : "non ancora misurate")</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; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "periodo")]
|
||||||
|
public string? Periodo { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
_period = Periodo is "30" or "7" or "oggi" ? Periodo : "avvio";
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
var orders = o.OpenOrders == 0 ? "Nessun ordine in corso." : o.OpenOrders == 1 ? "Un ordine in corso." : $"{o.OpenOrders} ordini in corso.";
|
||||||
|
if (o.Positions == 0)
|
||||||
|
{
|
||||||
|
return "Nessuna posizione aperta. " + orders;
|
||||||
|
}
|
||||||
|
|
||||||
|
var stops = o.PositionsWithoutStop == 0
|
||||||
|
? (o.Positions == 1 ? "con il suo stop" : "ognuna con il suo stop")
|
||||||
|
: $"{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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
@page "/primo-accesso"
|
||||||
|
@layout ServiceLayout
|
||||||
|
@inject AnubisHost Host
|
||||||
|
|
||||||
|
<PageTitle>Primo accesso · Anubis</PageTitle>
|
||||||
|
|
||||||
|
<h1>Benvenuto in Anubis</h1>
|
||||||
|
<p>Prima di cominciare, due cose.</p>
|
||||||
|
|
||||||
|
<section class="service-section">
|
||||||
|
<h2><Icon Name="database" Size="18" />Database</h2>
|
||||||
|
<p>Scelto nella configurazione del container: qui si vede soltanto. Per cambiarlo si modifica il container (manuale, capitolo Installazione).</p>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Motore</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite")</dd>
|
||||||
|
<dt>Dove</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="service-section">
|
||||||
|
<h2><Icon Name="lock" Size="18" />Scegli la tua password</h2>
|
||||||
|
<p>La password iniziale del container vale solo per questo primo accesso. Scegline una nuova, di almeno @Passwords.MinimumLength caratteri.</p>
|
||||||
|
@if (Message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
<form method="post" action="/azioni/primo-accesso" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="attuale">Password iniziale</label>
|
||||||
|
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
|
||||||
|
<label for="nuova">Nuova password</label>
|
||||||
|
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
<label for="conferma">Scrivila di nuovo</label>
|
||||||
|
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
<button class="btn btn-primary" type="submit">Salva e continua</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
private string? Message => PasswordMessages.For(Errore);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
@page "/primo-avvio"
|
||||||
|
@layout ServiceLayout
|
||||||
|
@attribute [AllowAnonymous]
|
||||||
|
@inject AnubisHost Host
|
||||||
|
|
||||||
|
<PageTitle>Primo avvio · Anubis</PageTitle>
|
||||||
|
|
||||||
|
<h1>Primo avvio</h1>
|
||||||
|
@if (!_local)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="alert"><Icon Name="lock" Size="16" />La prima configurazione si fa solo dal computer su cui gira Anubis.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<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>
|
||||||
|
}
|
||||||
|
|
||||||
|
<form method="post" action="/azioni/primo-avvio" class="form" data-wizard>
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@if (!Host.Config.IsComplete)
|
||||||
|
{
|
||||||
|
<fieldset class="service-section">
|
||||||
|
<legend><span class="step">1</span>Database</legend>
|
||||||
|
<label class="choice">
|
||||||
|
<input type="radio" name="motore" value="sqlite" checked data-engine />
|
||||||
|
<span><strong>SQLite</strong> (consigliato): un file nella cartella dei dati, niente da installare.</span>
|
||||||
|
</label>
|
||||||
|
<label class="choice">
|
||||||
|
<input type="radio" name="motore" value="postgres" data-engine />
|
||||||
|
<span><strong>PostgreSQL</strong>: un server che hai già, con un database dedicato e vuoto.</span>
|
||||||
|
</label>
|
||||||
|
<div class="postgres-fields" data-postgres>
|
||||||
|
<label for="host">Indirizzo del server</label>
|
||||||
|
<input id="host" name="host" autocomplete="off" placeholder="192.168.1.10" />
|
||||||
|
<div class="row">
|
||||||
|
<div><label for="porta">Porta</label><input id="porta" name="porta" inputmode="numeric" value="5432" /></div>
|
||||||
|
<div><label for="nome">Nome del database</label><input id="nome" name="nome" value="anubis" /></div>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<div><label for="utente">Utente</label><input id="utente" name="utente" value="anubis" autocomplete="off" /></div>
|
||||||
|
<div><label for="dbpassword">Password del database</label><input id="dbpassword" name="dbpassword" type="password" autocomplete="off" /></div>
|
||||||
|
</div>
|
||||||
|
<p class="hint">La password del database non va in <code>config.toml</code>: la custodisce Windows per il tuo utente.</p>
|
||||||
|
<button class="btn" type="submit" formaction="/azioni/primo-avvio/prova" data-test-connection>Prova la connessione</button>
|
||||||
|
<p class="test-result" data-test-result role="status"></p>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
<fieldset class="service-section">
|
||||||
|
<legend><span class="step">@(Host.Config.IsComplete ? "1" : "2")</span>Password</legend>
|
||||||
|
<p class="hint">Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.</p>
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
<label for="conferma">Scrivila di nuovo</label>
|
||||||
|
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||||
|
</fieldset>
|
||||||
|
<p class="hint">Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.</p>
|
||||||
|
<button class="btn btn-primary" type="submit">Crea l'installazione</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private bool _local;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override void OnInitialized() => _local = HttpContext is not null && CurrentUser.IsLocal(HttpContext);
|
||||||
|
|
||||||
|
private string? Message => Errore == "database"
|
||||||
|
? "Non riesco a collegarmi al database con questi dati. Controlla indirizzo, porta, nome, utente e password, poi riprova."
|
||||||
|
: PasswordMessages.For(Errore);
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/rischio"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
@using Anubis.Risk
|
||||||
|
|
||||||
|
<PageTitle>Rischio · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
}
|
||||||
|
@if (_message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
<div class="risk-top">
|
||||||
|
<section class="panel" aria-labelledby="interruttore">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="interruttore">Interruttore d'emergenza</h2>
|
||||||
|
<span class="link-state @(v.BotState == "active" ? null : "down")"><span class="dot"></span>@BotText(v.BotState)</span>
|
||||||
|
</div>
|
||||||
|
@if (v.WaitsForRestart)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
|
||||||
|
@if (v.Tripped.Count > 0)
|
||||||
|
{
|
||||||
|
<text>L'interruttore è scattato @string.Join(" e ", v.Tripped.Select(t => Where(t.World))): il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "stopped")
|
||||||
|
{
|
||||||
|
<text>Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.</text>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<text>Lì non apro posizioni e non vendo per le strategie; gli stop di protezione restano attivi. Il resto continua a lavorare.</text>
|
||||||
|
}
|
||||||
|
@if (v.CloseAllPending)
|
||||||
|
{
|
||||||
|
<text> Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura.</text>
|
||||||
|
}
|
||||||
|
</span></p>
|
||||||
|
@if (v.StopFile)
|
||||||
|
{
|
||||||
|
<p class="note">C'è il file <code>STOP</code> nella cartella dei dati: toglilo, poi conferma qui la ripartenza.</p>
|
||||||
|
}
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/rischio" />
|
||||||
|
<button class="btn" type="submit" disabled="@v.StopFile" data-confirm="@RestartText(v)">Riparti</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (v.BotState != "stopped")
|
||||||
|
{
|
||||||
|
<p>Con <strong>Ferma tutto</strong> annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.</p>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<div class="choices">
|
||||||
|
<form method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger-solid" type="submit" data-confirm="Ferma tutto: annullo gli ordini in attesa e non apro posizioni finché non riparti da qui. Gli stop restano. Confermi?"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
|
||||||
|
<form method="post" action="/azioni/bot/chiudi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger" type="submit" data-confirm="Ferma e chiudi: fermo tutto e vendo a mercato ogni posizione del bot. Ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop. Non si annulla. Confermi?">Ferma e chiudi tutte le posizioni</button></form>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<p class="note">Anche un file chiamato <code>STOP</code> nella cartella dei dati ferma tutto entro un minuto.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="blocchi">
|
||||||
|
<h2 id="blocchi">Blocchi automatici</h2>
|
||||||
|
@if (!v.AnyBlock)
|
||||||
|
{
|
||||||
|
<p class="gain status-line"><Icon Name="check" Size="16" />Nessun blocco attivo</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="blocks">
|
||||||
|
@foreach (var t in v.Tripped)
|
||||||
|
{
|
||||||
|
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @Where(t.World) @(t.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />Perdita del giorno oltre il limite: niente nuovi ingressi fino a @Moment(until).</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.State.WeeklyHalvingUntil is { } half && half > Clock.UtcNow)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />Perdita della settimana oltre il limite: rischio dimezzato fino a @Moment(half).</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.Measures.Drawdown <= -v.Limits.DrawdownHalf && !v.Risk.State.Tripped)
|
||||||
|
{
|
||||||
|
<li><Icon Name="alert" Size="16" />Calo dal massimo oltre il @Format.Percent(v.Limits.DrawdownHalf * 100m, 0): rischio dimezzato.</li>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "paused")
|
||||||
|
{
|
||||||
|
<li><Icon Name="pause" Size="16" />Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.</li>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "stopped" && v.Tripped.Count == 0)
|
||||||
|
{
|
||||||
|
<li class="loss"><Icon Name="stop" Size="16" />Ferma tutto acceso.</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<dl class="block-list">
|
||||||
|
<dt>Prossimo blocco in programma</dt>
|
||||||
|
@if (v.NextCalendarBlock is { } next)
|
||||||
|
{
|
||||||
|
<dd><strong>@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")</strong><span>@next.Title: in quell'ora non apro posizioni.</span></dd>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dd><span>Nessun dato economico importante nei prossimi 14 giorni.</span></dd>
|
||||||
|
}
|
||||||
|
<dt>Ultimo blocco scattato</dt>
|
||||||
|
@if (v.LastCalendarBlock is { } last)
|
||||||
|
{
|
||||||
|
<dd><strong>@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")</strong><span>@last.Title.</span></dd>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dd><span>Nessuno negli ultimi 14 giorni.</span></dd>
|
||||||
|
}
|
||||||
|
<dt>Protezione day trade (azioni)</dt>
|
||||||
|
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se il conto Alpaca vale meno di 25.000 $.")</span></dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="limiti">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="limiti">I limiti <span class="note">Valgono per tutte le strategie insieme@(v.World == Worlds.Real ? ", sui conti veri" : ", nel mondo simulato"). Si cambiano dalle <a href="/impostazioni#rischio">impostazioni</a>, mai da soli.</span></h2>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table limits">
|
||||||
|
<thead>
|
||||||
|
<tr><th scope="col">Limite</th><th scope="col" class="num">Adesso</th><th scope="col" class="wide">Quanto ne sto usando</th><th scope="col" class="num">Soglia</th><th scope="col" class="wide">Se lo supero</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var row in v.Rows)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<th scope="row">@row.Label</th>
|
||||||
|
<td class="num nowrap">@row.Now@if (row.Detail is { } d) {<text> </text><span class="muted">(@d)</span>}</td>
|
||||||
|
<td class="wide">
|
||||||
|
@if (row.Usage is { } u)
|
||||||
|
{
|
||||||
|
<span class="usage @(u >= 0.8m ? "high" : null)" role="img" aria-label="@Format.Percent(u * 100m, 0) del limite"><span style="width: @Css(u * 100m)%"></span></span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="num nowrap">@row.Threshold</td>
|
||||||
|
<td class="wide">@row.Beyond</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="columns">
|
||||||
|
<section class="panel" aria-labelledby="calo">
|
||||||
|
<h2 id="calo">Quanto è sceso dal massimo</h2>
|
||||||
|
<p class="note">Ogni fotografia del patrimonio@(v.Risk.State.PeakFrom is { } from ? " dal " + Local(from, "d MMMM") : " dall'avvio"). A zero vuol dire che il portafoglio era al suo punto più alto.</p>
|
||||||
|
@if (v.Drawdown.Count < 2)
|
||||||
|
{
|
||||||
|
<p class="note">Ancora troppo poche fotografie per disegnare la curva.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var worst = v.Drawdown.MinBy(p => p.Drawdown)!;
|
||||||
|
var floor = Math.Min(-0.01m, worst.Drawdown * 1.2m);
|
||||||
|
var first = v.Drawdown[0].At;
|
||||||
|
var span = Math.Max(1d, (v.Drawdown[^1].At - first).TotalSeconds);
|
||||||
|
string X(DateTimeOffset at) => Css((decimal)((at - first).TotalSeconds / span) * 560m + 30m);
|
||||||
|
string Y(decimal d) => Css(10m + d / floor * 150m);
|
||||||
|
var points = string.Join(' ', v.Drawdown.Select(p => X(p.At) + "," + Y(p.Drawdown)));
|
||||||
|
<svg class="drawdown" viewBox="0 0 600 190" role="img" aria-label="Calo dal massimo: il peggiore @Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMMM")">
|
||||||
|
<line x1="30" x2="590" y1="10" y2="10" class="axis" />
|
||||||
|
<text x="0" y="14" class="tick">0%</text>
|
||||||
|
<text x="0" y="164" class="tick">@Format.Percent(floor * 100m, 1)</text>
|
||||||
|
<polygon points="30,10 @points @X(v.Drawdown[^1].At),10" class="area" />
|
||||||
|
<polyline points="@points" class="line" />
|
||||||
|
<circle cx="@X(worst.At)" cy="@Y(worst.Drawdown)" r="4" class="dot" />
|
||||||
|
<text x="@X(worst.At)" y="@(Css(Math.Min(180m, 26m + worst.Drawdown / floor * 150m)))" text-anchor="middle" class="label">@Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMM")</text>
|
||||||
|
</svg>
|
||||||
|
<p class="note">
|
||||||
|
@if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m)
|
||||||
|
{
|
||||||
|
<text>Le soglie del @Format.Percent(v.Limits.DrawdownHalf * 100m, 0) e del @Format.Percent(v.Limits.DrawdownStop * 100m, 0) sono fuori scala: il calo peggiore è rimasto sotto un quinto del limite.</text>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<text>A @Format.Percent(-v.Limits.DrawdownHalf * 100m, 0) il rischio si dimezza, a @Format.Percent(-v.Limits.DrawdownStop * 100m, 0) il bot si ferma e aspetta te.</text>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="scenari">
|
||||||
|
<h2 id="scenari">Se succedesse domani</h2>
|
||||||
|
<p class="note">Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in <a href="/impostazioni#rischio">Impostazioni</a>.</p>
|
||||||
|
@if (!v.HasPositions)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Scenario</th><th scope="col" class="num">Senza stop</th><th scope="col" class="num">Con gli stop</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var s in v.Scenarios)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<th scope="row">@s.Scenario.Label</th>
|
||||||
|
<td class="num nowrap"><strong>@Shell.Money(s.WithoutStops, c, decimals: 0)</strong> <span class="muted">(@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true))</span></td>
|
||||||
|
<td class="num nowrap muted">@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0))</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Gli stop non sono una garanzia: in un crollo improvviso il prezzo può saltarli. E nessuno stop protegge dal cambio.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="columns">
|
||||||
|
<section aria-labelledby="mai" class="plain">
|
||||||
|
<h2 id="mai">Cosa il bot non può fare, mai</h2>
|
||||||
|
<ul class="never">
|
||||||
|
<li><Icon Name="ban" Size="16" />Usare soldi presi in prestito o vendere allo scoperto</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Prelevare o spostare denaro: le chiavi dei conti non lo permettono</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Toccare posizioni che non ha aperto lui</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Passare ai soldi veri senza la tua conferma</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Rischiare di più per recuperare una perdita</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Comprare di più perché lo suggerisce una notizia o il modello</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section aria-labelledby="eventi" class="plain">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="eventi">Eventi di rischio</h2>
|
||||||
|
@if (v.Events.Count == 0)
|
||||||
|
{
|
||||||
|
<span class="note">Nessun limite superato dall'avvio</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (v.Events.Count > 0)
|
||||||
|
{
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Events)
|
||||||
|
{
|
||||||
|
<dt>@Local(e.At, "d MMMM")</dt>
|
||||||
|
<dd class="@(e.Severity is RiskSeverities.Critical or RiskSeverities.High ? "loss" : null)">@e.Message</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
<a href="/diario">Vedi tutto nel diario</a>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private RiskView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
private string? _message;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await RiskView.LoadAsync(services, Clock, Shell.Zone, ct);
|
||||||
|
_message = Errore switch
|
||||||
|
{
|
||||||
|
"file-stop" => "Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire.",
|
||||||
|
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BotText(string state) => state switch
|
||||||
|
{
|
||||||
|
"active" => "Il bot sta operando",
|
||||||
|
"paused" => "In pausa",
|
||||||
|
_ => "Fermo",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato";
|
||||||
|
|
||||||
|
private static string RestartText(RiskView v) => v.Tripped.Count > 0
|
||||||
|
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
|
||||||
|
: "Riparti: il bot torna a operare. Confermi?";
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private string Moment(DateTimeOffset at) => Local(at, "d MMMM 'alle' HH:mm");
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
@page "/servizio"
|
||||||
|
@layout ServiceLayout
|
||||||
|
@attribute [AllowAnonymous]
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject IClock Clock
|
||||||
|
|
||||||
|
@* The error page of SPEC 15.1: what is wrong, what to do, and the engine stays off. Never another database. *@
|
||||||
|
<PageTitle>@ServiceText.Title(_status.Mode) · Anubis</PageTitle>
|
||||||
|
@if (_refresh)
|
||||||
|
{
|
||||||
|
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h1>@ServiceText.Title(_status.Mode)</h1>
|
||||||
|
|
||||||
|
@switch (_status.Mode)
|
||||||
|
{
|
||||||
|
case HostMode.Starting:
|
||||||
|
<p>Controllo configurazione e database. Questa pagina si aggiorna da sola.</p>
|
||||||
|
break;
|
||||||
|
|
||||||
|
case HostMode.ConfigProblem:
|
||||||
|
<p>Il motore resta spento finché la configurazione non è completa. Non uso nessun altro database al posto di quello indicato.</p>
|
||||||
|
<table class="table problems">
|
||||||
|
<thead><tr><th scope="col">Voce</th><th scope="col">Cosa non va</th><th scope="col">Come rimediare</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var problem in Host.Config.Problems)
|
||||||
|
{
|
||||||
|
<tr><td><code>@problem.Setting</code></td><td>@problem.What</td><td>@problem.Remedy</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||||
|
{
|
||||||
|
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="hint">Il file è <code>@Host.Config.Data.ConfigFile</code>. Appena lo correggi riprovo da solo.</p>
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case HostMode.DatabaseUnavailable:
|
||||||
|
<p>Il motore è fermo e aspetta il database. Non apro un altro database al suo posto: riprovo da solo ogni pochi secondi e riparto appena risponde.</p>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||||
|
<dt>Risposta</dt><dd>@(_status.Detail ?? "nessuna")</dd>
|
||||||
|
<dt>Tentativi</dt><dd>@_status.Attempts, dal @Format.ShortDate(_status.Since, Clock.UtcNow, Host.Config.TimeZone)</dd>
|
||||||
|
</dl>
|
||||||
|
<h2>Cosa controllare</h2>
|
||||||
|
<ul class="steps">
|
||||||
|
@if (Host.Config.Db?.Engine == DbEngine.Postgres)
|
||||||
|
{
|
||||||
|
<li>Che il server PostgreSQL sia acceso e raggiungibile da qui (indirizzo e porta).</li>
|
||||||
|
<li>Che nome del database, utente e password siano quelli giusti.</li>
|
||||||
|
<li>Che il database esista: lo crei tu una volta, Anubis non crea e non cancella database.</li>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<li>Che il file del database sia al suo posto e leggibile. Se l'hai spostato, rimettilo dov'era.</li>
|
||||||
|
<li>Che il disco della cartella dei dati sia collegato e abbia spazio libero.</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
break;
|
||||||
|
|
||||||
|
case HostMode.SchemaProblem:
|
||||||
|
<p>@_status.Detail</p>
|
||||||
|
<p>Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.</p>
|
||||||
|
break;
|
||||||
|
|
||||||
|
case HostMode.IdentityProblem:
|
||||||
|
<IdentityChoices Status="_status" Local="_local" />
|
||||||
|
break;
|
||||||
|
|
||||||
|
case HostMode.FirstRun:
|
||||||
|
<p><a href="/primo-avvio">Apri la procedura di primo avvio</a>.</p>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Errore is { } errore)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@(errore switch
|
||||||
|
{
|
||||||
|
"password" => "Password della configurazione d'avvio sbagliata, oppure scelta fatta da un altro computer.",
|
||||||
|
"importazione" => "Il ripristino non è riuscito e non ho cambiato nulla. Controlla l'archivio e riprova.",
|
||||||
|
"attesa" => "Troppi tentativi sbagliati. Riprova tra 15 minuti.",
|
||||||
|
_ => "Questa scelta non è disponibile adesso.",
|
||||||
|
})</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private HostStatus _status = null!;
|
||||||
|
private bool _refresh;
|
||||||
|
private bool _local;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
_status = Host.Status;
|
||||||
|
_refresh = _status.Mode is HostMode.Starting or HostMode.DatabaseUnavailable or HostMode.ConfigProblem;
|
||||||
|
if (HttpContext is not null)
|
||||||
|
{
|
||||||
|
_local = CurrentUser.IsLocal(HttpContext);
|
||||||
|
if (!HttpContext.Response.HasStarted)
|
||||||
|
{
|
||||||
|
HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||||
|
HttpContext.Response.Headers.CacheControl = "no-store";
|
||||||
|
HttpContext.Response.Headers.RetryAfter = "5";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
|
@page "/strategie"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
|
<PageTitle>Strategie · Anubis</PageTitle>
|
||||||
|
|
||||||
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
var working = v.Cards.Where(x => x.Stage.Stage != StrategyStages.Observation).ToList();
|
||||||
|
var watching = v.Cards.Where(x => x.Stage.Stage == StrategyStages.Observation).ToList();
|
||||||
|
}
|
||||||
|
@if (_message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice @(_ok ? "notice-gain" : "notice-loss")" role="status"><Icon Name="@(_ok ? "check" : "alert")" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
<section class="panel" aria-labelledby="percorso">
|
||||||
|
<h2 id="percorso">Il percorso verso i soldi veri <span class="note">Una strategia avanza solo se supera tutti i requisiti e se lo confermi tu. Se peggiora, torna indietro da sola.</span></h2>
|
||||||
|
<ol class="stages">
|
||||||
|
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
|
||||||
|
{
|
||||||
|
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
|
||||||
|
<li class="@(here.Count > 0 ? "here" : null)">
|
||||||
|
<span class="step">@(i + 1)</span>
|
||||||
|
<strong>@Capital(StrategyStages.Label(stage))</strong>
|
||||||
|
<p>@StageText(stage)</p>
|
||||||
|
<p class="stage-count">
|
||||||
|
@if (here.Count == 0)
|
||||||
|
{
|
||||||
|
<span class="muted">Nessuna strategia</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@foreach (var x in here)
|
||||||
|
{
|
||||||
|
<span class="swatch round" style="background: @x.Color"></span>
|
||||||
|
}
|
||||||
|
<strong>@(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")</strong>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@foreach (var s in working)
|
||||||
|
{
|
||||||
|
var up = s.ResultEur >= 0;
|
||||||
|
<section class="panel strategy" aria-label="@s.Name">
|
||||||
|
<div class="strategy-about">
|
||||||
|
<h2><span class="swatch round" style="background: @s.Color"></span>@s.Name <span class="tag">@(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))</span></h2>
|
||||||
|
<p>@s.Description</p>
|
||||||
|
<ul>
|
||||||
|
@foreach (var rule in s.Rules)
|
||||||
|
{
|
||||||
|
<li>@rule</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<p class="note">Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).</p>
|
||||||
|
</div>
|
||||||
|
<div class="strategy-result">
|
||||||
|
<p class="strategy-number">@Shell.Money(s.ResultEur, c, withSign: true) <span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(s.ResultPercent, 2, withSign: true)</span></p>
|
||||||
|
@if (s.Curve.Count > 1)
|
||||||
|
{
|
||||||
|
var min = s.Curve.Min(p => p.Index);
|
||||||
|
var max = s.Curve.Max(p => p.Index);
|
||||||
|
var range = Math.Max(0.0001m, max - min);
|
||||||
|
var points = string.Join(' ', s.Curve.Select((p, i) => Css(i * 300m / (s.Curve.Count - 1)) + "," + Css(70m - (p.Index - min) / range * 60m)));
|
||||||
|
<svg class="spark" viewBox="0 0 300 80" role="img" aria-label="Andamento della strategia"><polyline points="@points" style="stroke: @s.Color" /></svg>
|
||||||
|
}
|
||||||
|
<dl class="account-lines">
|
||||||
|
<dt>Calo peggiore</dt><dd><strong>@Format.Percent(s.WorstFall * 100m, 1)</strong></dd>
|
||||||
|
<dt>Operazioni chiuse</dt><dd><strong>@s.Closed@(s.Closed > 0 ? $", di cui {s.Winners} in guadagno" : "")</strong></dd>
|
||||||
|
<dt>Posizioni aperte</dt><dd><strong>@(s.Open.Count == 0 ? "nessuna" : string.Join(", ", s.Open.Distinct()))</strong></dd>
|
||||||
|
@if (s.TwinGap is { } gap)
|
||||||
|
{
|
||||||
|
<dt>Rispetto al gemello simulato</dt><dd><strong>@Format.Percent(gap, 2, withSign: true)</strong> <span class="muted">del capitale usato</span></dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="strategy-steps">
|
||||||
|
<h3>Requisiti per @(s.Stage.Stage == StrategyStages.Reduced ? "il reale pieno" : StrategyStages.IsLive(s.Stage.Stage) ? "restare con soldi veri" : "usare soldi veri")</h3>
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var r in s.Requirements)
|
||||||
|
{
|
||||||
|
<li class="@(r.Met ? "ok" : StrategiesView.IsPending(r) ? "wait" : "warn")">
|
||||||
|
<Icon Name="@(r.Met ? "tick" : StrategiesView.IsPending(r) ? "clock" : "alert")" Size="16" />
|
||||||
|
<span><strong>@r.Label</strong>: @r.Value <span class="muted">(@r.Target)</span></span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (s.Stage.ExitOnly)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.</p>
|
||||||
|
}
|
||||||
|
@if (StrategyStages.IsLive(s.Stage.Stage) && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn btn-danger" type="submit" data-confirm="Togli i soldi veri a questa strategia: torna in simulazione e le posizioni vere restano in sola uscita fino a zero. Confermi?">Togli i soldi veri</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
@if (s.Stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
|
||||||
|
{
|
||||||
|
var target = s.Stage.Stage == StrategyStages.Reduced ? "Passa al reale" : "Passa al reale ridotto";
|
||||||
|
var broker = StrategyNames.BrokerOf(s.Stage.Strategy);
|
||||||
|
var accounts = v.LiveAccounts.Where(a => a.Broker == broker).ToList();
|
||||||
|
if (!s.AllMet)
|
||||||
|
{
|
||||||
|
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")</span></p>
|
||||||
|
@if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r)))
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Per ora non merita soldi veri. Resta in simulazione finché non migliora.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<details class="confirm-live">
|
||||||
|
<summary class="btn">@target</summary>
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/reale" class="form-grid">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Ecco cosa cambia:</p>
|
||||||
|
<ul class="confirm-summary">
|
||||||
|
@foreach (var line in s.Summary)
|
||||||
|
{
|
||||||
|
<li>@line</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<p>Per confermare scrivi la frase qui sotto e la tua password.</p>
|
||||||
|
<label>Conto reale
|
||||||
|
<select name="conto" required>
|
||||||
|
@foreach (var a in accounts)
|
||||||
|
{
|
||||||
|
<option value="@a.Id">@a.Name</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>Scrivi: <code>@s.Phrase</code><input name="frase" required autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" required autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
<button class="btn btn-danger" type="submit">Conferma soldi veri</button>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (s.Stage.Stage == StrategyStages.Simulation && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn btn-small" type="submit" data-confirm="Riporta la strategia in osservazione: smette di operare nel simulatore. Confermi?">Riporta in osservazione</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="plain" aria-labelledby="osservazione">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="osservazione">In osservazione</h2>
|
||||||
|
<a href="/laboratorio">Prova una nuova strategia nel laboratorio</a>
|
||||||
|
</div>
|
||||||
|
@if (watching.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna strategia di base in osservazione.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="observing">
|
||||||
|
@foreach (var s in watching)
|
||||||
|
{
|
||||||
|
var report = StrategiesView.ReportOf(s.Stage);
|
||||||
|
var passed = s.Stage.Qualification?.Passed == true;
|
||||||
|
<dt>@s.Name</dt>
|
||||||
|
<dd>
|
||||||
|
<span>@StrategiesView.ObservationReason(s.Stage)@if (report is not null) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||||
|
@if (passed && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/simulazione"><AntiforgeryToken /><button class="btn btn-small" type="submit">Porta in simulazione</button></form>
|
||||||
|
}
|
||||||
|
else if (!passed)
|
||||||
|
{
|
||||||
|
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")</span>
|
||||||
|
}
|
||||||
|
</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private StrategiesView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
private string? _message;
|
||||||
|
private bool _ok;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await StrategiesView.LoadAsync(services, Clock, TradingConsent.From(Host.Config).AllowLive, ct);
|
||||||
|
(_message, _ok) = (Ok, Errore) switch
|
||||||
|
{
|
||||||
|
("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true),
|
||||||
|
("osservazione", _) => ("Fatto: la strategia è in osservazione.", true),
|
||||||
|
("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true),
|
||||||
|
(_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false),
|
||||||
|
(_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false),
|
||||||
|
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
|
||||||
|
(_, "password") => ("Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti.", false),
|
||||||
|
(_, "requisiti") => ("Non tutti i requisiti sono soddisfatti.", false),
|
||||||
|
(_, "conto") => ("Il conto scelto non è il conto reale del broker di questa strategia.", false),
|
||||||
|
(_, "consenso") => ("La configurazione d'avvio non consente i soldi veri.", false),
|
||||||
|
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
|
||||||
|
_ => (null, false),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string StageText(string stage) => stage switch
|
||||||
|
{
|
||||||
|
StrategyStages.Observation => "Produce solo segnali, nessun ordine.",
|
||||||
|
StrategyStages.Simulation => $"Ordini finti su prezzi veri, per almeno {StageBook.SimulationDays} giorni.",
|
||||||
|
StrategyStages.Reduced => "Soldi veri, con un quarto del capitale.",
|
||||||
|
_ => "Soldi veri, rischio pieno.",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@* A screen whose content arrives with a later phase: it says so plainly instead of showing invented numbers (SPEC 13.1). *@
|
||||||
|
<section class="panel empty">
|
||||||
|
<p class="empty-title">@Title</p>
|
||||||
|
<p>@ChildContent</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public string Title { get; set; } = "";
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public RenderFragment? ChildContent { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<Router AppAssembly="typeof(App).Assembly">
|
||||||
|
<Found Context="routeData">
|
||||||
|
<RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
|
||||||
|
</Found>
|
||||||
|
</Router>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>Titles of the service page, also used in plain answers while the application is not ready.</summary>
|
||||||
|
internal static class ServiceText
|
||||||
|
{
|
||||||
|
public static string Title(HostMode mode) => mode switch
|
||||||
|
{
|
||||||
|
HostMode.Starting => "Anubis si sta avviando",
|
||||||
|
HostMode.ConfigProblem => "Manca qualcosa nella configurazione d'avvio",
|
||||||
|
HostMode.FirstRun => "Anubis va configurato",
|
||||||
|
HostMode.DatabaseUnavailable => "Il database non risponde",
|
||||||
|
HostMode.SchemaProblem => "Il database non è compatibile con questa versione",
|
||||||
|
HostMode.IdentityProblem => "Il database non è quello di questa installazione",
|
||||||
|
_ => "Anubis",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Messages of the password forms.</summary>
|
||||||
|
internal static class PasswordMessages
|
||||||
|
{
|
||||||
|
public static string? For(string? code) => code switch
|
||||||
|
{
|
||||||
|
"diverse" => "Le due password non coincidono. Scrivile di nuovo.",
|
||||||
|
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
|
||||||
|
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
|
||||||
|
"attuale" => "La password attuale non è giusta.",
|
||||||
|
"demo" => "Nella modalità dimostrativa la password non si cambia.",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
@* The precision of the model week by week with the alarm line (SPEC 13.6, mockup 06). Weeks without enough cases leave no
|
||||||
|
point; the days on the axis keep the distance between the others. *@
|
||||||
|
@if (Weeks.Count >= 2)
|
||||||
|
{
|
||||||
|
var alarm = (decimal)(Anubis.Learning.Health.Alarm * 100);
|
||||||
|
var lo = Math.Min(Weeks.Min(w => w.Precision), alarm) - 4m;
|
||||||
|
var hi = Math.Max(Weeks.Max(w => w.Precision), alarm) + 4m;
|
||||||
|
var (first, last) = (Weeks[0], Weeks[^1]);
|
||||||
|
var lowest = Weeks.MinBy(w => w.Precision)!;
|
||||||
|
decimal X(LearningWeek w) => (w.Monday.DayNumber - first.Monday.DayNumber) * 1000m / (last.Monday.DayNumber - first.Monday.DayNumber);
|
||||||
|
decimal Y(decimal v) => (hi - v) / (hi - lo) * 1000m;
|
||||||
|
<figure class="weekly" aria-label="Precisione settimana per settimana">
|
||||||
|
<figcaption class="note">Precisione settimana per settimana</figcaption>
|
||||||
|
<div class="weekly-box">
|
||||||
|
<div class="chart-plot">
|
||||||
|
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||||
|
<line class="bench" x1="0" x2="1000" y1="@Css(Y(alarm))" y2="@Css(Y(alarm))" vector-effect="non-scaling-stroke" />
|
||||||
|
<polyline class="equity" points="@string.Join(" ", Weeks.Select(w => Css(X(w)) + "," + Css(Y(w.Precision))))" vector-effect="non-scaling-stroke" />
|
||||||
|
</svg>
|
||||||
|
@foreach (var w in Weeks)
|
||||||
|
{
|
||||||
|
<span class="end-dot hover-dot @(w == last || w == lowest ? null : "quiet")" style="left:@Pct(X(w) / 10);top:@Pct(Y(w.Precision) / 10)"><span class="hover-box">Settimana del @Day(w.Monday)<br />@w.Precision%</span></span>
|
||||||
|
}
|
||||||
|
@if (lowest != last)
|
||||||
|
{
|
||||||
|
<span class="point-label under" style="left:@Pct(X(lowest) / 10);top:@Pct(Y(lowest.Precision) / 10)">@lowest.Precision%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="weekly-side" aria-hidden="true">
|
||||||
|
<strong style="top:@Pct(Math.Min(Y(last.Precision), Y(alarm) - 300m) / 10)">@last.Precision%</strong>
|
||||||
|
<span style="top:@Pct(Y(alarm) / 10)">allarme<br />sotto @Format.Number(alarm)%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="weekly-x note" aria-hidden="true"><span>@Day(first.Monday)</span><span>@Day(last.Monday)</span></div>
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Vedi i numeri in una tabella</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Settimana dal lunedì</th><th scope="col" class="num">Precisione</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var w in Weeks.Reverse())
|
||||||
|
{
|
||||||
|
<tr><td>@Format.LongDate(w.Monday)</td><td class="num">@w.Precision%</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</figure>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public IReadOnlyList<LearningWeek> Weeks { get; set; } = [];
|
||||||
|
|
||||||
|
private static string Day(DateOnly day) => day.ToString("d MMM", CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
@using System.Globalization
|
||||||
|
@using Microsoft.AspNetCore.Authorization
|
||||||
|
@using Microsoft.AspNetCore.Components
|
||||||
|
@using Microsoft.AspNetCore.Components.Forms
|
||||||
|
@using Microsoft.AspNetCore.Components.Routing
|
||||||
|
@using Microsoft.AspNetCore.Components.Web
|
||||||
|
@using Anubis
|
||||||
|
@using Anubis.Access
|
||||||
|
@using Anubis.Core
|
||||||
|
@using Anubis.Db
|
||||||
|
@using Anubis.Platform
|
||||||
|
@using Anubis.Server
|
||||||
|
@using Anubis.Server.Components
|
||||||
|
@using Anubis.Server.Components.Layout
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command line tools for the data (Phase 2): the quality report, and the imports into the research history of the
|
||||||
|
/// data folder (SPEC 6.6). They read the same startup configuration as the server.
|
||||||
|
/// </summary>
|
||||||
|
internal static class DataCommand
|
||||||
|
{
|
||||||
|
private const string Usage =
|
||||||
|
"Uso: anubis data report [--days N] [--out file.md]\n" +
|
||||||
|
" anubis data binance <SIMBOLO> <1d|1m> <AAAA-MM> (per esempio BTCUSDT 1d 2017-08)\n" +
|
||||||
|
" anubis data csv <file.csv> (colonne descritte in file.mapping.json o mapping.json)\n" +
|
||||||
|
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||||
|
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||||
|
HttpMessageHandler? handler = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 1 || args[0] is not ("report" or "binance" or "csv"))
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (positional, rest) = Split(args[1..]);
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var options = ServerOptions.Parse([.. rest], environment);
|
||||||
|
var config = options.LoadConfig(environment);
|
||||||
|
var clock = new SystemClock();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
switch (args[0])
|
||||||
|
{
|
||||||
|
case "report":
|
||||||
|
return await ReportAsync(config, clock, rest, output).ConfigureAwait(false);
|
||||||
|
case "binance" when positional.Count == 3:
|
||||||
|
config.Data.Ensure();
|
||||||
|
var month = DateOnly.ParseExact(positional[2] + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture);
|
||||||
|
using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false))
|
||||||
|
{
|
||||||
|
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||||
|
var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), new ResearchStore(config.Data.Research), clock);
|
||||||
|
await WriteAsync(output, await importer.ImportAsync(positional[0].ToUpperInvariant(), positional[1], month.Year, month.Month, CancellationToken.None)
|
||||||
|
.ConfigureAwait(false)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
case "csv" when positional.Count == 1:
|
||||||
|
config.Data.Ensure();
|
||||||
|
var file = Path.GetFullPath(positional[0]);
|
||||||
|
var result = await new CsvImporter(new ResearchStore(config.Data.Research)).ImportAsync(file, CsvImporter.MappingFor(file), CancellationToken.None)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
await WriteAsync(output, result).ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
default:
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or System.Text.Json.JsonException
|
||||||
|
or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<int> ReportAsync(Platform.StartupConfig config, IClock clock, IReadOnlyList<string> rest, TextWriter output)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
var days = Option(rest, "--days") is { } d ? int.Parse(d, CultureInfo.InvariantCulture) : 7;
|
||||||
|
await using var db = Database.Open(config.Db!, allowCreate: false);
|
||||||
|
var markdown = (await QualityReport.BuildAsync(db, clock, TimeSpan.FromDays(days), CancellationToken.None).ConfigureAwait(false)).ToMarkdown();
|
||||||
|
if (Option(rest, "--out") is { } path)
|
||||||
|
{
|
||||||
|
await File.WriteAllTextAsync(path, markdown).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync("Rapporto scritto in " + Path.GetFullPath(path)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await output.WriteAsync(markdown).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task WriteAsync(TextWriter output, ImportResult result)
|
||||||
|
{
|
||||||
|
var lines = new List<string>
|
||||||
|
{
|
||||||
|
string.Create(CultureInfo.InvariantCulture,
|
||||||
|
$"{result.Venue} {result.Symbol} {result.Timeframe}: {result.Bars} barre, dal {result.First:yyyy-MM-dd HH:mm} al {result.Last:yyyy-MM-dd HH:mm} (UTC)."),
|
||||||
|
};
|
||||||
|
lines.AddRange(result.Notes.Select(n => "- " + n));
|
||||||
|
return output.WriteLineAsync(string.Join(Environment.NewLine, lines));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(IReadOnlyList<string> args, string name)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < args.Count - 1; i++)
|
||||||
|
{
|
||||||
|
if (args[i] == name)
|
||||||
|
{
|
||||||
|
return args[i + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Positional arguments come first; from the first "--" option on, everything is options.
|
||||||
|
private static (List<string> Positional, List<string> Options) Split(string[] args)
|
||||||
|
{
|
||||||
|
var index = Array.FindIndex(args, a => a.StartsWith("--", StringComparison.Ordinal));
|
||||||
|
return index < 0 ? (args.ToList(), []) : (args[..index].ToList(), args[index..].ToList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Platform;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command line export and import (SPEC 5.4), the way to change engine: with the server stopped, export from the old
|
||||||
|
/// database, point the configuration to the new one, import. The import goes only into an empty database and renews
|
||||||
|
/// the installation fingerprint, so the old copy is no longer accepted (SPEC 15.1).
|
||||||
|
/// </summary>
|
||||||
|
internal static class DatabaseCommand
|
||||||
|
{
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 2 || args[0] is not ("export" or "import"))
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Uso: anubis db export <cartella> | anubis db import <cartella> [--platform docker|desktop] [--data-dir <cartella>]").ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var options = ServerOptions.Parse(args[2..], environment);
|
||||||
|
var config = options.LoadConfig(environment);
|
||||||
|
if (!config.IsComplete)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("La configurazione d'avvio non è completa:").ConfigureAwait(false);
|
||||||
|
foreach (var problem in config.Problems)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync($"- {problem.Setting}: {problem.What} {problem.Remedy}").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Redactor.Register(config.Db!.Password);
|
||||||
|
var clock = new SystemClock();
|
||||||
|
var folder = Path.GetFullPath(args[1]);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile));
|
||||||
|
if (args[0] == "export")
|
||||||
|
{
|
||||||
|
var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync($"Esportate {index.Tables.Sum(t => t.Count)} righe di {index.Tables.Count} tabelle in {folder}.").ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
config.Data.Ensure();
|
||||||
|
var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false);
|
||||||
|
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " +
|
||||||
|
"Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,474 @@
|
|||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Access;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Platform;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>Answer of <c>GET /health</c>.</summary>
|
||||||
|
internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary<string, string>? Checks = null);
|
||||||
|
|
||||||
|
internal sealed record SettingBody(string Value);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The REST and WebSocket skeleton (issue #12) and the form actions of the service pages. The API answers JSON with
|
||||||
|
/// Italian messages, needs a session, and every request that changes something carries the CSRF token in a header.
|
||||||
|
/// </summary>
|
||||||
|
internal static partial class Endpoints
|
||||||
|
{
|
||||||
|
public const string CsrfHeader = "X-Anubis-Csrf";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
|
public static void Map(WebApplication app)
|
||||||
|
{
|
||||||
|
app.MapGet("/health", HealthAsync).AllowAnonymous();
|
||||||
|
app.MapGet("/brand/{file}", Brand).AllowAnonymous();
|
||||||
|
app.MapGet("/assets/{file}", Asset).AllowAnonymous();
|
||||||
|
app.MapGet("/favicon.ico", () => Brand("anubis.ico")).AllowAnonymous();
|
||||||
|
|
||||||
|
MapApi(app);
|
||||||
|
app.Map("/ws", StatusSocketAsync).RequireAuthorization();
|
||||||
|
Forms.Map(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Healthy only when the database answers and the scheduler loop is alive (SPEC 15.2); the body says why not.
|
||||||
|
private static async Task<IResult> HealthAsync(AnubisHost host, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var status = host.Status;
|
||||||
|
var checks = new Dictionary<string, string>(StringComparer.Ordinal) { ["mode"] = status.Mode.ToString() };
|
||||||
|
var healthy = status.Mode == HostMode.Ready;
|
||||||
|
if (host.Services is { } services)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||||
|
await services.Db.PingAsync(timeout.Token).ConfigureAwait(false);
|
||||||
|
checks["database"] = "ok";
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
checks["database"] = "non risponde";
|
||||||
|
healthy = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo";
|
||||||
|
healthy &= host.SchedulerRunning;
|
||||||
|
}
|
||||||
|
|
||||||
|
var body = new HealthResponse(healthy ? "ok" : "unavailable", AnubisInfo.Name, AnubisInfo.Version, status.Mode.ToString(), checks);
|
||||||
|
return Results.Json(body, _json, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The logo comes only from docs/design/logo, embedded at build time (ADR 0005).
|
||||||
|
private static IResult Brand(string file) => Embedded("Anubis.Server.Brand." + file, file);
|
||||||
|
|
||||||
|
private static IResult Asset(string file) => Embedded("Anubis.Server.Assets." + file, file);
|
||||||
|
|
||||||
|
private static IResult Embedded(string resource, string file)
|
||||||
|
{
|
||||||
|
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
|
||||||
|
if (stream is null)
|
||||||
|
{
|
||||||
|
return Results.NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
var type = Path.GetExtension(file) switch
|
||||||
|
{
|
||||||
|
".svg" => "image/svg+xml",
|
||||||
|
".png" => "image/png",
|
||||||
|
".ico" => "image/x-icon",
|
||||||
|
".css" => "text/css; charset=utf-8",
|
||||||
|
".js" => "text/javascript; charset=utf-8",
|
||||||
|
".ttf" => "font/ttf",
|
||||||
|
".txt" => "text/plain; charset=utf-8",
|
||||||
|
_ => "application/octet-stream",
|
||||||
|
};
|
||||||
|
return Results.Stream(stream, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void MapApi(WebApplication app)
|
||||||
|
{
|
||||||
|
var api = app.MapGroup("/api").RequireAuthorization().AddEndpointFilter(CsrfFilterAsync);
|
||||||
|
|
||||||
|
api.MapGet("/antiforgery", (HttpContext context, IAntiforgery antiforgery) =>
|
||||||
|
{
|
||||||
|
var tokens = antiforgery.GetAndStoreTokens(context);
|
||||||
|
return Results.Json(new { header = CsrfHeader, token = tokens.RequestToken }, _json);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.MapGet("/status", async (AnubisHost host, ShellData shell, CancellationToken ct) => Results.Json(await shell.SnapshotAsync(ct).ConfigureAwait(false), _json));
|
||||||
|
|
||||||
|
api.MapGet("/me", (HttpContext context) => Results.Json(new
|
||||||
|
{
|
||||||
|
username = context.User.Identity?.Name,
|
||||||
|
mustChangePassword = CurrentUser.MustChangePassword(context.User),
|
||||||
|
hasSecondFactor = CurrentUser.HasSecondFactor(context.User),
|
||||||
|
}, _json));
|
||||||
|
|
||||||
|
api.MapGet("/settings", async (AnubisHost host, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var services = host.Services!;
|
||||||
|
var values = new List<SettingValue>();
|
||||||
|
foreach (var definition in SettingsStore.All)
|
||||||
|
{
|
||||||
|
values.Add(await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Json(values, _json);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.MapPut("/settings/{key}", async (string key, SettingBody body, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
if (key == SettingsStore.BotState.Key)
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Risk limits go only through the settings page, which checks their order and asks for the confirmation of
|
||||||
|
// SPEC 12.4 when a limit goes up while a strategy uses real money: the check holds on the API too.
|
||||||
|
if (Anubis.Risk.RiskSettings.All.Any(d => d.Key == key))
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same for what lets the model shrink less.
|
||||||
|
if (Anubis.Learning.LearningSettings.All.Any(d => d.Key == key))
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.MapGet("/settings/history", async (AnubisHost host, CancellationToken ct) =>
|
||||||
|
Results.Json(await host.Services!.Settings.HistoryAsync(null, 100, ct).ConfigureAwait(false), _json));
|
||||||
|
|
||||||
|
// Data quality report (SPEC 6.4): JSON, or Markdown with ?format=md.
|
||||||
|
api.MapGet("/data/quality", async (AnubisHost host, IClock clock, int? days, string? format, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var report = await QualityReport.BuildAsync(host.Services!.Db, clock, TimeSpan.FromDays(Math.Clamp(days ?? 7, 1, 3650)), ct).ConfigureAwait(false);
|
||||||
|
return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The open positions of the Conti screen as CSV (SPEC 13.6), all accounts or one broker's.
|
||||||
|
api.MapGet("/conti/posizioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? conto, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var view = await AccountsView.LoadAsync(host.Services!, clock, shell.Zone, ct).ConfigureAwait(false);
|
||||||
|
var broker = conto is Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca ? conto : null;
|
||||||
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv(broker))).ToArray(),
|
||||||
|
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
|
||||||
|
});
|
||||||
|
|
||||||
|
// The closed trades of the Operazioni screen as CSV (SPEC 13.6), with the same filters as the page.
|
||||||
|
api.MapGet("/operazioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? cerca, string? conto, string? strategia, string? esito, string? periodo,
|
||||||
|
CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var filter = TradeFilter.Parse(cerca, conto, strategia, esito, periodo, null);
|
||||||
|
var view = await TradesView.LoadAsync(host.Services!, clock, filter, int.MaxValue, ct).ConfigureAwait(false);
|
||||||
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv())).ToArray(),
|
||||||
|
"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) =>
|
||||||
|
{
|
||||||
|
var services = host.Services!;
|
||||||
|
var market = services.MarketData;
|
||||||
|
return Results.Json(new
|
||||||
|
{
|
||||||
|
enabled = market is not null,
|
||||||
|
live = market?.LiveConnected ?? false,
|
||||||
|
lastHistoryRun = market?.LastHistoryRun,
|
||||||
|
sources = await new SourceStateStore(services.Db, clock).ListAsync(ct).ConfigureAwait(false),
|
||||||
|
freshness = market?.Freshness.Snapshot() ?? [],
|
||||||
|
}, _json);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Only whether a secret is set and where it comes from: the value never leaves the server (SPEC 15.4).
|
||||||
|
api.MapGet("/secrets/{name}", async (string name, AnubisHost host, CancellationToken ct) =>
|
||||||
|
Results.Json(await host.Services!.Secrets.StatusAsync(name, ct).ConfigureAwait(false), _json));
|
||||||
|
|
||||||
|
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
api.MapGet("/jobs", async (AnubisHost host, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var services = host.Services!;
|
||||||
|
var last = await services.Db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT name, description, last_due_at, last_finished_at, last_outcome, last_error FROM jobs ORDER BY name",
|
||||||
|
r => new
|
||||||
|
{
|
||||||
|
name = r.Text("name"),
|
||||||
|
description = r.Text("description"),
|
||||||
|
lastDue = r.MomentOrNull("last_due_at"),
|
||||||
|
lastFinished = r.MomentOrNull("last_finished_at"),
|
||||||
|
outcome = r.TextOrNull("last_outcome"),
|
||||||
|
error = r.TextOrNull("last_error")
|
||||||
|
}), ct).ConfigureAwait(false);
|
||||||
|
return Results.Json(new { upcoming = services.Scheduler.Upcoming(20), last }, _json);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method))
|
||||||
|
{
|
||||||
|
var antiforgery = http.RequestServices.GetRequiredService<IAntiforgery>();
|
||||||
|
if (!await antiforgery.IsRequestValidAsync(http).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "csrf", "Richiesta senza il gettone di sicurezza: ricarica la pagina e riprova.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return await next(context).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static async Task<IResult> SetSettingAsync(AnubisHost host, string key, string value, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await host.Services!.Settings.SetAsync(key, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||||
|
return Results.NoContent();
|
||||||
|
}
|
||||||
|
catch (ReadOnlySettingException ex)
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status409Conflict, "sola_lettura", ex.Message);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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, string by, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var settings = host.Services!.Settings;
|
||||||
|
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
||||||
|
|
||||||
|
// A switch tripped by the fall from the high stops only its world and leaves the bot "active": the restart is
|
||||||
|
// the user's confirmation for that world too (SPEC 9.2, 9.3).
|
||||||
|
var tripped = host.Services.Trading?.Risk is { } engine && await engine.AnyTrippedAsync(ct).ConfigureAwait(false);
|
||||||
|
var target = command switch
|
||||||
|
{
|
||||||
|
"pause" or "pausa" when current == "active" => "paused",
|
||||||
|
"resume" or "riprendi" when current == "paused" => "active",
|
||||||
|
"stop" or "ferma" => "stopped",
|
||||||
|
"close" or "chiudi" => "stopped",
|
||||||
|
"restart" or "riattiva" when current == "stopped" => "active",
|
||||||
|
"restart" or "riattiva" when tripped => current,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
if (target is null)
|
||||||
|
{
|
||||||
|
return (false, current == "stopped"
|
||||||
|
? "Dopo \"Ferma tutto\" il bot non riprende da solo: riattivalo dalla pagina Rischio."
|
||||||
|
: "Comando non ammesso nello stato attuale del bot.");
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
switch (command)
|
||||||
|
{
|
||||||
|
case "stop" or "ferma":
|
||||||
|
await risk.StopAllAsync(trading.Managers, by, "manual_stop", "Ferma tutto dall'interfaccia: annullo gli ordini in attesa e non apro posizioni. Gli stop restano.", ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return (true, target);
|
||||||
|
case "close" or "chiudi":
|
||||||
|
await risk.CloseAllAsync(trading.Managers, by, ct).ConfigureAwait(false);
|
||||||
|
return (true, target);
|
||||||
|
case "restart" or "riattiva":
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
return (false, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cross-site WebSocket hijacking: the page must come from this same server.
|
||||||
|
var origin = context.Request.Headers.Origin.ToString();
|
||||||
|
if (origin.Length > 0 && (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
|
||||||
|
!string.Equals(originUri.Authority, context.Request.Host.Value, StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
||||||
|
using var settings = bus.Subscribe<SettingChanged>(16);
|
||||||
|
using var modes = bus.Subscribe<HostChanged>(16);
|
||||||
|
var aborted = context.RequestAborted;
|
||||||
|
var receive = DrainAsync(socket, aborted);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
|
||||||
|
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
||||||
|
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
|
||||||
|
|
||||||
|
using var wait = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
||||||
|
wait.CancelAfter(TimeSpan.FromSeconds(5));
|
||||||
|
var changed = Task.WhenAny(Next(settings, wait.Token), Next(modes, wait.Token));
|
||||||
|
await Task.WhenAny(changed, receive, Task.Delay(Timeout.Infinite, wait.Token)).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Stop the reader that lost, or it would swallow the next event of its kind.
|
||||||
|
await wait.CancelAsync().ConfigureAwait(false);
|
||||||
|
if (receive.IsCompleted)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// Answer the client's close, or start ours. Output only: the drain loop may still be receiving.
|
||||||
|
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var closing = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||||
|
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closing.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.WhenAny(receive, Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task Next<T>(EventSubscription<T> subscription, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await foreach (var _ in subscription.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task DrainAsync(WebSocket socket, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var buffer = new byte[1024];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (socket.State == WebSocketState.Open)
|
||||||
|
{
|
||||||
|
var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (result.MessageType == WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Compares two secrets in constant time.</summary>
|
||||||
|
internal static bool SameSecret(string? given, string? expected) =>
|
||||||
|
given is not null && expected is not null &&
|
||||||
|
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(given)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,140 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Diagnostics;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Structured logs (SPEC 2.2, issue #10): one JSON object per line on the console and in a daily file under
|
||||||
|
/// data/logs, every text passed through the <see cref="Redactor"/> so no secret reaches a log. The last 14 files are kept.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class JsonLogProvider : ILoggerProvider
|
||||||
|
{
|
||||||
|
public const int KeepFiles = 14;
|
||||||
|
|
||||||
|
private readonly string? _folder;
|
||||||
|
private readonly IClock _clock;
|
||||||
|
private readonly bool _console;
|
||||||
|
private readonly Lock _gate = new();
|
||||||
|
private readonly ConcurrentDictionary<string, JsonLogger> _loggers = new(StringComparer.Ordinal);
|
||||||
|
private StreamWriter? _file;
|
||||||
|
private string? _fileDay;
|
||||||
|
|
||||||
|
public JsonLogProvider(string? folder, IClock clock, bool console)
|
||||||
|
{
|
||||||
|
_folder = folder;
|
||||||
|
_clock = clock;
|
||||||
|
_console = console;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new JsonLogger(name, this));
|
||||||
|
|
||||||
|
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))
|
||||||
|
{
|
||||||
|
json.WriteStartObject();
|
||||||
|
json.WriteString("at", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture));
|
||||||
|
json.WriteString("level", level.ToString().ToLowerInvariant());
|
||||||
|
json.WriteString("category", category);
|
||||||
|
if (eventId.Id != 0)
|
||||||
|
{
|
||||||
|
json.WriteNumber("event", eventId.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
json.WriteString("message", Redactor.Redact(message));
|
||||||
|
if (exception is not null)
|
||||||
|
{
|
||||||
|
json.WriteString("error", Redactor.Redact(exception.GetType().Name + ": " + exception.Message));
|
||||||
|
json.WriteString("stack", Redactor.Redact(exception.StackTrace));
|
||||||
|
}
|
||||||
|
|
||||||
|
json.WriteEndObject();
|
||||||
|
}
|
||||||
|
|
||||||
|
var line = Encoding.UTF8.GetString(buffer.ToArray());
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_console)
|
||||||
|
{
|
||||||
|
Console.Out.WriteLine(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteFile(now, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WriteFile(DateTimeOffset now, string line)
|
||||||
|
{
|
||||||
|
if (_folder is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var day = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
|
||||||
|
if (_file is null || _fileDay != day)
|
||||||
|
{
|
||||||
|
_file?.Dispose();
|
||||||
|
Directory.CreateDirectory(_folder);
|
||||||
|
_file = new StreamWriter(new FileStream(Path.Combine(_folder, "anubis-" + day + ".log"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), new UTF8Encoding(false))
|
||||||
|
{
|
||||||
|
AutoFlush = true,
|
||||||
|
};
|
||||||
|
_fileDay = day;
|
||||||
|
Prune();
|
||||||
|
}
|
||||||
|
|
||||||
|
_file.WriteLine(line);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
// A full or read-only disk must not stop the application: the console still has the line.
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Prune()
|
||||||
|
{
|
||||||
|
foreach (var old in Directory.EnumerateFiles(_folder!, "anubis-*.log").OrderDescending(StringComparer.Ordinal).Skip(KeepFiles))
|
||||||
|
{
|
||||||
|
File.Delete(old);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_file?.Dispose();
|
||||||
|
_file = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class JsonLogger(string category, JsonLogProvider provider) : ILogger
|
||||||
|
{
|
||||||
|
public IDisposable? BeginScope<TState>(TState state)
|
||||||
|
where TState : notnull => null;
|
||||||
|
|
||||||
|
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
|
||||||
|
|
||||||
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||||
|
{
|
||||||
|
if (!IsEnabled(logLevel))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
provider.Write(category, logLevel, eventId, formatter(state, exception), exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>How the laboratory pages write the numbers of a backtest, in plain Italian (SPEC 13.3).</summary>
|
||||||
|
internal static class LabText
|
||||||
|
{
|
||||||
|
public const string Missing = "—";
|
||||||
|
|
||||||
|
/// <summary>A fraction as a percentage: 0,1234 is "12,3%".</summary>
|
||||||
|
public static string Percent(double? fraction, int decimals = 1, bool withSign = false) =>
|
||||||
|
fraction is { } x && double.IsFinite(x) ? Format.Percent((decimal)(x * 100), decimals, withSign) : Missing;
|
||||||
|
|
||||||
|
public static string Number(double? value, int decimals = 2) =>
|
||||||
|
value is { } x && double.IsFinite(x) ? Format.Number((decimal)x, decimals) : Missing;
|
||||||
|
|
||||||
|
public static string Money(decimal value, string currency, bool withSign = false) => Format.Money(value, currency, withSign);
|
||||||
|
|
||||||
|
public static string Day(DateOnly? day) => day is { } d ? d.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) : Missing;
|
||||||
|
|
||||||
|
public static string Period(DateOnly from, DateOnly to) => $"{Day(from)} – {Day(to)}";
|
||||||
|
|
||||||
|
/// <summary>Parameters as the user reads them: "fast=20;slow=100" becomes "fast 20, slow 100".</summary>
|
||||||
|
public static string Parameters(string text) =>
|
||||||
|
string.IsNullOrEmpty(text) ? "nessun parametro" : string.Join(", ", text.Split(';').Select(p => p.Replace('=', ' ').Replace('.', ',')));
|
||||||
|
|
||||||
|
public static string Status(Trial trial, string? progress) => trial.Status switch
|
||||||
|
{
|
||||||
|
TrialStatuses.Planned => "In coda",
|
||||||
|
TrialStatuses.Running => progress is null ? "In corso" : "In corso: " + progress,
|
||||||
|
TrialStatuses.Failed => "Non riuscito",
|
||||||
|
_ => "Completato",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string Verdict(string? verdict) => verdict switch
|
||||||
|
{
|
||||||
|
TrialVerdicts.Passed => "Superato",
|
||||||
|
TrialVerdicts.Rejected => "Non superato",
|
||||||
|
_ => Missing,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string Source(TrialData data) => data.Source == TrialSources.Research
|
||||||
|
? "storico di ricerca " + Venue(data.Venue)
|
||||||
|
: "barre raccolte di " + Venue(data.Venue);
|
||||||
|
|
||||||
|
public static string Venue(string venue) => venue switch
|
||||||
|
{
|
||||||
|
"okx" => "OKX",
|
||||||
|
"alpaca" => "Alpaca",
|
||||||
|
"binance" => "Binance",
|
||||||
|
_ => venue,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string Symbols(IReadOnlyList<string> symbols) =>
|
||||||
|
symbols.Count <= 4 ? string.Join(", ", symbols) : string.Join(", ", symbols.Take(3)) + $" e altri {symbols.Count - 3}";
|
||||||
|
|
||||||
|
/// <summary>The value of a check, written in its unit.</summary>
|
||||||
|
public static string CheckValue(ReportCheck check, string currency) => check.Value is not { } v
|
||||||
|
? "non si applica"
|
||||||
|
: check.Unit switch
|
||||||
|
{
|
||||||
|
"money" => Format.Money((decimal)v, currency, withSign: true),
|
||||||
|
"percent" => Percent(v),
|
||||||
|
"count" => Format.Number((decimal)v),
|
||||||
|
_ => Number(v),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string CheckThreshold(ReportCheck check, string currency) => check.Comparison + " " + check.Unit switch
|
||||||
|
{
|
||||||
|
"money" => Format.Money((decimal)check.Threshold, currency),
|
||||||
|
"percent" => Percent(check.Threshold, 0),
|
||||||
|
"count" => Format.Number((decimal)check.Threshold),
|
||||||
|
_ => Number(check.Threshold),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>What the engine did not do as asked, in words.</summary>
|
||||||
|
public static string Note(string reason) => reason switch
|
||||||
|
{
|
||||||
|
BacktestReasons.NoCash => "Acquisti ridotti per mancanza di liquidità",
|
||||||
|
BacktestReasons.NoPrice => "Ordini senza prezzo di apertura",
|
||||||
|
BacktestReasons.UnknownSymbol => "Strumenti chiesti dalla strategia ma assenti dai dati",
|
||||||
|
BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate",
|
||||||
|
BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita",
|
||||||
|
BacktestReasons.Dividend => "Dividendi incassati",
|
||||||
|
_ when reason.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal) =>
|
||||||
|
"Decisioni cambiate da correttivi e rischio (" + ReasonTexts.Text(reason[BacktestReasons.AdjustedPrefix.Length..]).TrimEnd('.') + ")",
|
||||||
|
_ => "Ordini sotto il minimo dello strumento, non inviati",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Learning;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "anubis learning base": the first model (SPEC 11.2, issue #63). It rebuilds the examples of <c>crypto_trend</c> on the
|
||||||
|
/// history that "anubis backtest base" already downloaded and converted, trains, and writes the validation report and the
|
||||||
|
/// file that travels with the program. It never uses the network. The stock strategies wait for the Alpaca history.
|
||||||
|
/// </summary>
|
||||||
|
internal static class LearningCommand
|
||||||
|
{
|
||||||
|
private const string Usage =
|
||||||
|
"Uso: anubis learning base [--to AAAA-MM-GG] [--out docs/learning]\n" +
|
||||||
|
" Usa gli storici già scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||||
|
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 1 || args[0] != "base")
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rest = args[1..].ToList();
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
|
||||||
|
var now = new SystemClock().UtcNow;
|
||||||
|
var to = Option(rest, "--to") is { } t ? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture) : new DateOnly(now.Year, now.Month, 1).AddDays(-1);
|
||||||
|
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "learning"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(outDir);
|
||||||
|
var file = await FirstModel.BuildAsync(config.Data.Research, to, null, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.json"), FirstModel.ToJson(file)).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.md"),
|
||||||
|
FirstModel.Markdown(file, "anubis learning base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{file.Examples.Count} esempi, {file.Examples.Count(e => e.IsLabelled)} con un esito. ")
|
||||||
|
+ (file.Report is { } report ? report.Reason : "Nessun modello: esempi troppo pochi.")).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync("Rapporto scritto in " + outDir).ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or InvalidOperationException or FormatException or UnauthorizedAccessException or InvalidDataException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(List<string> args, string name)
|
||||||
|
{
|
||||||
|
var index = args.IndexOf(name);
|
||||||
|
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Learning;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>What the model is doing, for the badge and the sentences at the top.</summary>
|
||||||
|
internal static class LearningStates
|
||||||
|
{
|
||||||
|
/// <summary>No model yet: the night after the first start prepares it.</summary>
|
||||||
|
public const string None = "none";
|
||||||
|
|
||||||
|
public const string Observation = "observation";
|
||||||
|
public const string Active = "active";
|
||||||
|
|
||||||
|
/// <summary>Set aside on its own by the nightly check.</summary>
|
||||||
|
public const string Aside = "aside";
|
||||||
|
|
||||||
|
/// <summary>Set aside by the user.</summary>
|
||||||
|
public const string Manual = "manual";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A band of estimates: percentages as they are read, the point at the mean estimate.</summary>
|
||||||
|
public sealed record LearningBand(int From, int To, int Cases, decimal Estimated, decimal Observed)
|
||||||
|
{
|
||||||
|
public bool Solid => Cases >= Judge.BandMin;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record LearningWeight(string Name, int Share, bool Rest);
|
||||||
|
|
||||||
|
/// <summary>A column of the comparison between the model in charge and the one on trial.</summary>
|
||||||
|
internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout);
|
||||||
|
|
||||||
|
/// <summary>What was tried when a model was trained, the chosen one included.</summary>
|
||||||
|
internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen);
|
||||||
|
|
||||||
|
public sealed record LearningWeek(DateOnly Monday, int Precision);
|
||||||
|
|
||||||
|
/// <summary>A line of "Sorveglianza": <paramref name="State"/> is ok, warn or wait.</summary>
|
||||||
|
internal sealed record LearningCheck(string State, string Text);
|
||||||
|
|
||||||
|
internal sealed record LearningStory(string When, string Text);
|
||||||
|
|
||||||
|
/// <summary>The model box of the Panoramica: the same state in few words.</summary>
|
||||||
|
internal sealed record LearningSummary(string State, int Signals, int Needed, int? Precision, string Trained, string NextLabel, string NextCheck)
|
||||||
|
{
|
||||||
|
public string Sentence => State switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.",
|
||||||
|
LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.",
|
||||||
|
LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.",
|
||||||
|
LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.",
|
||||||
|
_ => "Il modello osserva e impara, ma non decide ancora.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Apprendimento screen (SPEC 13.6, mockup 06): what the model is doing, whether its probabilities can be trusted,
|
||||||
|
/// what it looks at, the model in charge against the challenger, the watch, the discoveries and the history. In demo mode
|
||||||
|
/// the numbers of appendix F.7 come from the aggregates.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record LearningView
|
||||||
|
{
|
||||||
|
/// <summary>The clues named one by one; the others are "Tutto il resto".</summary>
|
||||||
|
public const int NamedWeights = 9;
|
||||||
|
|
||||||
|
public const int StoryRows = 12;
|
||||||
|
|
||||||
|
private const string Fear = "Paura o avidità";
|
||||||
|
|
||||||
|
/// <summary>The pace is measured on the last four weeks, and needs at least one.</summary>
|
||||||
|
private const int PaceDays = 28;
|
||||||
|
|
||||||
|
private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
private static readonly string[] _numbers = ["zero", "una", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici"];
|
||||||
|
|
||||||
|
public required LearningSummary Summary { get; init; }
|
||||||
|
|
||||||
|
public required string Title { get; init; }
|
||||||
|
|
||||||
|
public required string Text { get; init; }
|
||||||
|
|
||||||
|
public string? Pace { get; init; }
|
||||||
|
|
||||||
|
/// <summary>With 300 signals done, what still stops it from counting.</summary>
|
||||||
|
public IReadOnlyList<string> Missing { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>"domenica 4 ottobre, versione 3".</summary>
|
||||||
|
public required string LastTraining { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningBand> Bands { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>The sentence under the calibration chart.</summary>
|
||||||
|
public string BandsText { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>True when the bands are those of the verification on the history, because the live ones are still too few.</summary>
|
||||||
|
public bool BandsFromHistory { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningWeight> Weights { get; init; } = [];
|
||||||
|
|
||||||
|
public string WeightsText { get; init; } = "";
|
||||||
|
|
||||||
|
public LearningVersion? Champion { get; init; }
|
||||||
|
|
||||||
|
public LearningVersion? Challenger { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The signals both estimated, with their outcome, and how many the next decision needs.</summary>
|
||||||
|
public int Pairs { get; init; }
|
||||||
|
|
||||||
|
public int PairsNeeded { get; init; }
|
||||||
|
|
||||||
|
/// <summary>No strategy with capital had examples when the model in charge was trained.</summary>
|
||||||
|
public bool GainOnReference { get; init; }
|
||||||
|
|
||||||
|
public string TrialTitle { get; init; } = "";
|
||||||
|
|
||||||
|
public string TrialText { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>How the model in charge was chosen, with everything that was tried.</summary>
|
||||||
|
public string? Choice { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningAttempt> Attempts { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Set when the last promotion can be taken back: the version that would return.</summary>
|
||||||
|
public int? UndoTo { get; init; }
|
||||||
|
|
||||||
|
public bool Anomaly { get; init; }
|
||||||
|
|
||||||
|
public bool Checked { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningCheck> Checks { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningWeek> Weeks { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningStory> Story { get; init; } = [];
|
||||||
|
|
||||||
|
// ---- Panoramica ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The few numbers of the Panoramica.</summary>
|
||||||
|
public static async Task<LearningSummary> SummaryAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(shell);
|
||||||
|
using var aggregates = shell.Aggregates();
|
||||||
|
if (aggregates is not null)
|
||||||
|
{
|
||||||
|
return DemoSummary(aggregates.RootElement.GetProperty("apprendimento"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var services = host.Services!;
|
||||||
|
var desk = new LearningDesk(services.Db, host.Clock, services.Settings);
|
||||||
|
var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningSummary Summarise(IReadOnlyList<ModelRow> models, int evaluated, CycleState state, bool aside, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
|
||||||
|
var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
|
||||||
|
var last = models.LastOrDefault(m => m.Version is not null);
|
||||||
|
var status = champion is null ? LearningStates.None
|
||||||
|
: aside ? LearningStates.Manual
|
||||||
|
: state.Aside is not null ? LearningStates.Aside
|
||||||
|
: state.ActivatedAt is not null ? LearningStates.Active
|
||||||
|
: LearningStates.Observation;
|
||||||
|
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now),
|
||||||
|
champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningSummary DemoSummary(JsonElement demo) => new(demo.GetProperty("stato").GetString()!, demo.GetProperty("segnali").GetInt32(), demo.GetProperty("necessari").GetInt32(),
|
||||||
|
demo.GetProperty("precisione_pct").GetInt32(), demo.GetProperty("ultimo_addestramento").GetString()!, "Prossima verifica dello sfidante", demo.GetProperty("prossima_verifica").GetString()!);
|
||||||
|
|
||||||
|
// ---- Page ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static async Task<LearningView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(shell);
|
||||||
|
using var aggregates = shell.Aggregates();
|
||||||
|
if (aggregates is not null)
|
||||||
|
{
|
||||||
|
return Demo(aggregates.RootElement.GetProperty("apprendimento"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var services = host.Services!;
|
||||||
|
var clock = host.Clock;
|
||||||
|
var desk = new LearningDesk(services.Db, clock, services.Settings);
|
||||||
|
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
|
||||||
|
var capitals = await LearningCycle.CapitalsAsync(services.Db, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return Of(snapshot, desk.BaseRates, capitals, aside, found, events, clock.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The page from what was read, without touching the database.</summary>
|
||||||
|
public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capitals, bool aside, DiscoverySet discoveries,
|
||||||
|
IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(snapshot);
|
||||||
|
ArgumentNullException.ThrowIfNull(discoveries);
|
||||||
|
ArgumentNullException.ThrowIfNull(events);
|
||||||
|
var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State);
|
||||||
|
var inCharge = snapshot.InCharge;
|
||||||
|
var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now);
|
||||||
|
var activation = ActivationCheck.Of(inCharge, baseRates, capitals);
|
||||||
|
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
|
||||||
|
var (title, text) = Words(summary, state, now);
|
||||||
|
|
||||||
|
// What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene".
|
||||||
|
var live = Judge.Bands(inCharge);
|
||||||
|
var history = !live.Any(b => b.Cases >= Judge.BandMin);
|
||||||
|
var verified = Verified(champion);
|
||||||
|
var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList();
|
||||||
|
var view = new LearningView
|
||||||
|
{
|
||||||
|
Summary = summary,
|
||||||
|
Title = title,
|
||||||
|
Text = text,
|
||||||
|
Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null,
|
||||||
|
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
|
||||||
|
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
|
||||||
|
Bands = bands,
|
||||||
|
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands, history ? null : activation.CalibrationError),
|
||||||
|
BandsFromHistory = history && bands.Count > 0,
|
||||||
|
Champion = Column(champion, now),
|
||||||
|
Challenger = Column(challenger, now),
|
||||||
|
Choice = champion?.Report.Reason is { Length: > 0 } reason ? reason : null,
|
||||||
|
Attempts = champion is null ? [] :
|
||||||
|
[
|
||||||
|
.. champion.Report.Attempts.Select(a =>
|
||||||
|
new LearningAttempt(LearnerNames.Label(a.Learner), Points(a.Combined.Precision), Round(a.Combined.Brier, 3), Round(a.Combined.GainWith, 2), a.Chosen)),
|
||||||
|
],
|
||||||
|
UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null,
|
||||||
|
Anomaly = state.Aside is not null,
|
||||||
|
Checked = state.Health is not null,
|
||||||
|
GainOnReference = champion?.Report.AllStrategiesCounted == true,
|
||||||
|
Found = discoveries.Found,
|
||||||
|
News = discoveries.News,
|
||||||
|
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
|
||||||
|
};
|
||||||
|
view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []);
|
||||||
|
if (champion is not null)
|
||||||
|
{
|
||||||
|
view = view with
|
||||||
|
{
|
||||||
|
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Health.Shown(w.Precision)))],
|
||||||
|
Checks = state.Health is not { } health ? []
|
||||||
|
: health.Version is { } seen && seen != champion.Version ? [new("wait", "Il modello in carica è cambiato: il primo controllo è alle 03:00. " + AlarmText(events, now))]
|
||||||
|
: ChecksOf(health, snapshot, champion, verified, events, now),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return champion is not null && challenger is not null
|
||||||
|
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), challenger.ThresholdDone, summary.NextCheck, champion.Version, challenger.Version)
|
||||||
|
: view with
|
||||||
|
{
|
||||||
|
TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.",
|
||||||
|
TrialText = champion is null ? "" : $"Il prossimo si addestra {At(summary.NextCheck)}, se nel frattempo ci sono casi nuovi.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero.";
|
||||||
|
const string Limits = "Non potrà mai ingrandirle, né aprirne di sue.";
|
||||||
|
const string Alone = "Le strategie proseguono senza di lui.";
|
||||||
|
return summary.State switch
|
||||||
|
{
|
||||||
|
LearningStates.None => ("Non ha ancora cominciato.", $"{How} La prima verifica, {At(summary.NextCheck)}, prepara il primo modello dai dati storici; da lì parte in osservazione."),
|
||||||
|
LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.",
|
||||||
|
$"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."),
|
||||||
|
LearningStates.Aside => ("Per ora è messo da parte.",
|
||||||
|
$"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."),
|
||||||
|
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione nuova; quelle già rimpicciolite restano così fino alla chiusura. Si riattiva da Impostazioni."),
|
||||||
|
_ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.",
|
||||||
|
$"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"),
|
||||||
|
_ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How long the missing signals take at the pace of the last four weeks.</summary>
|
||||||
|
public static string? PaceText(IReadOnlyList<Estimate> inCharge, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(inCharge);
|
||||||
|
var missing = ActivationCheck.Needed - inCharge.Count;
|
||||||
|
if (missing <= 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var today = DayOf(now);
|
||||||
|
if (inCharge.Count == 0 || (today.DayNumber - inCharge.Min(e => e.Case.Label!.ClosedDay!.Value).DayNumber) is not (>= 7 and var seen))
|
||||||
|
{
|
||||||
|
return "È presto per dire quanto manca.";
|
||||||
|
}
|
||||||
|
|
||||||
|
var days = Math.Min(PaceDays, seen);
|
||||||
|
var recent = inCharge.Count(e => e.Case.Label!.ClosedDay!.Value > today.AddDays(-days));
|
||||||
|
return recent == 0 ? "Nelle ultime settimane nessun segnale si è concluso." : PaceWords(missing * days / 7.0 / recent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing.</summary>
|
||||||
|
public static string PaceWords(double weeks)
|
||||||
|
{
|
||||||
|
if (weeks <= 1)
|
||||||
|
{
|
||||||
|
return "Al ritmo attuale, meno di una settimana.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (weeks > 52)
|
||||||
|
{
|
||||||
|
return "Al ritmo attuale, più di un anno.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (weeks > 12)
|
||||||
|
{
|
||||||
|
return string.Create(_it, $"Al ritmo attuale, circa {Math.Round(weeks / 4.345):0} mesi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var (low, high) = ((int)Math.Floor(weeks), (int)Math.Ceiling(weeks));
|
||||||
|
return low == high ? $"Al ritmo attuale, circa {_numbers[low]} settimane." : $"Al ritmo attuale, tra {_numbers[low]} e {_numbers[high]} settimane.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> Missings(ActivationCheck check)
|
||||||
|
{
|
||||||
|
var missing = new List<string>();
|
||||||
|
if (!check.Calibrated)
|
||||||
|
{
|
||||||
|
missing.Add(check.CalibrationError is { } error
|
||||||
|
? string.Create(_it, $"Le probabilità non sono ancora ben tarate: sbagliano in media di {error * 100:0.0} punti, il massimo è {ActivationCheck.MaxCalibrationError * 100:0}.")
|
||||||
|
: $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (check.Funded < ActivationCheck.FundedNeeded)
|
||||||
|
{
|
||||||
|
missing.Add($"Servono almeno {ActivationCheck.FundedNeeded} segnali di strategie con un capitale, anche in simulazione: per ora {(check.Funded == 1 ? "è uno" : $"sono {Format.Number(check.Funded)}")}.");
|
||||||
|
}
|
||||||
|
else if (!check.Improves)
|
||||||
|
{
|
||||||
|
missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Calibration and clues ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not
|
||||||
|
/// count. <paramref name="measured"/> is the error of the criterion to start counting (11.5), when it is the judge.
|
||||||
|
/// </summary>
|
||||||
|
public static string BandsWords(IReadOnlyList<LearningBand> bands, double? measured = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(bands);
|
||||||
|
var solid = bands.Where(b => b.Solid).ToList();
|
||||||
|
if (solid.Count == 0)
|
||||||
|
{
|
||||||
|
return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci.";
|
||||||
|
}
|
||||||
|
|
||||||
|
var error = measured is { } known ? Round(known * 100, 1) : solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
|
||||||
|
var best = solid[^1];
|
||||||
|
var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " +
|
||||||
|
((measured is { } exact ? exact < ActivationCheck.MaxCalibrationError : error < (decimal)ActivationCheck.MaxCalibrationError * 100) ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
|
||||||
|
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
|
||||||
|
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
|
||||||
|
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
|
||||||
|
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : Format.Number(cases) + " casi, troppo pochi")} per contarci.";
|
||||||
|
return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") +
|
||||||
|
(between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights)
|
||||||
|
{
|
||||||
|
var rest = weights.Skip(NamedWeights).Sum(w => w.Share);
|
||||||
|
var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList();
|
||||||
|
if (rest > 0)
|
||||||
|
{
|
||||||
|
rows.Add(new LearningWeight("Tutto il resto", rest, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share);
|
||||||
|
var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share);
|
||||||
|
var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
|
||||||
|
: news + fear == 0 && weights.Any(w => Clues.NewsGroups.Contains(w.Name) || w.Name == Fear) ? "Notizie, paura e avidità le studia già, ma per ora non pesano."
|
||||||
|
: news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono."
|
||||||
|
: news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100."
|
||||||
|
: $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100.";
|
||||||
|
return view with { Weights = rows, WeightsText = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Versions -----------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The scores of a model on the cases it had not studied, from the verification of its training.</summary>
|
||||||
|
private static Scores? Verified(ModelRow? model) => model?.Report.Attempts.FirstOrDefault(a => a.Chosen)?.Combined;
|
||||||
|
|
||||||
|
private static LearningVersion? Column(ModelRow? model, DateTimeOffset now) => model?.Version is not { } version ? null
|
||||||
|
: Verified(model) is { Cases: > 0 } s
|
||||||
|
? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2))
|
||||||
|
: new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null);
|
||||||
|
|
||||||
|
/// <param name="done">The last threshold already judged: at the next one, passed or not, there is a decision (SPEC 11.4).</param>
|
||||||
|
private static LearningView WithTrial(LearningView view, TrialCheck check, int done, string nextCheck, int? champion, int? challenger)
|
||||||
|
{
|
||||||
|
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, TrialCheck.Thresholds[^1]);
|
||||||
|
var first = TrialCheck.Thresholds[0];
|
||||||
|
var text = check.Pairs switch
|
||||||
|
{
|
||||||
|
0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||||
|
_ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " +
|
||||||
|
$"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||||
|
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. {(check.Pairs >= next ? $"Si decide {At(nextCheck)}" : $"Si decide di nuovo a {next} casi")}: " +
|
||||||
|
$"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.",
|
||||||
|
};
|
||||||
|
return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Watch --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static List<LearningCheck> ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var known = champion.Model is { } model ? snapshot.Examples.Count(e => e.Source == CaseSources.Live && model.Strategies.Contains(e.Strategy)) : 0;
|
||||||
|
var checks = new List<LearningCheck>
|
||||||
|
{
|
||||||
|
health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it))
|
||||||
|
: known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}")
|
||||||
|
: new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||||
|
PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)),
|
||||||
|
};
|
||||||
|
if (health.ErrorDrift)
|
||||||
|
{
|
||||||
|
checks.Add(new("warn", "I suoi errori sono aumentati negli ultimi casi"));
|
||||||
|
}
|
||||||
|
|
||||||
|
checks.Add(new("wait", $"Ultimo controllo {Moment(health.At, now)}. {AlarmText(events, now)}"));
|
||||||
|
return checks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningCheck PrecisionCheck(int? precision, int cases, int? expected)
|
||||||
|
{
|
||||||
|
if (precision is not { } seen || cases < Health.MinCases)
|
||||||
|
{
|
||||||
|
return new("wait", cases == 0 ? $"Nessun segnale concluso: la precisione si giudica da {Health.MinCases} casi" : $"Segnali conclusi: {cases}. La precisione si giudica da {Health.MinCases} casi");
|
||||||
|
}
|
||||||
|
|
||||||
|
var against = expected is not { } e ? "" : Math.Abs(seen - e) <= 5 ? $", in linea con il {e}% atteso" : seen < e ? $", sotto il {e}% atteso" : $", sopra il {e}% atteso";
|
||||||
|
return new(seen < Health.Alarm * 100 ? "warn" : "ok", $"Precisione sugli ultimi {cases} casi: {seen}%{against}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AlarmText(IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
if (events.LastOrDefault(e => e.Kind == ModelEvents.SetAside) is not { } alarm)
|
||||||
|
{
|
||||||
|
return "Nessun allarme finora";
|
||||||
|
}
|
||||||
|
|
||||||
|
var back = events.FirstOrDefault(e => e.Kind == ModelEvents.Back && e.At >= alarm.At);
|
||||||
|
var days = back is null ? 0 : Math.Max(1, (int)Math.Round((back.At - alarm.At).TotalDays));
|
||||||
|
return $"Ultimo allarme il {DayText(DayOf(alarm.At), now)}, {(back is null ? "ancora in corso" : days == 1 ? "rientrato in un giorno" : $"rientrato in {days} giorni")}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Demo ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static LearningView Demo(JsonElement demo)
|
||||||
|
{
|
||||||
|
static decimal Amount(JsonElement e, string name) => decimal.Parse(e.GetProperty(name).GetString()!, CultureInfo.InvariantCulture);
|
||||||
|
LearningVersion Version(string name)
|
||||||
|
{
|
||||||
|
var v = demo.GetProperty(name);
|
||||||
|
return new LearningVersion(v.GetProperty("versione").GetInt32(), v.GetProperty("addestrato").GetString()!, v.GetProperty("casi").GetInt32(), v.GetProperty("precisione_pct").GetInt32(),
|
||||||
|
Amount(v, "errore"), Amount(v, "guadagno"), Amount(demo, "guadagno_senza_filtro"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var summary = DemoSummary(demo);
|
||||||
|
var champion = Version("in_carica");
|
||||||
|
var challenger = Version("sfidante");
|
||||||
|
var watch = demo.GetProperty("sorveglianza");
|
||||||
|
var (title, text) = Words(summary, new CycleState(), DateTimeOffset.MinValue);
|
||||||
|
var view = new LearningView
|
||||||
|
{
|
||||||
|
Summary = summary,
|
||||||
|
Title = title,
|
||||||
|
Text = text,
|
||||||
|
Pace = PaceWords(demo.GetProperty("settimane_mancanti").GetDouble()),
|
||||||
|
LastTraining = $"{summary.Trained}, versione {challenger.Version}",
|
||||||
|
Bands =
|
||||||
|
[
|
||||||
|
.. demo.GetProperty("fasce").EnumerateArray().Select(b => (From: b.GetProperty("da").GetInt32(), To: b.GetProperty("a").GetInt32(), Band: b))
|
||||||
|
.Select(b => new LearningBand(b.From, b.To, b.Band.GetProperty("casi").GetInt32(), (b.From + b.To) / 2m, b.Band.GetProperty("pct").GetInt32())),
|
||||||
|
],
|
||||||
|
BandsText = demo.GetProperty("fasce_testo").GetString()!,
|
||||||
|
Champion = champion,
|
||||||
|
Challenger = challenger,
|
||||||
|
Checked = true,
|
||||||
|
Checks =
|
||||||
|
[
|
||||||
|
new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||||
|
PrecisionCheck(watch.GetProperty("precisione_pct").GetInt32(), watch.GetProperty("casi").GetInt32(), champion.Precision),
|
||||||
|
new("wait", watch.GetProperty("controllo").GetString()!),
|
||||||
|
],
|
||||||
|
Weeks = [.. watch.GetProperty("settimane").EnumerateArray().Select(w => new LearningWeek(DateOnly.Parse(w.GetProperty("lunedi").GetString()!, CultureInfo.InvariantCulture), w.GetProperty("pct").GetInt32()))],
|
||||||
|
Found = [.. demo.GetProperty("scoperte").EnumerateArray().Select(d => new Discovery(d.GetProperty("titolo").GetString()!, d.GetProperty("dettaglio").GetString()!, d.GetProperty("casi").GetInt32()))],
|
||||||
|
Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))],
|
||||||
|
};
|
||||||
|
var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList();
|
||||||
|
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Words --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model.</summary>
|
||||||
|
private static string NextText(DateTimeOffset now, bool sunday)
|
||||||
|
{
|
||||||
|
var local = TimeZoneInfo.ConvertTime(now, Zones.Rome);
|
||||||
|
var today = DateOnly.FromDateTime(local.DateTime);
|
||||||
|
var day = local.Hour < 3 ? today : today.AddDays(1);
|
||||||
|
if (sunday)
|
||||||
|
{
|
||||||
|
day = day.AddDays((7 - (int)day.DayOfWeek) % 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Format.Day(day) + ", 03:00";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"domenica 11 ottobre alle 03:00" from the short form.</summary>
|
||||||
|
private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>"oggi alle 03:00", "il 4 ottobre alle 03:00".</summary>
|
||||||
|
private static string Moment(DateTimeOffset at, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var time = TimeZoneInfo.ConvertTime(at, Zones.Rome).ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||||
|
return (DayOf(now).DayNumber - DayOf(at).DayNumber) switch
|
||||||
|
{
|
||||||
|
0 => $"oggi alle {time}",
|
||||||
|
1 => $"ieri alle {time}",
|
||||||
|
_ => $"il {DayText(DayOf(at), now)} alle {time}",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome);
|
||||||
|
|
||||||
|
/// <summary>"domenica 4 ottobre", with the year when it is another one.</summary>
|
||||||
|
private static string LongDay(DateOnly day, DateTimeOffset now) => Format.Day(day) + (day.Year == DayOf(now).Year ? "" : day.ToString(" yyyy", CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
/// <summary>"4 ottobre", with the year when it is another one.</summary>
|
||||||
|
private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day);
|
||||||
|
|
||||||
|
private static int? Points(double? share) => share is { } s ? (int)Math.Round(s * 100, MidpointRounding.AwayFromZero) : null;
|
||||||
|
|
||||||
|
private static decimal Round(double value, int decimals) => Math.Round((decimal)value, decimals, MidpointRounding.AwayFromZero);
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.News;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A gauge of "Umore del mercato" (SPEC 10.4): the value with its label, the dot on a track from <paramref name="Left"/> to
|
||||||
|
/// <paramref name="Right"/>. <paramref name="Position"/> is from 0 to 1, null while the indicator has not been read.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record MoodGauge(string Label, string? Value, string? Words, double? Position, string Left, string Right, bool Centered, string? Stale);
|
||||||
|
|
||||||
|
/// <summary>An event of "In calendario" with the effect it will have; <paramref name="Matters"/> when it holds entries.</summary>
|
||||||
|
internal sealed record CalendarRow(string When, string Title, string Effect, bool Matters);
|
||||||
|
|
||||||
|
/// <summary>A line of "Da dove leggo": the source, how often, and whether it answers.</summary>
|
||||||
|
internal sealed record SourceRow(string Name, string Frequency, bool Ok);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Notizie e mercato screen (SPEC 13.6, mockup 05): what the bot read and did, the mood of the market, the calendar
|
||||||
|
/// with the effect of each event, the sources and the spending on the language model. In demo mode the counts, the
|
||||||
|
/// sources and the spending of appendix F.9 come from the aggregates; the rows come from the database.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record NewsView(
|
||||||
|
NewsBoardResult Board,
|
||||||
|
IReadOnlyList<MoodGauge> Mood,
|
||||||
|
IReadOnlyList<CalendarRow> Calendar,
|
||||||
|
IReadOnlyList<SourceRow> Sources,
|
||||||
|
string Spending,
|
||||||
|
bool Collecting)
|
||||||
|
{
|
||||||
|
/// <summary>How far ahead the calendar looks: a week of economic data, a month of central banks, two weeks of earnings.</summary>
|
||||||
|
public static readonly TimeSpan EconomicAhead = TimeSpan.FromDays(7);
|
||||||
|
|
||||||
|
public static readonly TimeSpan CentralBanksAhead = TimeSpan.FromDays(31);
|
||||||
|
|
||||||
|
public static readonly TimeSpan EarningsAhead = TimeSpan.FromDays(14);
|
||||||
|
|
||||||
|
public const int CalendarRows = 6;
|
||||||
|
|
||||||
|
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||||
|
|
||||||
|
public static async Task<NewsView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(shell);
|
||||||
|
var services = host.Services!;
|
||||||
|
var clock = host.Clock;
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var board = await new NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var switches = await NewsRuleSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
var mood = await MoodAsync(new MoodStore(services.Db, clock), now, cancellationToken).ConfigureAwait(false);
|
||||||
|
var calendar = await CalendarAsync(services, clock, shell.Zone, switches, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
using var aggregates = shell.Aggregates();
|
||||||
|
if (aggregates?.RootElement.GetProperty("notizie") is { } demo)
|
||||||
|
{
|
||||||
|
var counted = board with
|
||||||
|
{
|
||||||
|
Read = demo.GetProperty("lette_24h").GetInt32(),
|
||||||
|
OnPositions = demo.GetProperty("sulle_posizioni").GetInt32(),
|
||||||
|
Active = demo.GetProperty("con_effetto").GetInt32(),
|
||||||
|
};
|
||||||
|
var sources = demo.GetProperty("fonti").EnumerateArray()
|
||||||
|
.Select(f => new SourceRow(f.GetProperty("nome").GetString()!, f.GetProperty("frequenza").GetString()!, true)).ToList();
|
||||||
|
var spending = $"Tutte le notizie passano da un modello locale, gratuito. Solo le {demo.GetProperty("sulle_posizioni").GetInt32()} rilevanti sono state rilette " +
|
||||||
|
$"da un modello linguistico: oggi è costato {Format.Money(decimal.Parse(demo.GetProperty("spesa_oggi").GetString()!, _it))} " +
|
||||||
|
$"su un tetto di {Format.Money(decimal.Parse(demo.GetProperty("tetto").GetString()!, _it))}.";
|
||||||
|
return new NewsView(counted, mood, calendar, sources, spending, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (rows, collecting) = await SourcesAsync(services, shell, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
// Only reads what was spent: the screen never asks the model anything.
|
||||||
|
var model = await new NewsAnalyst(services.Db, clock, services.Settings, services.Secrets.RevealAsync,
|
||||||
|
(_, _) => throw new InvalidOperationException("La schermata non interroga il modello.")).SpendingAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return new NewsView(board, mood, calendar, rows, SpendingText(model), collecting);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The spending of the day in words (SPEC 13.6): what the language model read and what it cost, against the cap.</summary>
|
||||||
|
public static string SpendingText(ModelSpending model)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(model);
|
||||||
|
const string Local = "Tutte le notizie passano da un modello locale, gratuito, sul tuo computer.";
|
||||||
|
if (!model.Configured)
|
||||||
|
{
|
||||||
|
return Local + " Il modello linguistico non è configurato: oggi non è costato nulla.";
|
||||||
|
}
|
||||||
|
|
||||||
|
var read = model.Judged switch
|
||||||
|
{
|
||||||
|
0 => "Oggi il modello linguistico non ha ancora riletto nessuna notizia",
|
||||||
|
1 => "Oggi il modello linguistico ha riletto 1 notizia sulle tue posizioni e sugli strumenti candidati",
|
||||||
|
var n => $"Oggi il modello linguistico ha riletto {n} notizie sulle tue posizioni e sugli strumenti candidati",
|
||||||
|
};
|
||||||
|
var full = model.Spent >= model.Cap ? " Il tetto è raggiunto: fino a mezzanotte giudica solo il modello locale." : "";
|
||||||
|
return $"{Local} {read}: è costato {Format.Money(model.Spent)} su un tetto di {Format.Money(model.Cap)}.{full}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IReadOnlyList<MoodGauge>> MoodAsync(MoodStore store, DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var fear = await store.LatestAsync(MoodIndicators.FearGreed, cancellationToken).ConfigureAwait(false);
|
||||||
|
var vix = await store.LatestAsync(MoodIndicators.Vix, cancellationToken).ConfigureAwait(false);
|
||||||
|
var funding = await store.LatestAsync(MoodIndicators.BtcFunding, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// A reading older than three days is shown with its date: the mood of last week is not today's.
|
||||||
|
string? Stale(MoodReading? r) => r is { } x && now - x.AsOf > TimeSpan.FromDays(3) ? "letto " + Format.ShortDate(x.AsOf, now, Zones.Rome, false) : null;
|
||||||
|
return
|
||||||
|
[
|
||||||
|
new("Crypto: paura o avidità", fear is { } f ? Format.Number((decimal)f.Value) : null, fear is { } f2 ? "su 100, " + MoodLabels.FearGreed(f2.Value) : null,
|
||||||
|
fear is { } f3 ? Math.Clamp(f3.Value / 100, 0, 1) : null, "Paura estrema", "Avidità estrema", false, Stale(fear)),
|
||||||
|
new("Azioni USA: nervosismo atteso", vix is { } v ? Format.Number((decimal)v.Value, 1) : null, vix is { } v2 ? MoodLabels.Vix(v2.Value) : null,
|
||||||
|
vix is { } v3 ? Math.Clamp((v3.Value - 10) / 30, 0, 1) : null, "Calmo (10)", "Panico (40)", false, Stale(vix)),
|
||||||
|
new("Bitcoin: scommesse a leva", funding is { } b ? Format.Percent((decimal)b.Value * 100m, 3, withSign: true) : null,
|
||||||
|
funding is { } b2 ? MoodLabels.Funding(b2.Value, TimeSpan.FromHours(8)) : null,
|
||||||
|
funding is { } b3 ? Math.Clamp(0.5 + (b3.Value / 0.0008), 0, 1) : null, "Troppi al ribasso", "Troppi al rialzo", true, Stale(funding)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The events that change something or that the user expects to see: this week's US and euro data of medium or high
|
||||||
|
// impact, the central banks of the next month, the earnings of the stocks held or watched.
|
||||||
|
private static async Task<IReadOnlyList<CalendarRow>> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var events = await new CalendarEventStore(services.Db, clock).BetweenAsync(now, now + CentralBanksAhead, cancellationToken).ConfigureAwait(false);
|
||||||
|
var (held, noted) = await services.Db.ReadAsync(async s =>
|
||||||
|
{
|
||||||
|
var h = await s.QueryAsync("SELECT i.symbol FROM positions p JOIN instruments i ON i.id = p.instrument_id WHERE i.venue = @v AND p.quantity > 0",
|
||||||
|
r => r.Text("symbol"), ("v", Venues.Alpaca)).ConfigureAwait(false);
|
||||||
|
var n = await s.QueryAsync("SELECT subject FROM news_notes WHERE kind = @k", r => r.Text("subject"), ("k", NewsReasons.Earnings)).ConfigureAwait(false);
|
||||||
|
return (h, n);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
var stocks = held.ToHashSet(StringComparer.Ordinal);
|
||||||
|
var withNote = noted.ToHashSet(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
var shown = events.Where(e => e.Kind switch
|
||||||
|
{
|
||||||
|
CalendarEventKinds.Economic => e.OccursAt - now <= EconomicAhead && e.Currency is "USD" or "EUR" && e.Impact is "High" or "Medium",
|
||||||
|
CalendarEventKinds.CentralBank => true,
|
||||||
|
CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey)),
|
||||||
|
_ => false,
|
||||||
|
}).OrderBy(e => e.OccursAt).Take(CalendarRows);
|
||||||
|
|
||||||
|
return [.. shown.Select(e => Row(e, now, zone, switches))];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches)
|
||||||
|
{
|
||||||
|
var local = TimeZoneInfo.ConvertTime(e.OccursAt, zone);
|
||||||
|
var day = DateOnly.FromDateTime(local.DateTime);
|
||||||
|
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, zone).DateTime);
|
||||||
|
var dayText = day == today ? "Oggi" : day == today.AddDays(1) ? "Domani" : Capital(Format.Day(day));
|
||||||
|
if (e.Kind == CalendarEventKinds.Earnings)
|
||||||
|
{
|
||||||
|
var session = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime);
|
||||||
|
var sessionText = session.DayNumber - today.DayNumber is > 0 and < 7 ? Format.Day(session).Split(' ')[0] : Format.Day(session);
|
||||||
|
var (when, until) = e.TimeHint switch
|
||||||
|
{
|
||||||
|
"bmo" => (", prima dell'apertura", $"fino a {sessionText}"),
|
||||||
|
"dmh" => (", durante la seduta", $"fino a {sessionText}"),
|
||||||
|
"amc" => (", dopo la chiusura", "fino alla seduta dopo i conti"),
|
||||||
|
_ => ("", "fino alla seduta dopo i conti"),
|
||||||
|
};
|
||||||
|
return switches.Earnings
|
||||||
|
? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: niente mean reversion {until}", true)
|
||||||
|
: new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: la regola è spenta, nessun effetto", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var whenText = e.TimeKnown ? $"{dayText}, {local:HH:mm}" : dayText;
|
||||||
|
var impact = e.Impact switch
|
||||||
|
{
|
||||||
|
"High" => "Impatto alto",
|
||||||
|
"Medium" => "Impatto medio",
|
||||||
|
_ => "Impatto basso",
|
||||||
|
};
|
||||||
|
if (CalendarBlocks.Window(e) is { } window)
|
||||||
|
{
|
||||||
|
if (!switches.Macro)
|
||||||
|
{
|
||||||
|
return new CalendarRow(whenText, e.Title, impact + ": la regola è spenta, nessun blocco", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var from = TimeZoneInfo.ConvertTime(window.From, zone);
|
||||||
|
var to = TimeZoneInfo.ConvertTime(window.To, zone);
|
||||||
|
return new CalendarRow(whenText, e.Title, string.Create(_it, $"{impact}: nessun nuovo ingresso dalle {from:HH:mm} alle {to:HH:mm}"), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new CalendarRow(whenText, e.Title, impact + ": nessun blocco", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(IReadOnlyList<SourceRow> Rows, bool Collecting)> SourcesAsync(AppServices services, ShellData shell, IClock clock, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var feeds = await new NewsStore(services.Db, clock).ListSourcesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var on = feeds.Where(f => f.Enabled).ToList();
|
||||||
|
var rows = new List<SourceRow>();
|
||||||
|
var press = on.Where(f => f.Name != "SEC").ToList();
|
||||||
|
if (press.Count > 0)
|
||||||
|
{
|
||||||
|
var failing = press.Count(f => f.LastError is not null);
|
||||||
|
rows.Add(new SourceRow($"{press.Count} testate e banche centrali", failing == 0 ? "ogni 2 minuti" : $"{failing} non rispondono", failing == 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (on.FirstOrDefault(f => f.Name == "SEC") is { } sec)
|
||||||
|
{
|
||||||
|
rows.Add(new SourceRow("Comunicati alla SEC", sec.LastError is null ? "ogni 2 minuti" : "non risponde", sec.LastError is null));
|
||||||
|
}
|
||||||
|
|
||||||
|
var states = await new SourceStateStore(services.Db, clock).ListAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
if (states.FirstOrDefault(s => s.Source == ForexFactory.Source) is { } calendar)
|
||||||
|
{
|
||||||
|
var ok = calendar.LastError is null && calendar.LastSuccessAt is not null;
|
||||||
|
rows.Add(new SourceRow("Calendario economico",
|
||||||
|
calendar.LastSuccessAt is { } at ? "aggiornato " + Inline(Format.ShortDate(at, shell.Now, shell.Zone)) : "non ancora letto", ok));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (rows, services.MarketData is not null && on.Count > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpperInvariant(text[0]) + text[1..];
|
||||||
|
|
||||||
|
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>A point of the total: equity, the capital put in or taken out so far (cumulative) and the time-weighted index.</summary>
|
||||||
|
public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark, decimal Flows = 0m, decimal? Twr = null);
|
||||||
|
|
||||||
|
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
|
||||||
|
|
||||||
|
/// <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);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. One world
|
||||||
|
/// only, as on the Conti screen: real money when there is a real account, otherwise the simulated one. Results leave
|
||||||
|
/// out the capital put in or taken out (SPEC 7.5): the amount is net of flows, the percentage is time-weighted.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record Overview(
|
||||||
|
IReadOnlyList<EquityPoint> Points,
|
||||||
|
IReadOnlyList<EquityPoint> Series,
|
||||||
|
PeriodResult Result,
|
||||||
|
DateOnly From,
|
||||||
|
decimal FromEquity,
|
||||||
|
IReadOnlyList<PeriodResult> Cells,
|
||||||
|
int Positions,
|
||||||
|
int PositionsWithoutStop,
|
||||||
|
int OpenOrders,
|
||||||
|
IReadOnlyList<NextMove> Next,
|
||||||
|
IReadOnlyList<LastAction> Last,
|
||||||
|
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")];
|
||||||
|
|
||||||
|
public bool HasData => Points.Count > 0;
|
||||||
|
|
||||||
|
public static async Task<Overview> LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (points, positions, withoutStop, orders, journal, capitalSet) = await services.Db.ReadAsync(async s =>
|
||||||
|
{
|
||||||
|
var environments = await s.QueryAsync("SELECT environment FROM accounts", r => r.Text("environment")).ConfigureAwait(false);
|
||||||
|
var world = environments.Any(e => TradingEnvironments.World(e) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
|
||||||
|
var mine = string.Join(", ", new[] { TradingEnvironments.Simulation, TradingEnvironments.Demo, TradingEnvironments.Live }.Where(e => TradingEnvironments.World(e) == world).Select(e => "'" + e + "'"));
|
||||||
|
var p = await s.QueryAsync(
|
||||||
|
"SELECT taken_at, equity, benchmark, flows, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at",
|
||||||
|
r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"), Flows: r.MoneyOrNull("flows") ?? 0m, Twr: r.MoneyOrNull("twr_index")),
|
||||||
|
("w", world)).ConfigureAwait(false);
|
||||||
|
var held = (await s.QueryAsync($"SELECT p.quantity, p.stop_price FROM positions p JOIN accounts a ON a.id = p.account_id WHERE a.environment IN ({mine})",
|
||||||
|
r => (Quantity: r.Money("quantity"), Stop: r.MoneyOrNull("stop_price"))).ConfigureAwait(false)).Where(x => x.Quantity > 0m).ToList();
|
||||||
|
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 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);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// One point per day: the last snapshot of each local day.
|
||||||
|
var daily = points
|
||||||
|
.Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark, p.Flows, p.Twr))
|
||||||
|
.GroupBy(p => p.Day)
|
||||||
|
.Select(g => g.Last())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
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, decision);
|
||||||
|
}
|
||||||
|
|
||||||
|
var latest = daily[^1];
|
||||||
|
EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0];
|
||||||
|
PeriodResult Between(string label, EquityPoint start)
|
||||||
|
{
|
||||||
|
var amount = latest.Equity - start.Equity - (latest.Flows - start.Flows);
|
||||||
|
var basis = start.Equity + (latest.Flows - start.Flows);
|
||||||
|
var percent = start.Twr is > 0m && latest.Twr is { } twr ? (twr / start.Twr.Value - 1m) * 100m
|
||||||
|
: basis == 0 ? 0 : amount / basis * 100m;
|
||||||
|
return new PeriodResult(label, amount, percent);
|
||||||
|
}
|
||||||
|
|
||||||
|
var start = period switch
|
||||||
|
{
|
||||||
|
"30" => Since(30),
|
||||||
|
"7" => Since(7),
|
||||||
|
"oggi" => Since(1),
|
||||||
|
_ => daily[0],
|
||||||
|
};
|
||||||
|
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)) };
|
||||||
|
// "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)
|
||||||
|
{
|
||||||
|
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, decision);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Today(string shortDate) => shortDate.StartsWith("Oggi ", StringComparison.Ordinal) ? shortDate["Oggi ".Length..] : shortDate;
|
||||||
|
}
|
||||||
Loaded 100 of 424 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user