70 Commits
Author SHA1 Message Date
Alby96 a66e3439d8 Merge pull request 'Fase 7: raccolta, collegamento e primo giudizio delle notizie, con il classificatore ONNX' (#97) from fase-7 into main
ci / test (postgres) (push) Failing after 7m44s
ci / test (sqlite) (push) Successful in 5m36s
ci / image (push) Skipped
2026-11-15 15:34:38 +01:00
Alby96andClaude Opus 5.5 1aede2fc1c Let the server test accept the news feeds and the pinned model host (refs #57)
ci / test (postgres) (push) Successful in 11m31s
ci / test (sqlite) (push) Successful in 5m26s
ci / test (postgres) (pull_request) Successful in 10m7s
ci / test (sqlite) (pull_request) Successful in 5m13s
ci / image (push) Successful in 3m12s
ci / image (pull_request) Successful in 1m46s
The news collector runs alongside the market data in the server test, so its
feeds and the Hugging Face download of the classifier can reach the fake network
before the assertion: they are the hosts the code declares, nothing else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:44:05 +01:00
Alby96andClaude Opus 5.5 78e77818eb Read the tone of English headlines with the pinned ONNX model of SPEC 4.5 (refs #57)
ci / test (postgres) (push) Failing after 6m20s
ci / test (sqlite) (push) Failing after 5m59s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Failing after 4m51s
ci / test (sqlite) (pull_request) Successful in 5m29s
ci / image (pull_request) Skipped
The classifier is distilroberta-finetuned-financial-news-sentiment-analysis in
Xenova's quantized ONNX export, pinned at revision e6953e30 and checked by size and
SHA-256.

- Model download: the model is not in the repository. The news job downloads it in
  the background into the models folder of the data directory, the first time, and
  retries after 6 hours if that fails. Until then the keywords judge alone, as
  SPEC 10.3 requires.
- Tokenizer: RoBERTa's byte-level BPE travels inside the DLL, read with
  BpeTokenizer and the RoBERTa pre-tokenizer. CodeGenTokenizer.Create adds ids for
  runs of spaces that the model rejects. No special tokens are recognised in
  untrusted text.
- Token check: the test compares the ids on 14 headlines with an independent copy
  of the GPT-2 encoder run on the same files.
- Model test: it reads the tone of clear headlines at 23-24 ms per title on one
  thread. It runs where the model is already downloaded and is skipped in CI.

Microsoft.ML.OnnxRuntime 1.31.1 and Microsoft.ML.Tokenizers 2.0.1 come from the
ADR 0004 list. Google.Protobuf joins the known indirect dependencies.

Anubis and Anubis.Server now declare win-x64 among their runtime identifiers, so
their lock files hold the Windows native packages. Publishing the Windows zip no
longer rewrites the lock files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:00:54 +01:00
Alby96andClaude Opus 5.5 5f0ce6b172 Record the news collection and the first judgement in the project state (refs #56 #57)
ci / test (postgres) (pull_request) Successful in 9m37s
ci / test (sqlite) (pull_request) Successful in 4m20s
ci / image (pull_request) Successful in 2m32s
ci / test (sqlite) (push) Successful in 4m24s
ci / test (postgres) (push) Failing after 9m18s
ci / image (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:57:49 +01:00
Alby96andClaude Opus 5.5 9ee2367693 Judge every article locally: serious cases by keywords, tone grade and importance (refs #57)
This is the first judgement of SPEC 10.2 point 4, without a language model.

- Serious cases: cyberattack, suspension, fraud, bankruptcy, investigation and
  delisting are found by whole-word phrases in English and Italian, so an
  Italian headline still counts.
- Tone: the five tone grades follow the bounds of the specification.
- Importance: 4 for a serious case, 3 for a negative tone, 2 when the article is
  linked to an instrument, otherwise 1.
- Classifier: it sits behind IToneClassifier and is asked only for English
  titles. The ONNX model plugs in there; without it the tone stays unknown and
  everything else works.

Every article stores its score, case and importance. Each story keeps the mean
score, the case and the highest importance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:57:49 +01:00
Alby96andClaude Opus 5.5 f1ba452aba Collect news from the SPEC 4.4 feeds, group retold stories and link them to instruments (refs #56)
News is the first input of Phase 7. Every two minutes the "notizie" job asks each
enabled feed conditionally and backs off a failing one up to an hour.

- Parsing: RSS 2.0, RSS 1.0 and Atom are read without DTDs or entity expansion, so a
  hostile feed reads nothing from disk.
- Deduplication: articles are deduplicated by canonical URL.
- Grouping: retold titles join one story by word similarity within 48 hours, and
  independent publishers are counted by registrable domain.
- Linking: stories are linked to instruments by source symbols, cashtags, exchange
  tickers, coin tickers and capitalised company names; to the crypto or equity class
  or to the market by theme; to the source topic as a fallback.

ADR 0014 records the thresholds. The tests read a synthetic archive in each source's
real format and run on both engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:57:49 +01:00
Alby96 25e71b679f Merge pull request 'Raccolta dei dati per l'analisi e release di prova per Windows' (#96) from diagnostica into main
ci / test (postgres) (push) Failing after 5m55s
ci / test (sqlite) (push) Successful in 4m18s
ci / image (push) Skipped
2026-11-14 18:55:56 +01:00
Alby96andClaude Opus 5.5 9cf386d08b Count WebSocket upgrades as successful calls and tidy the report (refs #95)
ci / test (postgres) (pull_request) Successful in 9m14s
ci / test (sqlite) (push) Successful in 4m11s
ci / test (sqlite) (pull_request) Successful in 4m12s
ci / test (postgres) (push) Successful in 9m40s
ci / image (pull_request) Successful in 2m14s
ci / image (push) Successful in 54s
Trying the packaged release showed three things to fix: a 101 answer that opens a
WebSocket was counted as a failure, the duration buckets were too coarse around
the usual 200-500 ms of the brokers, and the report mixed CRLF and LF lines and
named SQLite only by its version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:05:57 +01:00
Alby96andClaude Opus 5.5 6e365673b8 Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped
The 48-hour soak run at home kept being cut short by the host, never by Anubis.
The user will instead run a release for as long as they like and paste back a
report, so the bot now records what that report needs (ADR 0013).

- Every 5 minutes and at each start, a process sample goes to diagnostic_samples:
  memory, GC, threads, handles, CPU, exceptions, database size, log warnings and
  errors, and outbound HTTP calls by destination with duration buckets, read from
  the System.Net.Http meter without any new package.
- Every scheduled job run goes to job_runs. Both tables keep 30 days.
- The Markdown report (at most 60 KB, redacted, user folders masked) adds
  findings, the soak checks, starts and silences, jobs, calls, grouped log
  warnings and errors, and resources over time with their slopes. It comes from
  "anubis diagnostics", GET /api/diagnostica.md and a button in Diario e sistema.
- New {long} column token: SQLite STRICT tables reject BIGINT.
- "tasks release-win" builds the trial zip with a start script, a script that
  writes the report, and Italian instructions. Version 0.7.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:57:03 +01:00
Alby96 32673007a2 Merge pull request 'Prova di 48 ore: stop di Docker di 15 minuti e come evitarlo' (#94) from prova-48h-docker into main
ci / test (postgres) (push) Successful in 6m6s
ci / test (sqlite) (push) Successful in 3m14s
ci / image (push) Successful in 1m6s
2026-11-13 09:08:03 +01:00
Alby96andClaude Opus 5.5 e561245d4e Keep the 48-hour run going after Docker stopped with the Claude app (refs #53 #55)
ci / test (sqlite) (pull_request) Successful in 3m37s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Successful in 6m4s
ci / test (postgres) (push) Successful in 6m27s
ci / image (pull_request) Successful in 1m3s
ci / image (push) Successful in 1m5s
On 12 November at 23:37 Docker Desktop stopped for 15 minutes. It had
been started from the Claude app's shell after the PC switched off, so it
lived in the app's process job and died when the app updated itself. The
bot resumed alone and recorded the absence.

The run is not restarted from zero: a fresh start would no longer span
two US sessions before the weekend. Instead two reports are read: the 48
uninterrupted hours from 23:57, which must be regular, and the whole run
from 21:02, whose only allowed failure is that 15-minute stop. Docker is
now started through WMI, outside the app, and SVILUPPO.md says how.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:59:49 +01:00
Alby96 829fbd2eba Merge pull request 'Prova di 48 ore ripartita dopo lo spegnimento del PC' (#93) from prova-48h-ripartita into main
ci / test (postgres) (push) Successful in 7m4s
ci / test (sqlite) (push) Failing after 1m0s
ci / image (push) Skipped
2026-11-12 23:23:08 +01:00
Alby96andClaude Opus 5.5 f59eee8632 Restart the 48-hour run after the PC switched off (refs #53 #55)
ci / test (postgres) (pull_request) Successful in 8m29s
ci / test (sqlite) (pull_request) Successful in 4m18s
ci / image (pull_request) Successful in 1m25s
ci / test (postgres) (push) Successful in 7m25s
ci / test (sqlite) (push) Successful in 4m6s
ci / image (push) Successful in 1m32s
The first attempt ran 22 hours: on 12 November at 19:49 the PC switched
off without a clean shutdown (power or a machine hang, no bug check).
When it came back the bot resumed by itself and wrote the absence in
the diary, but a 48-hour run needs no gaps, so it started again from
zero at 21:02. STATE gives the new window and command; the first
attempt's report and database are kept under artifacts/prova-48h.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:03:56 +01:00
Alby96 7291f5d15b Merge pull request 'Fase 6 — Motore dal vivo in simulazione' (#92) from fase-6 into main
ci / test (postgres) (push) Successful in 10m0s
ci / test (sqlite) (push) Successful in 4m48s
ci / image (push) Successful in 1m31s
2026-11-11 22:30:53 +01:00
Alby96andClaude Opus 5.5 9a4e31aa48 Record the start of the 48-hour run and how to read its report (refs #53)
ci / test (postgres) (push) Successful in 9m13s
ci / test (sqlite) (push) Successful in 4m46s
ci / image (push) Successful in 1m50s
ci / test (sqlite) (pull_request) Successful in 4m57s
ci / test (postgres) (pull_request) Successful in 11m4s
ci / image (pull_request) Successful in 1m2s
The run started on 11 November 2026 at 21:44 Italian time in the
anubis-prova container, from the image of this branch. STATE says when
and how to make the report so that it spans both US sessions; its check
is the first step of Phase 7 (#55).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:49:12 +01:00
Alby96andClaude Opus 5.5 1c7205024f Count short gaps at the edges of the soak window as covered (refs #53)
The scheduler's first jobs finish about a minute after the bot starts, so
a run started exactly at the window's start was reported as covering
slightly less than 48 hours. A gap shorter than the allowed silence
(15 minutes) at either edge now counts as covered, like one in the middle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:40:41 +01:00
Alby96andClaude Opus 5.5 be6d5fb91f Let a late decision wait for its bars; read the soak run's continuity from jobs and absences (refs #49 #53)
Starting the 48-hour run showed two defects.

After an absence, a decision made past 12:00 UTC was written off as
"no data" at the first pulse, because the data step had not yet brought
the bars of the close: the recovered decision was lost. A late decision
now asks for its bars and waits up to 30 minutes for them. The 20-hour
absence test pulses before the bar arrives and fails without the fix.

The soak report measured coverage and silences from reconciliation
rows, but a clean round writes none, so a healthy run would have been
reported as never covered. It now reads when the scheduled jobs first
ran and last finished, the absences written at each restart, the guard
interventions, and each account's status (reconciled within the last
15 minutes and normal). The test no longer fakes a row every 5 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:35:03 +01:00
Alby96andClaude Opus 5.5 2185a0b36b Fix the defects found by the Phase 6 review (refs #47 #48 #49 #51 #52 #54)
An independent review of the phase found nine defects. The ones that
could lose money or orders:

- Exits at the close of equity_meanrev are now planned orders written in
  the same transaction that claims the decision, so a restart can neither
  lose them nor send them twice. A sell with a deadline starts aggressive.
- Resume also finds a planned order not yet linked to its execution
  (restart between sending and linking) and closes it before re-planning.
- An account is "ready" only after adopting the guard's stops, checking
  the key, reconciling, resuming and aligning stops. Until then nothing is
  decided on it or sent to it, and the loop retries its startup each
  minute. The guard's note is deleted only when every stop it placed is in
  the ledger.
- Each account's turn is cut after 45 s (60 s for a retried startup), so a
  slow broker no longer silences the heartbeat until the guard kills a
  healthy engine; the beat is also withheld when the scheduler has been
  silent for 30 minutes.

Smaller ones: a stock decision made after the open is marked late; the
Telegram loops survive unexpected errors; a long absence is shown on the
Panoramica until "Ho visto" (SPEC 5.6); plain-http heartbeats are only
accepted to home-network addresses; the soak report gives a daily close
30 minutes to be decided before expecting it.

ADR 0012 point 12 records these choices; #51 and the two screen criteria
are ticked in the roadmap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:10:28 +01:00
Alby96andClaude Opus 5.5 3d174931e9 Add the endurance run report and record the Phase 6 choices (refs #53 #54)
"anubis soak" reads the bot's records over a time window and says whether
the run kept control. It changes nothing, so it can run beside the working
bot with docker exec. It exits with 4 when something needs a look. It
checks:
- the hours covered and silences longer than 15 minutes;
- orders or decisions made twice;
- unexplained reconciliation differences and each account's last outcome;
- absences and guard interventions;
- one crypto decision per daily close.

ADR 0012 records what the specification leaves open in this phase: the
live engine shares the backtest's decision call, run keys, recovery after
an absence, the guard and its drill seams, the diary templates, the
"senza bot" comparison, Telegram and the heartbeat, the screens and the
endurance run. ROADMAP ticks the Phase 6 items and criteria with the tests
that prove them, STATE moves on to Phase 7, and SVILUPPO explains the
guard and the report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:36:22 +01:00
Alby96andClaude Opus 5.5 9ae107000b Ignore late messages from a replaced engine; list only moves in the morning summary (refs #48 #52)
The guard drill failed once under load. The pipe of the killed engine
delivered a late "running" beat after the restart. The drill took the new
engine as ready and stopped it before it had cancelled the half-done sale
and put the stop back.

The same late message could have made a crash of the new engine look like
a planned stop, which the guard never restarts. Each engine the guard starts
now has a number, and messages from a replaced one are ignored. The drill
also waits until the restart's work is in the database before it checks.

The morning Telegram summary listed every job due today, including the
background ones that run every minute. It now lists only the bot's moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:34:25 +01:00
Alby96andClaude Opus 5.5 e96ca70a1a Build the Panoramica and Diario e sistema screens as in the mockups (refs #51)
Panoramica now follows mockup 01. Below "Finora" and "Adesso e dopo" it
shows:
- the two account cards with the invested/cash bar and a 30-day trend;
- the four risk limits;
- the open positions by value;
- the strategies;
- the news, learning and system tiles.

On the phone it follows mockup 09: Conti as a list, four positions with
"Vedi le altre", and two limits. Outside the demo, news and learning say
they are not active yet (Phases 7 and 8). The next moves are the scheduler's
moves only, no longer every interval job.

Diario e sistema follows mockup 08:
- the diary grouped by day, with search and filter chips (plain links, no
  JavaScript) and older days on request;
- how each component is doing;
- the scheduled jobs;
- the host's processor, memory and disk;
- the technical logs as a zip, for signed-in users only.

In demo mode the screens show the values of appendix F.10. Tests cover the
demo figures, the filters and search, and the logs download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:32:19 +01:00
Alby96andClaude Opus 5.5 84c540786c Send Telegram notices, answer phone commands and call the heartbeat (refs #52)
Every notice is written to the queue in the same transaction as what it
tells, then sent every ten seconds. Each has a state: pending, sent, or
failed with its error. Network failures and 429s are retried with growing
pauses (Telegram's own wait when it gives one). Refusals are final. A notice
that could not leave within a day is given up instead of arriving late. Every
fill now also reaches the phone, and so do pause, resume and restart.

Commands are read by long polling and obeyed only from the configured chat
and only when fresh, so yesterday's /pausa never pauses today. They are
/stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (confirmed with
/conferma within two minutes) and /aiuto. Restarting after "Ferma tutto",
real money, limits and keys stay in the interface.

Also added:
- the heartbeat call every minute when an address is configured;
- the morning summary at 08:00, caught up within four hours;
- an optional hourly or evening status;
- a Telegram section in Impostazioni: test-before-save, a test button, the
  queue's state and the last successful heartbeat;
- on desktop, the first-run page recommends the heartbeat.

Tests run against a fake Telegram server, including the commands through
the real server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:53:55 +01:00
Alby96andClaude Opus 5.5 d00dfbd32f Add the guard that watches the engine and protects positions (refs #48)
The guard (SPEC 9.3, 9.4) is now the container's main process and the parent
of the engine. It listens on a named pipe for the engine's heartbeat and
startup steps, and steps in after two minutes of silence, ten minutes of a
startup that does not move, or an exit without notice. It stops the engine,
cancels our purchases and sales left open on demo accounts, puts back the
stops the positions need from the state file the engine writes every ten
seconds, writes a note, warns the user and restarts the engine without any
injected fault. The third forced restart within an hour writes the STOP
file. The container's stop is passed on to the engine, which closes in order.

At restart the engine adopts the guard's stops before reconciling, cancels
the orders it left open and plans again the exits already decided, so the
rules of SPEC 5.6 apply to them.

The acceptance test blocks the main loop right after a sale leaves: in
process on a demo-like broker, and with real processes in the drill, which
also runs inside the Docker image (tasks ci and the CI workflow). The guard
uses the ASP.NET shared runtime so both programs share /app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:36:32 +01:00
Alby96andClaude Opus 5.5 680cab4bb6 Recover missed work after an absence by the rules of SPEC 5.6 (refs #49)
At the start the host measures how long the bot was away from the last
job that finished, records the absence and writes it in the diary; one
longer than a day is kept for the Panoramica until the user has seen it.

A job can now say how a run missed while the bot was off is treated: the
nightly backup, the exchange rates, the market calendar and the cleanup
run once at the restart, queued, however late; a job with a deadline is
skipped past it and the diary says so. Corporate actions are read before
the reconciliation puts any stop back. A decision the engine makes late
because of an absence is written in the diary as recovered, as are the
orders it releases late; entries that moved too far or expired are
dropped with their reason.

Tests switch the bot off for 3 hours, 20 hours and 3 days with a manual
clock and check each of those rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:38:50 +01:00
Alby96andClaude Opus 5.5 41e067e7d1 Run the strategies live in simulation with the live engine (refs #47)
The live engine makes each decision at its time of SPEC 5.5 through the
same DecideOnce call the backtest uses, so live and backtest cannot drift:
the crypto close at 00:05 UTC, the stock signals 20 minutes after the
close, the meanrev exits 5 minutes before it, the stock orders and the
daily stops at the open. Each decision has a run key written in the same
transaction as its decision rows, planned orders and diary lines, and each
planned order's id gives the order key, so a restart never decides or
sends anything twice. Entries recovered late are dropped when the price
has moved too far.

The engine runs from the scheduler once the accounts are reconciled. The
IEX stream follows held stocks, planned orders and SPY during the session,
and the stock simulator's day orders now expire at the close.

Tests: parity with the backtest for crypto_trend (40 days) and
equity_meanrev (6 weeks), and a 14-day run with the network down, a lost
answer, a restart mid-order and the database unreachable, ending
reconciled with no duplicate orders, on SQLite and PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:28:08 +01:00
Alby96andClaude Opus 5.5 98ee504dab Write the diary from fixed templates and add the "senza bot" comparison (refs #50)
The diary needs sentences in the tone of appendix B, built only from what
happened. DiaryText holds the templates the live engine will use: fills
with the result of the trade they close, raised stops, the daily crypto
close, the stock signals, observation signals, recovery and absence. The
reason-code sentences move from the server into the library
(ReasonCatalog) so the engine and the screens share them; a test checks
that every reason constant has its sentence. The diary gets the kinds of
the Diario screen: Ordini, Decisioni, Sistema, Notizie, Apprendimento.

The comparison of SPEC 7.5 invests each capital flow on its day, 40% in
BTC/EUR and 60% in SPY adjusted and converted at the ECB rate, and never
touches it; a withdrawal sells both in the proportion they reached. Prices
are the closes of the day before, so a deposit is never a gain. Without
the SPY history (no Alpaca keys) the photograph leaves it empty rather
than show half a comparison. The Panoramica now takes the flows out of
the "Senza bot" result, as it already did for the bot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:46:28 +01:00
Alby96 e3c9eae65b Merge pull request 'Fase 5 — Strategie, portafoglio e rischio' (#91) from fase-5 into main
ci / test (postgres) (push) Successful in 5m34s
ci / test (sqlite) (push) Successful in 3m11s
ci / image (push) Successful in 5s
2026-11-11 17:30:08 +01:00
Alby96andClaude Opus 5.5 fc5df0146e Prepare strategies before the host is ready; stop demo servers first (refs #44 #45)
ci / test (postgres) (push) Successful in 4m39s
ci / test (sqlite) (push) Successful in 2m57s
ci / image (push) Successful in 56s
ci / test (postgres) (pull_request) Successful in 5m27s
ci / test (sqlite) (pull_request) Successful in 3m14s
ci / image (pull_request) Successful in 10s
Loading the outcomes before "ready" was not enough: on a fresh database the
strategy rows did not exist yet, so the load did nothing and CI run 220
failed the same way on PostgreSQL. The new TradingService.PrepareAsync
creates accounts and strategies, then loads the outcomes; the host runs it
before it is ready and logs a failure without blocking the interface.
StartAsync repeats it, which changes nothing.

The demo tests deleted the demo folder while the server still held its
SQLite file, which Windows refuses at random. They now stop the server
first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:19:15 +01:00
Alby96andClaude Opus 5.5 dc1ba4e701 Load the backtest outcomes before the host is ready (refs #44 #45)
ci / test (postgres) (push) Failing after 4m53s
ci / test (sqlite) (push) Successful in 3m4s
ci / image (push) Skipped
The trading service loaded the outcomes in the background after the host
reported "ready", so for a moment Strategie showed every strategy as
without a backtest. CI run 219 caught it on SQLite. The host now loads
them before it is ready; the call is idempotent, so the one at trading
start changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:01:25 +01:00
Alby96andClaude Opus 5.5 9ac159a7db Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46)
ci / test (postgres) (push) Successful in 3m52s
ci / test (sqlite) (push) Failing after 2m41s
ci / image (push) Skipped
An independent review found these, now fixed and tested:

- Risk limits could be raised through PUT /api/settings without the
  phrase and the password. The API now refuses risk keys.
- The reference equity counted results twice after reduced to real and
  after a demotion. Each ledger now keeps a baseline, and carried results
  stay in the ledger's currency until the reference is computed.
- An instrument could be bought by a second strategy in the same account
  (SPEC 8.6), and purchases under way did not hold their cash, so several
  purchases sent together could exceed it. Both are refused or shrunk now.
- After an automatic trip of the switch there was no way to restart from
  the interface. Rischio now shows the trip of both worlds and the restart.
- The fresh password of SPEC 12.4 could be tried without limit. Five wrong
  attempts in 15 minutes now lock it.
- Observation to simulation skipped the 90 days of live signals.
- A new build changed the qualification of a strategy with real money,
  "Ferma tutto" counted as a critical incident, raising risk ignored
  demotion conditions in progress, and weekends counted as stock sessions.
- The 12.4 confirmation now summarises capital, first purchases and limits,
  and live strategies show the gap with their simulated twin.

The backtest converts each bar with the rate fixed before it opens, the
day before, and the report now counts how often correctives and risk
changed a decision. crypto_trend is still not passed: the broad universe
now falls 32.8%. The outcome file also keeps the qualified parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:48:41 +01:00
Alby96andClaude Opus 5.5 17d6b8db38 Record the Phase 5 choices and close the roadmap items (refs #46)
ADR 0011 collects what the specification leaves open or refines in this
phase: strategies shared by backtest and live, correctives and risk inside
the backtests, the risk engine that only refuses or shrinks, the stages as
the only way to real money, the euro history and the protocol of the base
backtests, and the honest "not passed" of crypto_trend.

ROADMAP ticks the Phase 5 items and criteria with the tests that prove
them; STATE moves to Phase 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:19:35 +01:00
Alby96andClaude Opus 5.5 13f9c42f61 Add the Operazioni, Strategie and Rischio screens (refs #45)
The three screens follow mockups 03, 04 and 07.

Operazioni shows the balance of the closed trades, filters, a CSV export,
and for each trade why it was bought and sold. The reasons come from the
decision codes through fixed Italian templates.

Strategie shows the four stages towards real money, a card per strategy
with its requirements, the procedure of SPEC 12.4, and why each strategy in
observation waits. A strategy that failed its backtest cannot be moved into
the simulation.

Rischio shows the emergency switch, the automatic blocks, the use of each
limit, the fall from the peak, the scenarios and the risk events. Stop,
close and restart now go through the risk engine. A restart is refused
while the STOP file exists.

Impostazioni gains the limits, the day-trade guard and the scenarios.
Lowering a limit is always allowed. Raising a limit or the entrusted capital
while a strategy uses real money needs the phrase and the password.

The demo now holds the decisions behind its trades, the 58 days of
simulation and the indices of its curves, so it matches the mockups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:14:44 +01:00
Alby96andClaude Opus 5.5 7041533ce2 Add the honest backtests of the base strategies (refs #44)
crypto_trend now has a backtest report and an outcome file, computed by
"anubis backtest base" on the Binance daily archives from 2019 to October
2026. Prices are converted from USDT to euro with the ECB rate of the day,
and delisted coins stay in the universe, so survivors do not flatter the
result. The protocol runs the broad universe and BTC, ETH and SOL, with
costs doubled and tripled and buy and hold beside. Both universes must pass.

The outcome is "not passed": the broad universe falls 29.1% (limit 25%) and
the narrow one has a probability of overfitting of 0.84 (limit 0.40). The
strategy therefore stays in observation. The stock strategies wait for the
Alpaca keys and stay in observation too. The bot reads the outcome files at
every start.

Trials now read 450 days of history before their start, only so the
indicators and the 400-day listing age are ready on the first day. Before
this, 2019 was spent warming up and BTC and ETH could not be chosen until
2020. A daily series also stops at a hole longer than a week, so the LUNA
relaunched in 2022 is not mistaken for the coin that collapsed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:13:23 +01:00
Alby96andClaude Opus 5.5 8def84e122 Add the risk engine, correctives and strategy stages (refs #41 #42 #43)
Every intent of a strategy now crosses a risk engine that only refuses or
shrinks: loss limits per world with the 24-hour block, the weekly halving,
the halving and the switch on the fall from the high, the size limits on
invested capital, single position, crypto share and trade risk, the
technical checks, no short sales and no leverage, the day-trade guard
(off by default). The switch, "Ferma tutto", "Ferma e chiudi", the STOP
file and the orders-per-minute anomaly stop the bot until the user
confirms a restart, and a restart after a trip measures the high from
then on.

The correctives of SPEC 8.5 (crypto regime, economic calendar) and the
risk rules also run inside the backtests of the base strategies, so the
reports show what would happen live. Each stage of a decision is written
to a new decisions table with reason codes.

The stage book is the only way to real money: an order on a real account
needs the startup consent, every requirement of SPEC 12.3 met, the typed
phrase and a fresh password and second factor. Order managers on real
accounts fail closed and ask again before each order leaves. A demoted or
revoked strategy keeps its real positions in exit only, with stops, until
they are at zero. The simulated twin stays out of totals and of the
reference equity.

Tests cover each rule of 9.1 and 9.2, with property tests for "never
larger than asked" and "never larger after a loss", and both proofs on a
fake real account: nothing reaches it without the procedure, and a
demoted strategy manages exits and stops down to zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:22:35 +01:00
Alby96andClaude Opus 5.5 2409e74b26 Add the three base strategies and their indicators (refs #38 #39 #40)
crypto_trend follows nine breakout periods with Donchian-middle stops,
volatility-targeted weights under the 35%/20% caps and a monthly top-10
universe. equity_momentum reviews on the last close of each week with the
SPY filter, inverse-volatility weights and an ATR trailing stop.
equity_meanrev buys RSI(2) dips above the 200-session average, sized for
a fixed risk, and exits at the close.

The engine gains what the rules need: exits at the same close, a stop set
at a distance from the price obtained, data-only instruments such as SPY,
the trading calendar, the reference equity of the strategy's share and the
equity history. Every strategy passes the look-ahead check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:43:19 +01:00
Alby96 a6227793c3 Merge Phase 4: backtest and laboratory (#90)
ci / test (postgres) (push) Successful in 2m58s
ci / test (sqlite) (push) Successful in 2m11s
ci / image (push) Successful in 9s
2026-11-11 14:18:18 +01:00
Alby96andClaude Opus 5.5 9db95ea79a Add the VS Code debug configuration
ci / test (postgres) (push) Successful in 3m18s
ci / test (sqlite) (push) Successful in 2m1s
ci / test (postgres) (pull_request) Successful in 3m50s
ci / test (sqlite) (pull_request) Successful in 2m26s
ci / image (push) Successful in 8s
ci / image (pull_request) Successful in 6s
Four launch entries for the server: a data folder of its own under
artifacts/ (ignored by git), the demo mode, the user's real data folder,
and attach to a running process. Each builds in Debug first and opens the
browser once the server listens. tasks.json also exposes check, test and
dev. SVILUPPO.md explains which entry to pick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:53:49 +01:00
Alby96andClaude Opus 5.5 f278ff4f67 Fix the defects of the Phase 4 review (refs #34 #35 #36)
ci / test (postgres) (push) Successful in 2m41s
ci / test (sqlite) (push) Successful in 1m56s
ci / test (postgres) (pull_request) Successful in 3m45s
ci / test (sqlite) (pull_request) Successful in 2m22s
ci / image (push) Successful in 1m10s
ci / image (pull_request) Successful in 13s
- An error of the database (PostgreSQL restarting) no longer stops the
  laboratory until the next start: the queue logs it, waits 30 seconds
  on the injectable clock and tries the same trial again.
- Buy and hold, the comparison of every report, buys an instrument
  whose history starts later at its first close, with the share kept
  free for it; before, it was never bought and the others took its
  weight. Its version goes to 2.
- The comparison page reads a and b as text: a malformed id shows
  "two finished tests needed" instead of an error page.
- A trial re-checks the hash of its plan before running and refuses a
  plan that no longer matches it.
- Parameters that count days take whole numbers only (10.5 would run
  as 10 and count twice in the DSR); the capital starts from 1, as the
  message says.

ADR 0010 says so, and corrects the estimated minimum of the research
history: 5 does refuse smaller orders, like the exchanges' minimums.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:17:18 +01:00
Alby96andClaude Opus 5.5 af7528560f Record the Phase 4 choices and close the roadmap items (refs #37)
ADR 0010 writes down what the specification leaves open: the event
order of a session, the costs shared with the simulator, the pass-through
correctives and risk until Phase 5, the in-house statistics, validations
on the daily returns of the variants, the plateau rule as the minimum of
own and neighbourhood Sharpe, the sizes of walk-forward, CPCV and CSCV,
the trial count of the DSR, the plan written first and never changed,
the low-priority laboratory and the two data origins (the research
history stays in USDT; a trial uses a single currency).

ROADMAP ticks the four acceptance criteria with the tests that prove
them; STATE moves to Phase 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:05:05 +01:00
Alby96andClaude Opus 5.5 953ffe5e9b Add the Laboratorio screen: new test, report, comparison (refs #36)
The laboratory starts with the host (off in demo mode) and runs its
queue next to market data and trading. The page lists every trial with
status, verdict and headline figures, refreshing itself while one is
queued or running, and offers the form for a new test: strategy, data
origin and market, instruments, period, initial capital and the grid,
with the thresholds stated before the run. The form posts with the
antiforgery token; errors come back as a short code.

The report page shows the protocol checks, the chosen variant against
buy and hold (table and chart), results per year, cost sensitivity,
the Deflated Sharpe Ratio, PBO, walk-forward windows, purged CV paths,
the look-ahead result, every variant with its zone score, what the
backtest does not model, the data used and the trades. A comparison
page puts two finished tests side by side and says whether they read
the same data. The improvements of 8.7 and the cost estimates of 11.6
have their sections, empty until Phases 9 and 8.

The equity chart takes amounts in their own currency and its labels as
parameters. The profit factor has no value without a losing trade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:01:05 +01:00
Alby96andClaude Opus 5.5 5efb149fd6 Add the trial register, the report and the laboratory queue (refs #35 #36)
A trial is planned before it runs: strategy and version, grid, data,
initial capital, cost multipliers, validation settings, thresholds and
engine version go into backtest_trials as JSON with the SHA-256 of the
text. The store has no way to change a plan; later writes touch only
status, verdict, results and times, and a test reads the raw row back
to prove it. Every finished trial stays and counts towards the number
of tries the Deflated Sharpe Ratio deflates for.

The trial runner is pure computation: every grid variant on the whole
period, plateau choice, the chosen variant again at double and triple
costs, buy and hold, walk-forward, purged CV, PBO, DSR and the
look-ahead check, then the five thresholds of SPEC 12.2 and the report
of point 6 with the limitations the backtest declares (no correctives
without history, no risk engine before Phase 5).

The laboratory writes the plan, queues the trial and runs one at a time
on a dedicated thread with below-normal priority; only the async side
reads and writes the database. On start, trials left running go back
to planned and run again. Data comes from the daily bars and corporate
actions in the database, or from the Binance research history with
estimated order rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:49:05 +01:00
Alby96andClaude Opus 5.5 ccb9602950 Add backtest metrics, Deflated Sharpe, PBO, purged CV and the look-ahead test (refs #34 #35)
Metrics give what the report of SPEC 12.2 point 6 needs: return, CAGR,
annualised volatility and Sharpe, max drawdown with its days, trades,
win rate, profit factor, fees, exposure and results per calendar year.

Statistics are written in house as SPEC 12.2 asks: the normal CDF
(Hart 5666, double precision) and quantile (Acklam plus a Halley step),
moments, the probabilistic and the Deflated Sharpe Ratio. The DSR test
reproduces the example of Bailey and López de Prado (SR0 0.1132, DSR
0.9004).

Validation works on the daily returns of every grid variant:
walk-forward with a growing window, combinatorial purged CV (6 groups,
2 tested: 15 splits, 5 paths, purge and embargo of 1% of the series)
and PBO by CSCV (16 groups). Pure noise gives a PBO near 0.5, a
dominating variant 0, a winner that always loses out of sample 1.
Choices follow the plateau rule: a variant scores its own Sharpe but no
more than the mean of its zone, so a lonely peak loses to a broad hill
and a poor variant does not win by standing next to a good one.

The look-ahead check reruns the strategy on data cut at six days and
requires every decision up to each cut to be unchanged; it fails on a
strategy that reads tomorrow and passes on the average cross. The
one-step comparison of SPEC 12.3 classifies intents and flags action
differences and sizes more than 10% apart. A golden run guards the
engine against unintended changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:40:06 +01:00
Alby96andClaude Opus 5.5 d97304d7b9 Add the event-driven backtest engine and the strategy interface (refs #34)
The strategy contract of SPEC 5.3 (IStrategy, StrategyContext, Intent) is
shared by backtest and live: the context exposes bars only up to the
decision, adjusted and anchored to that day, and reading past it throws.
The engine runs each session as ordered events (corporate actions, open,
session, close), decides on the close and executes at the next open with
the simulator's price lists, slippage tiers, tick and lot rounding,
minimums and no leverage. Corrective and risk hooks are wired in and pass
everything through until Phase 5. One decision cycle can restart from a
recorded book (SPEC 12.3).

A scripted toy strategy reproduces a result computed by hand to the cent
on OKX and Alpaca costs. The Phase 3 class Trading.Strategies becomes
StrategyNames so the Anubis.Strategies namespace can exist.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:47:36 +01:00
Alby96andClaude Opus 5.5 60d5ebbc05 Document Phase 3; fix CSV decimals and Alpaca price steps (refs #33 #31 #32 #27)
ADR 0009 records the Phase 3 choices; API-NOTES gains the verified trading
facts and what Anubis does with each; ROADMAP and STATE mark the phase done
with the live-demo conformance waiting for the user's keys.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:24:38 +01:00
Alby96andClaude Opus 5.5 4c4f848d80 Add the Conti screen, account keys and entrusted capital (refs #32 #29 #31)
The Conti e posizioni screen follows mockup 02: totals split by strategy,
one card per account with key permissions and the last reconciliation,
positions with a per-account filter and CSV export, pending stops (Alpaca
grouped into permanent and day stops), residues, and exposure by currency.
It shows one world only, real accounts when there are any, so simulated
and real money never add up. Position values are rounded to the cent per
row, as the table shows them, so the figures add up on screen.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:16:42 +01:00
Alby96andClaude Opus 5.5 d2441df592 Add the broker conformance battery and trading service tests (refs #26 #28 #29 #31)
One abstract battery states the adapter contract (time and cash, an order's
client id from send to cancel, well-formed orders, positions and fills with
fees as costs, key permissions) and runs it on the internal simulator, on
Alpaca's and OKX's documentation samples with stateful fakes, and on the demo
accounts when the user's keys are in the environment (LiveDemo, inconclusive
without them). The OKX sample key lists withdraw, and the adapter reports it.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:40:21 +01:00
Alby96andClaude Opus 5.5 1419457fe4 Add the trading core: ledger, simulator, order manager, reconciliation (refs #26 #27 #28 #29 #30)
Phase 3 needs books the bot can trust before any strategy trades. This adds:
- schema 0003: executions, order events, trades, residues, account status,
  reconciliations, capital changes, applied corporate actions, simulator books;
- the broker interface with the internal simulator and the Alpaca paper and
  OKX demo adapters, all behind the live guard (SPEC 2.2);
- the append-only ledger with lots, trades from zero to zero, residues,
  dividends, splits and reversals; capital entrusted per broker and equity
  photographs with time-weighted return and FX effect;
- the order manager (chasing limit, pacing, sells never abandoned, server
  stops, breached-stop rule) and the reconciler with prudent mode;
- the trading service wired into the host, off in demo mode and in tests.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:29:02 +01:00
Alby96 74d4c4fa6f Merge pull request 'Fase 2 — Dati di mercato' (#88) from fase-2 into main
ci / test (postgres) (push) Successful in 2m59s
ci / test (sqlite) (push) Successful in 2m38s
ci / image (push) Successful in 30s
2026-11-10 17:53:12 +01:00
Alby96andClaude Opus 5.5 1a8d48212f Give test databases a longer PostgreSQL connect timeout (refs #20 #25)
ci / test (postgres) (push) Successful in 2m37s
ci / test (sqlite) (push) Successful in 2m4s
ci / test (postgres) (pull_request) Successful in 3m17s
ci / test (sqlite) (pull_request) Successful in 2m22s
ci / image (push) Successful in 35s
ci / image (pull_request) Successful in 11s
On the CI runner twelve test workers open PostgreSQL connections at once
and some waited longer than the application's 5 seconds, failing two
collector tests with a connection timeout that has nothing to do with
the code under test. The connect timeout is now a DbSettings field that
keeps the 5-second default for the application, and the test databases
ask for 30 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:40:12 +01:00
Alby96andClaude Opus 5.5 094a527ba2 Make two tests steady on a busy CI runner (refs #20 #25)
ci / test (postgres) (push) Successful in 2m48s
ci / test (sqlite) (push) Successful in 2m10s
ci / test (postgres) (pull_request) Failing after 3m37s
ci / test (sqlite) (pull_request) Successful in 2m20s
ci / image (pull_request) Skipped
ci / image (push) Successful in 21s
- The skipped-minute test waited for the recovered bar, but the issue is
  closed a moment after the bar is stored; on PostgreSQL in CI (run 181) it
  read the issue in between and saw it still open. It now waits for the
  issue's final state.
- Creating a PostgreSQL test database retries on a connection timeout: CI
  run 179 on main failed because twelve workers created their databases at
  once and one connection missed the application's 5-second timeout. The
  application's timeout is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:23:58 +01:00
Alby96andClaude Opus 5.5 de2cc0eedf Fix the phase 2 review findings (refs #20 #23 #25)
ci / test (postgres) (push) Successful in 2m10s
ci / test (sqlite) (push) Successful in 2m14s
ci / image (push) Successful in 31s
ci / test (postgres) (pull_request) Failing after 2m50s
ci / test (sqlite) (pull_request) Successful in 2m27s
ci / image (pull_request) Skipped
- Gaps between the last stored bar and the first new one were never found,
  so a minute the live feed skipped, or a day missing right after the stored
  history, was lost for good. A gap is now new when it ends after the last
  bar held, and is downloaded again like any other.
- When one OKX connection dropped while the other kept writing, the write to
  the closed feed threw out of the live loop and left it marked connected.
  Writes now stop quietly, and the loop treats any failure (database
  included) as a drop: marked down, back off, reconnect.
- The background worker now survives a failed round instead of stopping for
  the life of the process.
- Alpaca gives adjusted prices on the basis of the download day, so a later
  split looked like a crash. Each download re-reads the last stored day and,
  if its adjusted/real ratio changed, rescales all older adjusted prices.
- Stock days are fetched up to the last closed New York session, so the job
  after the close collects that day; missing stock days are checked against
  the exchange calendar; delisted stocks with history are not asked again.
- Smaller: a lock in the freshness monitor, no NaN mood readings (SQLite
  stored them as NULL), and the network proof runs only with
  ANUBIS_LIVE_PROOF=1. The test wait is 30 s for busy machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:06:39 +01:00
Alby96andClaude Opus 5.5 68fdd0baee Record the Phase 2 choices, verified facts and state (refs #25)
ADR 0008 collects the market data decisions the spec leaves open: research
history in csv.gz instead of Parquet (no extra package), the immediate second
reading of suspect data, EUR pairs only, Alpaca only with the paper keys,
name-based fund exclusion and the background worker. API-NOTES gets the facts
checked while writing the adapters and the biases that remain in past
universes. ROADMAP and STATE mark the phase done, with the stock history still
waiting for the user's Alpaca keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:55:01 +01:00
Alby96andClaude Opus 5.5 aa2766f3ed Add a network proof of the real daily history (refs #18 #21)
A LiveDemo test, outside the normal suite, that downloads the whole OKX EUR
daily history of BTC, ETH and SOL and the Binance BTCUSDT archives since 2017,
then writes the quality report. It is the evidence for the phase criteria that
a fake network cannot give.

The detached database test now retries the file move for a few seconds:
Windows refuses to move the SQLite file while a request of the running server
holds it, which made the test fail now and then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:51:37 +01:00
Alby96andClaude Opus 5.5 4a65d4060f Show data sources and the central bank list in Settings (refs #22)
A "Dati" section lists every external source with its state, last answer
and the reason it is off (Alpaca without the paper keys, FRED and Finnhub
without theirs), links the 30-day quality report, and edits the Fed/ECB
meeting list; a list that does not parse is refused with an example.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:45:06 +01:00
Alby96andClaude Opus 5.5 1e71038209 Run market data inside the server (refs #19 #20 #22 #24)
MarketDataService wires the collector, the reference sources, the
universes and the corporate actions into the scheduler. Short jobs (rates,
calendar, mood, spread samples, corporate actions) run on their schedule;
long downloads (catalogues, the first history, thousands of stocks, the
Binance archives) run on a background worker the jobs only wake, so they
never delay the backup or each other. The live crypto feed follows the
crypto universe, or BTC, ETH and SOL until one exists.

Alpaca uses only the paper account keys; without them the stock part is off
and the sources list says why. Market data is off in demo mode, with
ANUBIS_MARKET_DATA=off, and in tests that bring no fake network.

New: GET /api/data/quality (JSON or Markdown) and /api/data/sources, and
"anubis data report|binance|csv" on the command line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:42:10 +01:00
Alby96andClaude Opus 5.5 49ed73e6f6 Add the market data collector, universes and corporate action store (refs #20 #23 #24)
MarketCollector downloads what is missing at startup and after every drop
of the live feed, checks every bar and never corrects in silence: suspect
bars are stored as suspect and read a second time (same values confirm,
different ones replace, impossible ones are dropped), gaps are downloaded
again once and what the source still lacks is recorded as unrecoverable.
A test detaches the feed for ten minutes and finds every minute recovered.

The stock and crypto universes are chosen "as of a date" from the bars up to
that date only: funds, ETFs and ETNs are excluded through nasdaqtraded.txt
and the security name, stocks delisted later still count when they traded.
Corporate actions are kept once per source key and found by ex-date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:33:40 +01:00
Alby96andClaude Opus 5.5 b3fb69e696 Add free reference sources and research importers (refs #21 #22)
Readers for the ECB rates, the Forex Factory calendar, FRED release dates,
Finnhub earnings, the Fed/ECB meeting list, fear and greed, the Cboe VIX
history, nasdaqtraded.txt and the Binance kline archives, each tested on
recorded responses. ReferenceSources downloads them within their limits
and records every attempt in source_state, so limits hold across restarts
and the interface can say which source is off and why (FRED and Finnhub
without a key). The central-bank list is an editable, validated setting.

BinanceImporter checks every monthly zip against its SHA-256 file before
writing it to the research history; CsvImporter reads user files with a
configurable column mapping and reports unreadable lines and gaps instead
of fixing them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:20:35 +01:00
Alby96andClaude Opus 5.5 956306a8fa Add OKX Europe and Alpaca market data clients (refs #18 #19)
Both clients are written in house on HttpClient and ClientWebSocket, behind
IMarketDataSource, with a rate limiter on the injected clock and retries
that wait on it too.

OKX: EUR pairs only (trap 14), rules from public/instruments, daily
candles with bar=1Dutc and a refusal of any candle not opening at 00:00
UTC (trap 23), backwards paging of history-candles, errors read from the
code field because OKX answers them with HTTP 200, tickers on the public
stream and candles on the business stream with ping after silence. The
HMAC signer and the demo header are ready for Phase 3.

Alpaca: consolidated daily bars, real and adjusted, dated in New York and
never newer than 15 minutes (trap 8), an explicit feed on every request,
IEX for recent minutes, quotes and the stream (at most 30 symbols),
calendar and clock converted to UTC, corporate actions. Without keys
nothing is sent and the reason is stated. Tests use the documentation's
examples and synthetic answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:07:23 +01:00
Alby96andClaude Opus 5.5 3b13a4258d Add market data schema, catalogue, bar storage and quality checks (refs #18 #20 #21 #23)
Migration 0002 adds the market data tables on both engines: daily and
one-minute bars, corporate actions, FX rates, the exchange calendar,
calendar events, mood indicators, spread samples, data issues, source
state and universe members, plus the trading rules on instruments.

The data layer is format-independent so the venue clients can build on
it: the instrument catalogue (rules from the venue, delisted kept), bar
upserts with ON CONFLICT, the SPEC 6.4 checks with an issue register
that blocks entries until a second reading, freshness by age of the last
datum (trap 10), research history in .csv.gz with exact decimals, and
adjusted series anchored at the decision day with level and quantity
conversion across splits and dividends.

Recorded API responses from OKX, the Alpaca docs and the free sources
are kept byte for byte as test fixtures; the secret scan now ignores
pagination cursors such as Alpaca's next_page_token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:58:44 +01:00
Alby96 67350f091e Merge Instrument Sans typeface (fase-1-carattere) into main
ci / test (postgres) (push) Failing after 2m28s
ci / test (sqlite) (push) Successful in 2m12s
ci / image (push) Skipped
Bundle the Instrument Sans typeface, approved by the user.
2026-11-10 14:27:41 +01:00
Alby96andClaude Opus 5.5 992467ff04 Bundle the Instrument Sans typeface (refs #13)
ci / test (postgres) (push) Successful in 2m23s
ci / test (sqlite) (push) Successful in 2m5s
ci / image (push) Successful in 30s
ci / test (postgres) (pull_request) Successful in 2m14s
ci / test (sqlite) (pull_request) Successful in 1m58s
ci / image (pull_request) Successful in 9s
The user allowed the download, so the interface now uses the typeface
of the mockups instead of the system one. The variable file (weights
400-700) and its SIL OFL licence are embedded and served by the app
itself, never fetched from the internet; source and SHA-256 are in
API-NOTES. The typeface is slightly wider, so top-bar labels and
buttons move to 13 px as in the mockup, keeping the date line whole at
1440 px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:07:47 +01:00
Alby96 cf6d0536aa Merge phase 1 (fase-1) into main
ci / test (postgres) (push) Successful in 2m47s
ci / test (sqlite) (push) Successful in 2m8s
ci / image (push) Successful in 12s
Phase 1 foundations: platform, portable database, access, interface shell, demo mode, Docker image.
2026-11-10 13:10:44 +01:00
Alby96andClaude Opus 5.5 101dcbb152 Fix two startup races found by CI on Linux (refs #9 #14)
ci / test (postgres) (push) Successful in 2m31s
ci / test (sqlite) (push) Successful in 2m8s
ci / image (push) Successful in 59s
ci / test (postgres) (pull_request) Successful in 2m23s
ci / test (sqlite) (pull_request) Successful in 2m4s
ci / image (pull_request) Successful in 9s
An error-page choice released the startup loop before resetting the
services, so the loop could start the application and then lose its
services while reporting ready. The reset now happens while the loop is
still held, and moves the status back to Starting.

A SQLite file could vanish between the existence check and the open;
with create allowed, the open would put an empty database in its place.
Once the file has been seen, connections open read-write only and fail
on a missing file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:51:33 +01:00
Alby96andClaude Opus 5.5 f9d71559e8 feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
ci / test (postgres) (push) Successful in 2m22s
ci / test (sqlite) (push) Failing after 2m27s
ci / image (push) Skipped
Phase 1 completed on top of the library foundations:
- Server: startup state machine (config, first run, database down, schema,
  identity, ready) with an error page that retries by itself; the configured
  database is the only one ever opened, and a vanished SQLite file is never
  recreated. REST API and status WebSocket; session cookie auth, CSRF on
  every form and write call; desktop and demo answer only the computer itself.
- Interface: static Blazor rendering with plain forms (no interactive
  runtime), menu, top bar and phone bottom bar as in the mockups, light and
  dark themes with appendix C tokens and a contrast test, Panoramica, Diario,
  Rischio, Impostazioni; service pages for sign-in, first access, desktop
  first run and the database error page with its choices.
- Demo mode (tasks seed-demo): appendix F in a database of its own under the
  temp folder, frozen clock, never touches the configured installation.
- Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv,
  HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong
  configuration and a database that goes away and comes back.
- tasks screenshots drives the installed Edge/Chrome through DevTools for
  exact 1440 and 390 pixel shots; anubis db export|import on the command line.

Fixes from the independent review: return paths without control characters,
Host check against DNS rebinding, attempt limit counted before the check and
also on the error-page password, one-use TOTP codes and a code to switch the
second factor off, error-page choices serialized with the startup loop,
identity checked before migrating, restore restarts with "Ferma tutto" on,
damaged archives reported instead of crashing. Running the server tests on
PostgreSQL exposed pages rendered before their data arrived; data-loading
components now load first (LoadedComponent).

Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:40:15 +01:00
Alby96andClaude Opus 5.5 53ca01b7c3 feat(core): platform layer, portable database, archives and access (refs #7 #8 #9 #10 #11)
Phase 1 foundations in the Anubis library:
- Platform: startup configuration from environment variables (Docker) or
  config.toml (desktop, in-house TOML subset), data folder layout, secret key
  custody (ANUBIS_SECRET_KEY, DPAPI on Windows, restricted file elsewhere),
  installation identity and database fingerprint.
- Db: ADO.NET with Npgsql and Microsoft.Data.Sqlite, money as NUMERIC(38,18)
  or canonical text rounded to 18 decimals, UTC moments, UUIDv7 ids; numbered
  SQL migrations with type tokens and a version table; engine-independent
  export/import with count and accounting-total checks; backups keeping 14.
- Core: injectable clock, channel event bus, scheduler with fixed, interval
  and market-relative times, settings with change log, AES-GCM secrets, log
  redaction, Italian formats.
- Access: PBKDF2-SHA512 hashes, RFC 6238 TOTP, hashed session tokens,
  sign-in attempt limit.

SQLitePCLRaw (Apache-2.0) arrives with Microsoft.Data.Sqlite and is declared
in DependencyPolicyTests and API-NOTES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:09:42 +01:00
Alby96 ffb67c9135 Merge phase 0 (fase-0) into main
ci / test (postgres) (push) Successful in 1m10s
ci / test (sqlite) (push) Successful in 1m2s
ci / image (push) Successful in 7s
Phase 0: toolchain, minimal app, Docker, CI and re-checked API facts.

Closes #1, #2, #3, #4, #5, #6
2026-11-10 10:22:57 +01:00
372 changed files with 110263 additions and 168 deletions

No files matched your search

+2
View File
@@ -6,6 +6,8 @@
artifacts/
TestResults/
docs/
!docs/design/logo/
!docs/backtests/*.outcome.json
**/*.md
.env
.env.*
+4
View File
@@ -24,3 +24,7 @@ csharp_using_directive_placement = outside_namespace:warning
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = 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
+9
View File
@@ -3,5 +3,14 @@
*.sh text eol=lf
.githooks/* text eol=lf
Dockerfile text eol=lf
# Windows scripts and the instructions in the release zip keep CRLF (ADR 0013).
*.cmd text eol=crlf
deploy/windows/*.txt text eol=crlf
*.png binary
*.ico binary
*.ttf binary
# Recorded API responses stay byte for byte as the source sent them (CRLF in nasdaqtraded.txt included).
tests/Anubis.Tests/Fixtures/** -text
# The tokenizer of the news classifier stays byte for byte as published (hashes in ADR 0014).
src/Anubis/News/Model/*.json -text
src/Anubis/News/Model/*.txt -text
+4
View File
@@ -32,6 +32,7 @@ jobs:
ANUBIS_TEST_DB: ${{ matrix.db }}
ANUBIS_TEST_PG_HOST: postgres
ANUBIS_TEST_PG_PORT: "5432"
ANUBIS_TEST_PG_PASSWORD: anubis-ci
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
DOTNET_NOLOGO: "1"
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
@@ -62,3 +63,6 @@ jobs:
git checkout -q FETCH_HEAD
- name: Build image (no publish)
run: docker build -f deploy/docker/Dockerfile -t anubis:ci .
# The guard drill inside the image (issue #48): offline, its own SQLite database in a temporary folder.
- name: Guard drill in the image
run: docker run --rm anubis:ci drill
+4
View File
@@ -0,0 +1,4 @@
{
// The C# extension provides the "coreclr" debugger used by launch.json.
"recommendations": ["ms-dotnettools.csharp"]
}
+70
View File
@@ -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}"
}
]
}
+45
View File
@@ -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": []
}
]
}
+8 -4
View File
@@ -11,15 +11,18 @@ Bot di trading personale: azioni USA su Alpaca, crypto spot su OKX Europe, senza
## 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.
- `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`.
- `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.
- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili.
- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`.
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
- `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea.
- `desktop-win` (Fase 10): non ancora disponibile.
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
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/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti
- `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri
- `docs/adr/0007-scelte-fase-1.md` — schema per i due motori, interfaccia statica, immagine Docker
- `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo
- `docs/ROADMAP.md` — fasi, issue, criteri di accettazione
- `docs/STATE.md` — stato corrente
+1 -1
View File
@@ -13,7 +13,7 @@
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
<Company>BalboSoft</Company>
<Product>Anubis</Product>
<Version>0.0.1</Version>
<Version>0.7.0</Version>
</PropertyGroup>
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
+12
View File
@@ -9,4 +9,16 @@
<PackageVersion Include="MSTest.TestAdapter" Version="4.5.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
</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>
+25 -7
View File
@@ -1,22 +1,40 @@
# Anubis image (ADR 0003). Phase 0: minimal server with /health.
# Phase 1 adds the entrypoint (PUID/PGID, data folder) and the HEALTHCHECK (issue #16).
# Anubis image (ADR 0003, SPEC 15.2). Build from the repository root:
# 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
WORKDIR /src
COPY global.json Directory.Build.props Directory.Packages.props ./
COPY src/Anubis/Anubis.csproj src/Anubis/packages.lock.json src/Anubis/
COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json src/Anubis.Server/
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode
COPY src/Anubis.Guard/Anubis.Guard.csproj src/Anubis.Guard/packages.lock.json src/Anubis.Guard/
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode && \
dotnet restore src/Anubis.Guard/Anubis.Guard.csproj --locked-mode
COPY src/Anubis/ src/Anubis/
COPY src/Anubis.Server/ src/Anubis.Server/
COPY src/Anubis.Guard/ src/Anubis.Guard/
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
COPY docs/design/logo/ docs/design/logo/
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
COPY docs/backtests/ docs/backtests/
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app ./
ENV ASPNETCORE_HTTP_PORTS=8787 \
TZ=Europe/Rome
COPY --chmod=755 deploy/docker/entrypoint.sh /usr/local/bin/anubis-entrypoint
# 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
VOLUME /data
USER $APP_UID
ENTRYPOINT ["dotnet", "Anubis.Server.dll"]
# Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts
# the engine. "docker run --rm <image> drill" runs the guard drill instead (issue #48).
# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy.
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
ENTRYPOINT ["anubis-entrypoint"]
+31
View File
@@ -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" "$@"
+8
View File
@@ -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
+44
View File
@@ -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"
+6
View File
@@ -1,11 +1,14 @@
# 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
# First access at http://localhost:8787 with ANUBIS_ADMIN_PASSWORD, then choose a new password.
services:
anubis:
build:
context: .
dockerfile: deploy/docker/Dockerfile
image: gitea.encke-hake.ts.net/balbosoft/anubis:dev
# The guard gives the engine up to 55 seconds to close in order (SPEC 9.3).
stop_grace_period: 60s
ports:
- "8787:8787"
environment:
@@ -15,6 +18,9 @@ services:
ANUBIS_DB_NAME: anubis
ANUBIS_DB_USER: anubis
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"
TZ: Europe/Rome
volumes:
+74 -6
View File
@@ -128,7 +128,7 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio
|---|---|---|---|---|
| M1 | `mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis`, licenza Apache-2.0 | confermato | — | https://huggingface.co/mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis |
| M2 | Esportazione ONNX pronta nei repository `Xenova/...` | confermato | `Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`: `onnx/model.onnx` (circa 329 MB), `onnx/model_quantized.onnx` (circa 83 MB) e `tokenizer.json`. Revisione da fissare: `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`. Il repository **non dichiara una licenza**: vale quella del modello originale (Apache-2.0), da annotare nell'ADR della Fase 7. | https://huggingface.co/Xenova/distilroberta-finetuned-financial-news-sentiment-analysis |
| M3 | 10–20 ms per titolo su CPU | non verificabile | Si misura nella Fase 7, con ONNX Runtime per .NET. | — |
| M3 | 10–20 ms per titolo su CPU | misurato | Il 15/11/2026, con ONNX Runtime 1.31.1 per .NET e il modello quantizzato su un solo thread: 23–24 ms per titolo sul PC di sviluppo (test `TheModelReadsTheToneOfFinancialHeadlines`). Con più thread scende, ma Anubis ne usa uno (ADR 0014, punto 8). | — |
| M4 | Claude Haiku 5.5: 0,10 $ in ingresso e 0,50 $ in uscita per milione di token (fino a 100.000 token); batch a metà prezzo; non ancora nella panoramica dei modelli | cambiato | Ora **è** nella panoramica, con identificativo `claude-haiku-5-5`. Prezzi confermati. Oltre i 100.000 token costa 0,50 $ e 2,50 $. | https://platform.claude.com/docs/en/about-claude/models/overview · https://platform.claude.com/docs/en/about-claude/pricing |
| M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing |
@@ -151,12 +151,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 |
| 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 |
| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo. | 3 |
| O7 liquidità | Elenco fisso di coppie ammesse e filtro sullo spread prima di ogni ordine. | 3, 5 |
| 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 (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 |
| 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 |
| 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
@@ -170,7 +230,7 @@ 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.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 |
| `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.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.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 |
@@ -202,10 +262,10 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
| 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 | — |
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 | — |
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 (in uso) | Nell'elenco del test dalla Fase 7. |
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
## Immagini Docker
@@ -213,3 +273,11 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
- `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.
- 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
+95 -94
View File
@@ -10,12 +10,12 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
| Fase | Titolo | Stato |
|---|---|---|
| 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 |
| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Da fare |
| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Da fare |
| 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Da fare |
| 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Da fare |
| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Da fare |
| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Completata |
| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Completata (azioni in attesa delle chiavi Alpaca) |
| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Completata (conti di prova in attesa delle chiavi) |
| 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Completata |
| 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Completata (`crypto_trend` non superato, azionarie in attesa delle chiavi Alpaca) |
| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Completata (prova di 48 ore in corso) |
| 7 | [Notizie](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/34) | Da fare |
| 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Da fare |
| 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Da fare |
@@ -53,30 +53,30 @@ Le basi su cui si appoggia tutto: piattaforma, database, sicurezza, guscio dell'
**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
- [ ] [#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
- [ ] [#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
- [ ] [#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
- [ ] [#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`)
- [ ] [#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] [#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] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL
- [x] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni
- [x] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati
- [x] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP
- [x] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket
- [x] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani
- [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
- [x] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`)
- [x] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck)
- [x] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1`
**Criteri di accettazione**
- [ ] 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)
- [ ] I formati numerici superano i test
- [ ] 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
- [ ] 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
- [ ] 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`
- [ ] La modalità dimostrativa non tocca il database configurato (test)
- [x] Accesso funzionante
- [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)
- [x] I formati numerici superano i test
- [x] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres`
- [x] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database
- [x] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola
- [x] La stessa batteria di test passa su entrambi i motori
- [x] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi
- [x] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml`
- [x] La modalità dimostrativa non tocca il database configurato (test)
## Fase 2 — Dati di mercato
@@ -86,22 +86,22 @@ Storico e dati dal vivo affidabili, controllati e senza sguardi in avanti.
**Lavori**
- [ ] [#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)
- [ ] [#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
- [ ] [#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
- [ ] [#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] [#18](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/18) Catalogo degli strumenti e parte dati dell'adapter OKX Europe
- [x] [#19](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/19) Parte dati dell'adapter Alpaca (piano gratuito)
- [x] [#20](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/20) Collector storico e dal vivo, recupero dei buchi, controlli di qualità, freschezza
- [x] [#21](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/21) Importatori: archivi Binance e CSV dell'utente verso lo storico di ricerca
- [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
- [x] [#23](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/23) Azioni societarie e serie rettificate ancorate al giorno della decisione
- [x] [#24](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/24) Universi "a una certa data" con esclusione degli ETF
- [x] [#25](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/25) Chiusura della fase, revisione indipendente e tag `fase-2`
**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
- [ ] 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
- [ ] Rapporto di qualità dei dati
- [ ] L'elenco dell'universo azionario a tre date passate non contiene ETF
- [ ] 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)
- [x] Senza chiavi Alpaca la parte azionaria si prova su dati sintetici e risposte d'esempio, e il criterio resta in attesa dell'utente
- [x] Un test stacca il flusso per 10 minuti e verifica che il buco venga recuperato
- [x] Rapporto di qualità dei dati
- [x] L'elenco dell'universo azionario a tre date passate non contiene ETF
## Fase 3 — Conti, ordini, contabilità
@@ -111,22 +111,22 @@ Ordini sicuri e ogni euro tracciato.
**Lavori**
- [ ] [#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
- [ ] [#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
- [ ] [#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`
- [ ] [#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] [#26](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/26) Conti e ordini nell'interfaccia BrokerAdapter e simulatore interno (PaperBroker)
- [x] [#27](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/27) OMS: macchina a stati, identificativi deterministici, limite che insegue, ritmo degli invii
- [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
- [x] [#29](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/29) Ambienti, capitale affidato e contabilità: registro, lotti, patrimonio, rendimento corretto
- [x] [#30](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/30) Riconciliazione con i conti e modalità prudente
- [x] [#31](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/31) Adapter Alpaca (paper) e OKX (demo) e batteria di conformità `live_demo`
- [x] [#32](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/32) Schermata Conti e posizioni; conti in Impostazioni e nel primo avvio
- [x] [#33](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/33) Chiusura della fase, revisione indipendente e tag `fase-3`
**Criteri di accettazione**
- [ ] I test di proprietà contabili passano
- [ ] 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)
- [ ] I test con guasti di questa parte passano
- [ ] Un test dimostra che gli adapter rifiutano un ambiente reale senza il consenso della configurazione d'avvio, in Docker e su desktop
- [ ] La schermata Conti e posizioni corrisponde al mockup
- [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) — **simulatore e risposte d'esempio fatti** (`PaperBrokerConformance`, `AlpacaDocConformance`, `OkxDocConformance`); **conti di prova in attesa dell'utente** (`AlpacaPaperConformance`, `OkxDemoConformance`)
- [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`)
- [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`)
- [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
@@ -136,17 +136,17 @@ Un motore di prova onesto, riproducibile e protetto dall'auto-inganno.
**Lavori**
- [ ] [#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
- [ ] [#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] [#34](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/34) Motore di backtest a eventi, modelli di costo e metriche
- [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
- [x] [#36](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/36) Rapporto di backtest e schermata Laboratorio
- [x] [#37](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/37) Chiusura della fase, revisione indipendente e tag `fase-4`
**Criteri di accettazione**
- [ ] Una strategia giocattolo con risultato noto dà esattamente il risultato atteso
- [ ] Il test anti-sguardo-avanti esiste e fallisce su una strategia volutamente scorretta
- [ ] DSR e PBO riproducono i casi noti di 12.2
- [ ] Il rapporto si apre dall'interfaccia
- [x] Una strategia giocattolo con risultato noto dà esattamente il risultato atteso (`AToyStrategyGivesExactlyTheResultComputedByHand`, `TheMetricsOfTheToyRunAreThoseComputedByHand`: patrimonio, commissioni ed esecuzioni calcolati a mano, al centesimo)
- [x] Il test anti-sguardo-avanti esiste e fallisce su una strategia volutamente scorretta (`TheLookAheadTestCatchesAStrategyThatReadsTomorrow`)
- [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)
- [x] Il rapporto si apre dall'interfaccia (`TheReportOpensFromTheLaboratory`: test pianificato dal modulo, eseguito, rapporto e confronto aperti)
## Fase 5 — Strategie, portafoglio, rischio
@@ -156,25 +156,25 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare.
**Lavori**
- [ ] [#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`
- [ ] [#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
- [ ] [#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
- [ ] [#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
- [ ] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
- [x] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
- [x] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum`
- [x] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev`
- [x] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento
- [x] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza
- [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
- [x] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
- [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
- [x] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
**Criteri di accettazione**
- [ ] Ogni regola di 9.1 e 9.2 ha il suo test
- [ ] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale
- [ ] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero
- [ ] 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
- [ ] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione
- [ ] I test anti-sguardo-avanti passano
- [ ] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup
- [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à)
- [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`)
- [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`)
- [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`
- [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)
- [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`)
- [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
@@ -184,25 +184,25 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta.
**Lavori**
- [ ] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione
- [ ] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri
- [ ] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6)
- [ ] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot"
- [ ] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema
- [ ] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita
- [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale
- [x] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione
- [x] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri
- [x] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6)
- [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot"
- [x] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema
- [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita
- [x] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale
- [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6`
**Criteri di accettazione**
- [ ] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi
- [ ] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati
- [ ] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker
- [ ] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono
- [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca)
- [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px)
- [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale
- [ ] I comandi Telegram funzionano (o, senza token, superano i test con un finto server)
- [x] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi (`TheLiveEngineMakesTheSameTradesAsTheBacktest` su 40 giorni di `crypto_trend`, `TheStockSideMakesTheSameTradesAsTheBacktest` su 6 settimane di `equity_meanrev`)
- [x] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati (`TenDaysWithFaultsEndReconciledWithoutDuplicateOrders`: 14 giorni con rete giù, risposta persa, ripartenza con un ordine a metà e database irraggiungibile, su SQLite e PostgreSQL)
- [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm <immagine> drill` in `tasks ci` e nella CI: 7 controlli su 7)
- [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`)
- [x] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) — partita nel container `anubis-prova`, ripartita da zero il 12/11/2026 alle 21:02 dopo uno spegnimento improvviso del PC; il rapporto si verifica in Fase 7 (#55)
- [x] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) (`TheDemoPanoramicaShowsAccountsPositionsAndLimits`; fotografie di `tasks screenshots`, confronto nella prova di #51)
- [x] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale (`TheDiaryFiltersAndSearches`; a 390 px `scrollWidth` uguale alla larghezza su `/`, `/diario` e `/diario?cerca=…`)
- [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests`
## Fase 7 — Notizie
@@ -212,7 +212,8 @@ Le notizie usate per evitare guai, mai per comprare.
**Lavori**
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata
- [ ] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013)
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013)
- [ ] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
- [ ] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
- [ ] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
@@ -222,7 +223,7 @@ Le notizie usate per evitare guai, mai per comprare.
**Criteri di accettazione**
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013)
- [ ] Su un archivio di notizie registrate la deduplica e il collegamento superano i test
- [ ] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (test dedicato)
- [ ] Senza chiave del modello linguistico tutto funziona
+89 -8
View File
@@ -1,10 +1,10 @@
# Stato del progetto
Aggiornato: 2026-11-10
Aggiornato: 2026-11-15
## Fase corrente
**Fase 0 — Preparazione: completata.** La prossima è la Fase 1 (Fondamenta), da iniziare con il via dell'utente.
**Fase 7 — Notizie: in corso.** La Fase 6 è completata. La sua prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
## Fatto
@@ -34,6 +34,67 @@ Aggiornato: 2026-11-10
- `/health`.
- 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:`.
- **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. Le sezioni "Migliorie in osservazione" e "Stime di costo da confermare" aspettano le Fasi 9 e 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, in corso** (ADR 0013):
- Raccolta dei dati per l'analisi (#95). Ogni 5 minuti, e a ogni avvio, il bot scrive una fotografia del processo in `diagnostic_samples`: memoria, GC, thread, handle, CPU, eccezioni, dimensione del database, avvisi ed errori dei registri, chiamate HTTP in uscita per destinazione con le durate. Ogni esecuzione di ogni lavoro va in `job_runs`. Si tiene tutto per 30 giorni.
- Il rapporto da incollare, in Markdown fino a 60 KB e senza segreti, si ottiene in tre modi: dal pulsante «Scarica i dati per l'analisi» in Diario e sistema, da `/api/diagnostica.md` e da `anubis diagnostics`.
- Release di prova per Windows con `tasks release-win`: uno zip con il server, `Avvia Anubis.cmd`, `Prepara i dati da incollare.cmd` e un `LEGGIMI.txt`.
- Raccolta delle notizie (#56, ADR 0014, branch `fase-7`). Il lavoro "notizie" legge ogni 2 minuti le 14 fonti di SPEC 4.4. Le richieste sono condizionate e una fonte che sbaglia aspetta sempre di più, fino a un'ora. Poi:
- i feed si leggono senza DTD né entità;
- gli articoli doppi si tolgono per indirizzo e le riprese dello stesso fatto si raggruppano in una storia, contando le fonti indipendenti;
- ogni storia si collega a strumenti, classi o mercato: simboli, ticker, nomi delle società e delle monete, temi.
- Primo giudizio locale (#57): casi gravi trovati con parole chiave in inglese e in italiano, tono in cinque gradi, importanza da 1 a 4. Ogni articolo e ogni storia lo conservano.
- Classificatore ONNX (#57, ADR 0014 punto 8): il modello Xenova quantizzato, con revisione e hash fissati, scaricato dal bot nella cartella `models` al primo giro delle notizie. Il tokenizzatore sta nella DLL e dà gli stessi identificativi dell'originale. 23–24 ms per titolo su un thread. Senza il modello giudicano le sole parole chiave.
## In corso
@@ -41,13 +102,32 @@ Nulla.
## 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. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56) e primo giudizio con il classificatore (#57) sono fatti. Restano:
- l'analista facoltativo (#58);
- lo stato per strumento (#59);
- la schermata (#60).
3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
## Da sapere
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
- La prova nel container `anubis-prova` è chiusa (ADR 0013). I compiti programmati che la sorvegliavano sono spenti; il container si può fermare con `docker stop anubis-prova`.
- La modalità dimostrativa mostra le schermate costruite fin qui. Notizie e apprendimento appaiono solo con i dati dell'appendice F: fuori dalla demo arrivano con le Fasi 7 e 8. Nella demo il motore di trading e Telegram sono spenti.
- In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo.
- La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4).
- Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata.
- Il capitale affidato si decide in euro in Impostazioni → Conti e chiavi. Finché non c'è, le strategie osservano soltanto.
- `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`.
- 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).
- 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).
- 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.
- 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 +135,13 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc
| Cosa | Da quando serve | Senza |
|---|---|---|
| Via libera per la Fase 1 | Subito | Non si parte |
| Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa |
| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa |
| Far girare la release `v0.7.0` e incollare il rapporto in chat | Ora, per il tempo che vuoi | La prova di durata (#55) resta aperta |
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa |
| Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa |
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
| Chiavi FRED e Finnhub (facoltative, gratuite) | Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
| Token del bot Telegram e chat autorizzata (facoltativi), da Impostazioni → Telegram | Fase 6 | Nessun avviso sul telefono; comandi provati con un finto server |
| Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme |
| Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
| Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale |
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
| Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa |
+24
View File
@@ -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à.
## 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
- **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 -1
View File
@@ -1,6 +1,6 @@
# 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
+108
View File
@@ -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.
+71
View File
@@ -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.
+83
View File
@@ -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.
+68
View File
@@ -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.
+90
View File
@@ -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.
+148
View File
@@ -0,0 +1,148 @@
# 0012 — Scelte della Fase 6: motore dal vivo in simulazione
Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 5.5, 5.6, 7.4, 7.5, 9.3, 9.4, 13, 14) e gli ADR 0009–0011, senza aggiungere componenti esterni
## Contesto
La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il recupero dopo un'assenza, il processo di guardia, il diario con le frasi dell'appendice B, Telegram con il segnale di vita, le schermate Panoramica e Diario e sistema, e la prova di durata in tempo reale. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
## Decisione
**1. Il motore dal vivo decide con la stessa chiamata del backtest.**
- Ogni decisione passa da `DecideOnce`, la stessa funzione che usa il motore di backtest, così prova e simulazione non possono divergere. Il test di parità lo controlla su 40 giorni di `crypto_trend` e su 6 settimane di `equity_meanrev`, con correttivi e rischio attivi.
- Gli orari sono quelli di 5.5:
- chiusura crypto alle 00:05 UTC;
- segnali azionari 20 minuti dopo la chiusura di Wall Street;
- uscite di `equity_meanrev` 5 minuti prima della chiusura;
- ordini azionari e stop del giorno all'apertura.
- Una strategia gira con i parametri scritti nel suo file dell'esito (`parameters`), cioè quelli che si sono qualificati, non con quelli predefiniti.
- Il motore parte dal pianificatore solo dopo che i conti sono stati riconciliati.
**2. Ogni decisione si prende una volta sola, anche attraverso le ripartenze.**
- La decisione ha una chiave (`run_key`: strategia e chiusura su cui decide). Questa chiave viene scritta nella stessa transazione delle righe di decisione, degli ordini pianificati e delle righe del diario: o c'è tutto o non c'è niente.
- L'id di ogni ordine pianificato è l'id della decisione dell'intenzione, e da lì viene la chiave dell'ordine. Una ripartenza che trova l'esecuzione già presente non la manda una seconda volta.
- Gli ordini azionari decisi dopo la chiusura aspettano l'apertura nella tabella `planned_orders`. Ognuno ha una scadenza e un prezzo di riferimento.
- La prova accelerata copre 14 giorni con un guasto diverso nei giorni indicati: rete giù, una risposta persa, una ripartenza con un ordine a metà e il database irraggiungibile. Su SQLite e PostgreSQL termina riconciliata e senza ordini doppi.
**3. Il recupero dopo un'assenza (5.6).**
- L'assenza si misura all'avvio dall'ultimo lavoro finito (`jobs.last_finished_at`). Sotto i 5 minuti è una ripartenza, non un'assenza.
- Ogni assenza va nel diario. Una più lunga di un giorno resta in cima alla Panoramica finché l'utente non l'ha vista.
- Ogni lavoro dichiara cosa fare con le esecuzioni perse:
- salvataggio, cambi, calendario di borsa e pulizia girano una volta alla ripartenza, comunque in ritardo;
- un lavoro con una scadenza si salta dopo quella scadenza, e il diario lo dice.
- Le azioni societarie si leggono prima che la riconciliazione rimetta gli stop.
- Una decisione presa in ritardo per l'assenza va nel diario come recuperata. Un'entrata il cui prezzo si è mosso troppo o che è scaduta si lascia cadere, con il suo motivo.
**4. La guardia è il processo principale e il genitore del motore (9.3, 9.4).**
- In Docker il punto d'ingresso è `Anubis.Guard.dll`, che avvia `Anubis.Server.dll` come processo figlio con gli stessi argomenti.
- I due processi parlano su una pipe locale con nome (`ANUBIS_GUARD_PIPE`), un messaggio JSON per riga:
- il motore manda il battito, i passi dell'avvio, le chiavi dei conti (tenute solo in memoria) e gli stop che decide;
- la guardia manda solo "stop".
- La guardia interviene in tre casi:
- due minuti senza battito;
- un avvio fermo sullo stesso passo per dieci minuti;
- un'uscita del motore senza preavviso.
- Un salto dell'orologio oltre 30 secondi (computer sospeso) non conta come silenzio.
- Quando interviene, la guardia:
1. ferma il motore;
2. annulla i nostri acquisti e le nostre vendite rimasti aperti sui conti di prova;
3. rimette gli stop che le posizioni richiedono, leggendoli dal file di stato che il motore scrive ogni dieci secondi;
4. scrive una nota e avvisa l'utente;
5. fa ripartire il motore.
- La terza ripartenza forzata in un'ora scrive il file STOP.
- Gli stop rimessi dalla guardia saltano 500 numeri di sequenza (`GuardRepair.SequenceGap`), così il loro id non si scontra mai con uno che il motore stava per mandare.
- Alla ripartenza il motore, prima di riconciliare:
- adotta gli stop della guardia;
- annulla gli ordini che aveva lasciato aperti (motivo `restart`);
- pianifica di nuovo le uscite già decise, che seguono così le regole di 5.6.
- Lo stop del container (SIGTERM) passa al motore, che chiude in ordine e non viene fatto ripartire. Il compose e il template Unraid concedono 60 secondi; la guardia ne aspetta 55.
- **I conti reali per ora sono fuori dalla guardia.** La guardia apre solo conti di prova. Avrà i conti reali con la fase dei soldi veri, quando riceverà anche la procedura di avvio di 12.4. Oggi nessuna strategia usa soldi veri.
- La guardia usa il runtime condiviso di ASP.NET (`FrameworkReference`): server e guardia stanno così nella stessa cartella `/app` dell'immagine, con le stesse librerie.
**5. La prova della guardia ha due appigli, solo per la prova.**
- `ANUBIS_FAULT=hang-mid-sale` blocca il ciclo principale subito dopo l'invio di una vendita. La guardia non lo passa mai al motore che fa ripartire.
- `ANUBIS_DRILL_OKX_URL` indirizza il conto OKX della prova a un finto OKX. Funziona solo con indirizzi locali (loopback).
- La prova (`Anubis.Guard drill`) gira con processi veri in una cartella temporanea, anche dentro l'immagine Docker: lo fanno `tasks ci` e la CI. Fa sette controlli:
- la guardia è intervenuta;
- il motore è ripartito;
- la vendita era partita;
- la vendita rimasta a metà è stata annullata;
- lo stop è tornato per l'intera quantità;
- la vendita già decisa è ripartita con un ordine nuovo;
- la nota è nel diario.
**6. Il diario si scrive con frasi fisse.**
- Le frasi nel tono dell'appendice B vengono da modelli (`DiaryText`) riempiti solo con ciò che è successo: esecuzioni con il risultato dell'operazione che chiudono, stop alzati, chiusura crypto, segnali azionari, segnali in osservazione, recupero e assenza.
- Le frasi dei codici motivo stanno nella libreria (`ReasonCatalog`), condivise da motore e schermate. Un test controlla che ogni codice abbia la sua frase.
- I generi del diario sono quelli della schermata: Ordini, Decisioni, Sistema, Notizie, Apprendimento.
**7. Il confronto "senza bot" (7.5).**
- Ogni movimento di capitale viene investito nel suo giorno: 40% in BTC/EUR e 60% in SPY rettificato, convertito con il cambio BCE. Poi non si tocca più.
- Un prelievo vende i due nella proporzione che hanno raggiunto.
- I prezzi sono le chiusure del giorno prima, così un versamento non sembra mai un guadagno.
- Senza lo storico di SPY (niente chiavi Alpaca) la fotografia lascia vuoto il confronto, invece di mostrarne metà.
**8. Telegram (14).**
- Ogni avviso va prima in coda (`notifications`), nella stessa transazione di ciò che racconta, e poi si spedisce. Il passo di spedizione gira ogni dieci secondi e manda al massimo 20 messaggi.
- Ogni messaggio ha uno stato: in attesa, spedito, oppure non riuscito con il suo errore.
- Rete giù e 429 si riprovano dopo 1, 2, 4… fino a 60 minuti, o dopo l'attesa indicata da Telegram se è più lunga; al massimo 8 tentativi.
- Un rifiuto di Telegram è definitivo.
- Un messaggio che non è partito entro un giorno si abbandona con il motivo, invece di arrivare tardi come se fosse una notizia.
- I comandi si leggono con il long polling. Valgono solo:
- dalla chat configurata (le altre si ignorano in silenzio);
- se hanno meno di 5 minuti, così un /pausa di ieri non mette in pausa oggi.
- `/ferma` chiede `/conferma` entro due minuti; qualsiasi altro comando nel frattempo la annulla.
- Ripartire dopo "Ferma tutto", i soldi veri, i limiti e le chiavi restano nell'interfaccia.
- Lavori in programma:
- riepilogo del mattino alle 08:00, recuperabile entro quattro ore;
- stato ogni ora o alle 20:00, solo se l'impostazione `telegram.status` lo chiede.
- Nella modalità dimostrativa Telegram è spento.
- Il passo Telegram del primo avvio resta in Impostazioni → Telegram: la pagina del primo avvio non ha ancora un database dove tenere i segreti. Quella pagina lo dice, e sul desktop raccomanda il segnale di vita.
**9. Il segnale di vita.** Ogni minuto, se c'è un indirizzo, il bot chiama un servizio esterno (per esempio un controllo di Healthchecks.io).
- L'indirizzo viene da `ANUBIS_HEARTBEAT_URL`, oppure dal segreto `HEARTBEAT_URL` impostato da Impostazioni.
- È il servizio esterno ad avvisare se le chiamate smettono: copre il caso in cui bot e guardia sono spenti insieme.
**10. Panoramica e Diario e sistema (13.6).**
- Le prossime mosse vengono dai lavori del pianificatore che sono mosse del bot; i lavori a intervallo (ogni minuto, ogni 5 minuti) non compaiono. Gli eventi del calendario economico tra le mosse ci sono solo nella demo, che usa i valori dell'appendice F.10; fuori dalla demo la riga "Prossima decisione" dice "tra X, alle HH:MM".
- Notizie e Apprendimento, fuori dalla demo, dicono "non ancora attivo" fino alle Fasi 7 e 8.
- Il Diario filtra per genere con semplici collegamenti, senza JavaScript. Il filtro Rischio raccoglie i codici del motore del rischio e quelli di ordini o stop rifiutati, chiavi con prelievo, conto prudente, intervento della guardia e salto dell'orologio. La ricerca ignora maiuscole e accenti, guarda le ultime 5.000 righe e ne mostra al massimo 200. "Mostra i giorni precedenti" aggiunge 7 giorni e compare solo se ci sono righe più vecchie.
- Non esiste ancora una pagina per una singola operazione: "Perché l'ho comprata e venduta" porta a Operazioni filtrata su quel titolo, dove la scheda "perché" si apre.
- Il computer che lo ospita: il processore è la quota di questo processo dall'ultima lettura; la memoria è quella del processo sul limite che .NET vede (nel container, il limite del container); lo spazio è quello del disco della cartella dei dati.
- "Scarica i registri tecnici" (`/api/registri.zip`) chiede l'accesso e mette nello zip solo i file `anubis-*.log` della cartella dei registri, già oscurati quando sono stati scritti.
**11. La prova di durata.**
- `anubis soak` legge i registri del bot su una finestra di tempo e scrive un rapporto, senza cambiare niente. Può girare mentre il bot lavora, in Docker con `docker exec`. I suoi controlli:
- durata coperta;
- bot al lavoro dall'inizio alla fine (vedi il punto 12);
- nessun ordine né decisione doppia;
- nessuna differenza inspiegata e ultima riconciliazione in regola per ogni conto;
- nessuno spegnimento;
- nessun intervento della guardia;
- una decisione `crypto_trend` per ogni chiusura giornaliera.
- La prova gira sull'immagine Docker di questo PC, con un volume suo, senza chiavi: conto crypto sul simulatore interno con prezzi veri di OKX, nessuna parte azionaria.
- `crypto_trend` non ha superato il backtest (ADR 0011, punto 13), quindi resta in osservazione: decide ogni notte, ma non manda ordini. Non la porto in simulazione per far vedere ordini: sarebbe aggirare il suo esito. Gli ordini, le ripartenze e i guasti sono coperti dalla prova accelerata (punto 2) e dalla prova della guardia (punto 5).
**12. Correzioni dopo la revisione indipendente.** Una revisione del codice della fase ha trovato nove difetti; le correzioni scelte sono queste.
- **Un conto parte solo quando è in ordine.** All'avvio ogni conto prima adotta gli stop messi dalla guardia, poi controlla la chiave, si riconcilia, riprende o annulla ciò che era rimasto a metà e allinea gli stop. Solo se tutto riesce il conto è "pronto". Finché non lo è, il motore non decide su di lui e non gli manda ordini pianificati; il ciclo riprova l'avvio ogni minuto. Prima, un broker che non rispondeva all'avvio lasciava il conto lavorare su un registro non riconciliato.
- **Gli stop della guardia si adottano prima di tutto il resto.** La nota della guardia si cancella solo quando ogni stop che ha messo risulta nel registro degli ordini; se l'adozione si interrompe, la nota resta e si riprova.
- **Un turno di conto ha un tempo massimo**: 45 secondi per il giro degli ordini, 60 per un nuovo avvio. Un broker lento non tiene più fermo il segnale di vita per i due minuti dopo i quali la guardia interviene: il turno si interrompe, si scrive nel registro e si riprova al giro dopo. Un motore davvero bloccato resta in silenzio e la guardia lo sente.
- **Il segnale di vita guarda anche il pianificatore.** Se il pianificatore, dove girano le decisioni, tace da 30 minuti (i suoi lavori più lunghi durano pochi minuti), il ciclo degli ordini smette di battere e la guardia interviene.
- **Le uscite alla chiusura di `equity_meanrev` sono ordini pianificati**, scritti nella stessa transazione che prende la chiave della decisione, con scadenza alla chiusura della sessione. Il rilascio li manda subito; una vendita con scadenza parte già aggressiva (limite vicino al prezzo opposto). Prima venivano mandate direttamente: un riavvio a metà poteva perderle o mandarle due volte.
- **La ripresa trova anche l'ordine pianificato non ancora collegato** alla sua esecuzione (riavvio tra l'invio e la scrittura del collegamento), dalla chiave dell'ordine, e lo chiude prima di ripianificare il resto.
- **Una decisione azionaria fatta dopo l'apertura** (per esempio dopo un'assenza) è segnata in ritardo e segue le regole del recupero.
- **I cicli di Telegram non si fermano per un errore inatteso** (database occupato, rete): scrivono nel registro e riprovano.
- **Lo spegnimento lungo si vede in Panoramica** (SPEC 5.6): un avviso in cima dice per quanto il bot è rimasto spento e rimanda al diario, finché l'utente non preme "Ho visto".
- **Una decisione in ritardo aspetta i suoi dati.** Dopo uno spegnimento, al primo battito i dati del giorno prima non sono ancora arrivati: una decisione fatta dopo le 12:00 UTC li chiede e li aspetta fino a 30 minuti, invece di chiudersi subito come "senza dati" e andare persa. Il difetto si è visto all'avvio della prova di durata.
- **Il rapporto della prova di durata non conta più le righe di riconciliazione**, che si scrivono solo quando c'è una differenza. Legge invece:
- quando i lavori in programma hanno cominciato e quando hanno finito l'ultima volta;
- gli spegnimenti, scritti a ogni ripartenza dopo almeno 5 minuti;
- gli interventi della guardia, per un ciclo fermo con il processo vivo;
- lo stato di ogni conto: riconciliato negli ultimi 15 minuti della finestra e in modalità normale.
- Il segnale di vita in `http://` è accettato solo verso indirizzi della rete di casa (10.x, 172.16-31.x, 192.168.x, locali e i loro equivalenti IPv6); il rapporto della prova di durata non conta una chiusura giornaliera avvenuta meno di 30 minuti prima della fine della finestra.
## Conseguenze
- Un riavvio, un crash o un'assenza non producono decisioni né ordini doppi: le chiavi e le transazioni lo garantiscono, e i test lo provano su entrambi i motori.
- I conti reali, quando arriveranno, avranno bisogno che anche la guardia sappia aprirli: è scritto qui per non dimenticarlo.
- Il rapporto della prova di durata si controlla come primo passo della Fase 7.
@@ -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.
+87
View File
@@ -0,0 +1,87 @@
# 0014 — Scelte della Fase 7: raccolta e collegamento delle notizie
Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5 e 10.2 (punti 1–4) per le issue #56 e #57. Usa solo i componenti già ammessi dall'ADR 0004
## Contesto
La Fase 7 porta le notizie dentro Anubis. Il primo pezzo (#56) le raccoglie dalle fonti di SPEC 4.4, le pulisce, raggruppa gli articoli che raccontano lo stesso fatto e li collega agli strumenti, alla classe o al mercato. La specifica dice che cosa fare, ma non fissa alcune soglie e alcune scelte pratiche: sono qui.
## Decisione
**1. Lettura dei feed.**
- RSS 2.0, RSS 1.0 (RDF) e Atom si leggono con il lettore XML di .NET, senza pacchetti.
- Il lettore ignora le DTD e non apre mai file né indirizzi citati dal documento. Le entità dichiarate nel feed non vengono espanse, per cui un feed ostile non legge il disco e non gonfia la memoria. Lo prova il file `hostile.xml` dei test.
- Un documento si legge fino a 5 MB, con un tempo massimo di 30 secondi. Titoli e riassunti perdono i tag HTML e le entità, e il riassunto si ferma a 600 caratteri.
- Le date si leggono nei formati che le fonti usano davvero: RFC 822 con `GMT`, `Z`, `+0100` o i fusi americani con nome, e ISO 8601. Una data senza fuso si legge come UTC. Un articolo senza data prende l'ora in cui è stato visto.
- Il testo delle notizie è un dato, mai un'istruzione (SPEC 10.4): qui si salva e basta.
**2. Cortesia verso le fonti.**
- Il giro delle fonti è il lavoro pianificato "notizie" e gira ogni 2 minuti.
- Ogni fonte riceve una richiesta condizionata (`If-None-Match`, `If-Modified-Since`), e un "non modificato" vale come riuscita. Tra una fonte e l'altra passa un secondo.
- Una fonte che fallisce si riprova dopo 2, 4, 8… minuti, mai oltre un'ora. L'errore resta scritto sulla fonte, e la schermata Notizie (#60) lo mostrerà.
- Le fonti iniziali sono le 14 di SPEC 4.4 che rispondevano il 9 ottobre 2026. Si scrivono solo al primo avvio: poi l'elenco è dell'utente, e una fonte tolta resta tolta.
- Sono affidabili, come dice SPEC 10.2: Federal Reserve, BCE, SEC, CNBC, MarketWatch, CoinDesk, Il Sole 24 Ore, ANSA. Le altre sono aggregatori o testate di settore.
- La SEC chiede ai programmi automatici di indicare un contatto. Anubis manda solo `Anubis/<versione>` e non usa mai l'indirizzo dell'utente senza chiederlo. Se la SEC rifiuta, la fonte va in attesa come le altre. Un campo per il contatto arriverà con le Impostazioni delle notizie (#60).
**3. Doppioni e storie.**
- Lo stesso articolo ha un solo indirizzo canonico. Si tolgono `www.`, il frammento, le barre doppie e finali, e i parametri di tracciamento (`utm_*`, `fbclid`, `gclid`, `mod`, `ref`…). Gli altri parametri si ordinano. Un articolo con un indirizzo già visto è un doppione e non si salva.
- Due titoli raccontano lo stesso fatto quando le loro parole significative si somigliano almeno al 50% (indice di Jaccard). Vale anche quando il titolo più corto, di almeno 4 parole, sta per l'80% dentro l'altro. Due titoli di meno di 3 parole devono essere uguali.
- Una storia raccoglie gli articoli simili usciti entro 48 ore. Gli articoli più vecchi di 3 giorni non entrano: sono storia, non notizie.
- Le fonti indipendenti si contano per dominio registrabile: due feed dello stesso editore valgono uno. La storia è "affidabile" quando almeno una fonte è affidabile. Una storia con una sola fonte non affidabile aspetta una seconda fonte prima di contare (SPEC 10.2, punto 2). Il conto resta nella storia per gli usi successivi (#59).
**4. Collegamento.** Una storia si collega a strumenti, classi o mercato in quest'ordine di forza:
1. i simboli che la fonte stessa indica;
2. i cashtag (`$NVDA`) e i riferimenti di borsa (`(NASDAQ: TSLA)`);
3. le sigle delle crypto scritte in maiuscolo (`BTC`, `ETH`), solo per le monete del catalogo;
4. i nomi delle società, tolti "Inc.", "Corporation", "Common Stock" e simili, scritti con la maiuscola. "apple pie" non è Apple;
5. i nomi delle monete (Bitcoin, Ethereum, Solana…);
6. i temi: banche centrali, inflazione, tassi e dazi vanno al mercato; criptovalute e stablecoin alla classe crypto; Wall Street e i grandi indici alla classe azioni. Un riferimento di borsa come `(NASDAQ: AAPL)` non vale come tema "Nasdaq".
Inoltre:
- Se non si trova niente, vale l'argomento della fonte: il feed della Fed parla di mercato, CoinDesk di crypto.
- Un nome che è anche una parola comune (Target, Block, Gap, Visa…) collega solo con il suo ticker.
- I fondi (ETF) non si collegano per nome.
- Il dizionario dei nomi si ricostruisce dal catalogo degli strumenti al più ogni ora.
**5. Lingua.** La lingua viene dal feed (`<language>`, `xml:lang`). Se manca, una stima semplice distingue l'italiano dall'inglese. Serve al classificatore (#57), che lavora sull'inglese, e all'analista (#58).
**6. Database.**
- Quattro tabelle, uguali sui due motori (migrazione `0008_news.sql`): `news_sources`, `news_stories`, `news_items`, `news_links`.
- L'indirizzo canonico è unico.
- Un collegamento è unico per storia, ambito e bersaglio.
**7. Primo giudizio senza modello linguistico (#57).**
- Ogni articolo ha:
- un tono da −1 a +1, dato solo per i titoli in inglese;
- un eventuale caso grave;
- un'importanza da 1 a 4.
- Ogni storia tiene il tono medio, il caso grave e l'importanza più alta dei suoi articoli.
- I casi gravi si trovano con frasi intere in inglese e in italiano, nell'ordine di 10.2: attacco informatico, sospensione, frode, fallimento, indagine, revoca dalla quotazione. "hackathon" non è "hack".
- Le negazioni ("smentisce la frode") contano come il caso. È la scelta prudente: una restrizione in più, mai una in meno.
- L'importanza si assegna così: 4 ai casi gravi, 3 a un tono fino a −0,6, 2 agli articoli collegati a uno strumento, 1 al resto. Il 3 per un evento in calendario arriva con #59; il 5 lo dà solo il modello linguistico (#58).
**8. Classificatore locale (#57).**
- Il modello è `onnx/model_quantized.onnx` di `Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`:
- revisione `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`;
- 82.763.251 byte, SHA-256 `8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec`, lo stesso pubblicato da Hugging Face;
- è la versione quantizzata, quattro volte più piccola di `model.onnx`.
- Il repository Xenova non dichiara una licenza. Vale quella del modello originale, `mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis`: Apache-2.0.
- Il modello non sta nel repository né nello zip. Al primo giro delle notizie, il bot lo scarica in sottofondo nella cartella `models` dei dati, dall'indirizzo con la revisione fissata, e controlla dimensione e hash. Un file che non corrisponde non si usa mai.
- Se il download o l'apertura falliscono, si riprova dopo 6 ore. Intanto le notizie arrivano lo stesso e giudicano le sole parole chiave (SPEC 10.3: tutto funziona senza modello).
- Nella modalità dimostrativa e con i dati di mercato spenti non si scarica niente.
- Il tokenizzatore sta dentro la DLL (`src/Anubis/News/Model/`, hash nel `README.md` della cartella). È il BPE a livello di byte di RoBERTa, letto con `BpeTokenizer` di `Microsoft.ML.Tokenizers` e il pre-tokenizzatore di RoBERTa.
- `CodeGenTokenizer.Create` non va bene: aggiunge identificativi per le sequenze di spazi che RoBERTa non ha, e il modello li rifiuta.
- Nessun token speciale viene riconosciuto nel testo: un titolo che contiene `<s>` o `<mask>` resta testo.
- Il testo si tronca a 128 token: un titolo ci sta sempre.
- La prova che gli identificativi coincidono con l'originale: il test li confronta, su 14 titoli con accenti, simboli e spazi, con quelli di una copia indipendente del codificatore di GPT-2 sugli stessi file. "Hello world" dà il noto `0 31414 232 2`.
- Il modello gira su un solo thread, per non togliere il processore al motore di trading: 23–24 ms per titolo su questo PC.
- È un po' sopra i 10–20 ms di SPEC 4.5, che non dice su quanti thread.
- Con un giro ogni 2 minuti e qualche decina di titoli nuovi l'ora, il costo resta trascurabile.
- Il test sul modello vero gira dove il file è già scaricato (`ANUBIS_TEST_MODEL_DIR`). In CI risulta ignorato: i test non scaricano 83 MB a ogni esecuzione.
- Lo zip per Windows porta in più la libreria nativa di ONNX Runtime per win-x64 (`onnxruntime.dll`, 17 MB) e passa da 3,4 a 10,7 MB. Per questo `Anubis` e `Anubis.Server` dichiarano `win-x64` tra i loro runtime: il file di blocco contiene anche i pacchetti nativi di Windows, e `tasks release-win` non lo modifica più. Che l'immagine Docker carichi la libreria per linux-x64 (SPEC 3, distribuzione Docker) non è ancora provato: si controlla con il primo avvio del classificatore in Docker.
## Conseguenze
- Le notizie si accumulano già nel database con il loro primo giudizio. Analista, stato per strumento e schermata arrivano con le issue #58–#60.
- Le soglie di somiglianza e di età sono costanti nel codice. Se l'uso reale mostra storie unite o divise male, si cambiano con un nuovo ADR e un test che lo mostra.
- I test leggono un archivio sintetico nel formato reale di ogni fonte (`tests/Anubis.Tests/Fixtures/news/`). Non chiamano mai internet.
+286
View File
@@ -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.
+377
View File
@@ -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
]
}
+10
View File
@@ -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": []
}
+10
View File
@@ -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": []
}
+118 -1
View File
@@ -2,8 +2,125 @@
"version": 2,
"dependencies": {
"net10.0-windows7.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
"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": {
"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=="
}
}
}
+2
View File
@@ -4,6 +4,8 @@
<RootNamespace>Anubis.Guard</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- The same shared runtime as the engine: in the image both live in /app (ADR 0012). -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\Anubis\Anubis.csproj" />
</ItemGroup>
</Project>
+49 -3
View File
@@ -1,3 +1,49 @@
// Placeholder: the guard process (SPEC 9.3) arrives in phase 6 (ADR 0003).
await Console.Error.WriteLineAsync("Anubis.Guard non è ancora disponibile: arriva nella Fase 6.").ConfigureAwait(false);
return 2;
using System.Collections;
using System.Runtime.InteropServices;
using Anubis.Core;
using Anubis.Platform;
using Anubis.Supervision;
// The guard (SPEC 9.3, ADR 0012): the main process of the container and the parent of the engine. Its arguments go to
// the engine as they are. "drill" runs the guard drill in a temporary folder instead.
if (args is ["drill", ..])
{
return await GuardDrill.RunAsync(GuardLaunch.Server(), Console.Out, CancellationToken.None).ConfigureAwait(false);
}
var environment = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var paths = new GuardPaths(DataRoot(args, environment));
var logger = new LineLogger(Console.Out.WriteLine);
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
var clock = SystemClock.Instance;
var guardian = new Guardian(paths, clock, new GuardOptions(),
start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start),
(account, keys) => GuardBrokers.Create(http, clock, account, keys),
(text, keys, ct) => GuardBrokers.AlertAsync(http, logger, keys, text, ct),
logger);
// The stop of the container (SIGTERM) or Ctrl+C: passed on to the engine, which closes in order and is not restarted.
using var shutdown = new CancellationTokenSource();
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop);
using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop);
return await guardian.RunAsync(shutdown.Token).ConfigureAwait(false);
void Stop(PosixSignalContext context)
{
context.Cancel = true;
shutdown.Cancel();
}
// The engine's data folder: --data-dir when given, /data in Docker, the user's folder on desktop (SPEC 15.2, 15.6).
static string DataRoot(string[] args, Dictionary<string, string?> environment)
{
var index = Array.IndexOf(args, "--data-dir");
if (index >= 0 && index + 1 < args.Length)
{
return Path.GetFullPath(args[index + 1]);
}
var platform = Array.IndexOf(args, "--platform") is var p and >= 0 && p + 1 < args.Length ? args[p + 1] : environment.GetValueOrDefault("ANUBIS_PLATFORM");
return platform == "docker" ? "/data" : DataDirectory.ForCurrentUser().Root;
}
+102 -1
View File
@@ -2,8 +2,109 @@
"version": 2,
"dependencies": {
"net10.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
"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": {
"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=="
}
}
}
+279
View File
@@ -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(' ')];
}
}
+11
View File
@@ -2,6 +2,11 @@
<PropertyGroup>
<RootNamespace>Anubis.Server</RootNamespace>
<InvariantGlobalization>false</InvariantGlobalization>
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Anubis\Anubis.csproj" />
@@ -9,4 +14,10 @@
<ItemGroup>
<InternalsVisibleTo Include="Anubis.Tests" />
</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>
+741
View File
@@ -0,0 +1,741 @@
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);
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger,
Guard is null ? null : GuardDrill.DrillOkx(environment))
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct),
Path.Combine(Config.Data.Root, "STOP"))
{
Guard = Guard,
GuardFiles = Guard is null ? null : new GuardPaths(Config.Data.Root),
// The drill's fault is honored only under a guard, which never passes it to an engine it restarts.
Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable),
// The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take
// minutes), and the guard must hear it (SPEC 9.3).
OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence,
}
: null;
if (_trading is not null)
{
// 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 (_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 void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
{
// 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) };
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
{
scheduler.Add(job, 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.
+739
View File
@@ -0,0 +1,739 @@
/* 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; }
@media (max-width: 1180px) {
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.overview-row-wide, .journal-columns { grid-template-columns: minmax(0, 1fr); }
}
/* ---- Service pages ---- */
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
.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); }
}
+128
View File
@@ -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);
})();
+10
View File
@@ -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.
}
})();
+142
View File
@@ -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; }
}
+28
View File
@@ -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;
}
}
+16
View File
@@ -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,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);
}
}
+107
View File
@@ -0,0 +1,107 @@
@* 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 "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>
+49
View File
@@ -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();
}
+39
View File
@@ -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,5 @@
@page "/apprendimento"
<PageTitle>Apprendimento · Anubis</PageTitle>
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
@@ -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,603 @@
@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.",
_ => "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="#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&amp;days=30">Rapporto sulla qualità dei dati degli ultimi 30 giorni</a></p>
<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#dati" />
<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="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 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 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.",
_ => PasswordMessages.For(Errore),
};
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,239 @@
@inherits LoadedComponent
@page "/laboratorio"
@inject AnubisHost Host
@inject ShellData Shell
@inject IClock Clock
@using Anubis.Backtest
@using Anubis.Data
@using Anubis.Strategies
<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>
<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. Arrivano con la Fase 8.</p>
</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 = [];
[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);
_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,
"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 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,5 @@
@page "/notizie"
<PageTitle>Notizie e mercato · Anubis</PageTitle>
<Pending Title="Nessuna notizia letta finora.">La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva.</Pending>
@@ -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,492 @@
@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 non è ancora attiva. Quando lo sarà, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.</p>
}
else
{
<ul class="news-list">
@foreach (var n in p.News)
{
<li>
<span class="note">@n.When, @n.About</span>
<strong>@n.Title</strong>
<span class="@(n.Active ? "attention" : "muted")">@if (n.Active) {<Icon Name="alert" Size="16" />}@n.Effect</span>
</li>
}
</ul>
}
</section>
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
@if (p.Learning is not { } m)
{
<p class="note">L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.</p>
}
else
{
<p><strong>Il modello osserva e impara, ma non decide ancora.</strong></p>
<div class="limit">
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
</div>
<dl class="tile-facts">
<dt>Previsioni azzeccate</dt><dd>@m.Precision% su dati mai visti</dd>
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
</dl>
}
</section>
<section class="plain tile" aria-labelledby="sistema-sintesi">
<div class="panel-head"><h2 id="sistema-sintesi">Sistema</h2><a href="/diario">Dettaglio</a></div>
<ul class="system-tiles">
@foreach (var part in p.System.Tiles)
{
<li class="@PartClass(part.State)"><Icon Name="@PartIcon(part.State)" Size="16" /><span>@part.Name</span><span class="muted">@part.Detail</span></li>
}
</ul>
</section>
</div>
@code {
private Overview _overview = null!;
private PanoramaView _panorama = null!;
private string _currency = "EUR";
private string _period = "avvio";
private int? _runningDays;
private decimal? _worst;
private Anubis.Trading.Absence? _absence;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[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>&nbsp;</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,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
+130
View File
@@ -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());
}
}
+64
View File
@@ -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;
}
}
}
+139
View File
@@ -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;
}
}
}
+243
View File
@@ -0,0 +1,243 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Anubis.Core;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A piece of a diary line: plain text, or an amount coloured as a gain or a loss (always with its sign).</summary>
internal sealed record DiaryPiece(string Text, string? Class = null);
/// <summary>
/// A diary entry as the page draws it (mockup 08): the first sentence as the main line, the rest underneath; a rule
/// the bot changed shows its lead in bold; a sale that closed a trade links to its "why".
/// </summary>
internal sealed record DiaryEntry(DateTimeOffset At, string Kind, string Icon, string? Lead, IReadOnlyList<DiaryPiece> Main, string? Rest, bool Attention, string? Trade);
internal sealed record DiaryDay(DateOnly Day, string Heading, IReadOnlyList<DiaryEntry> Entries);
/// <summary>
/// The diary of "Diario e sistema" (SPEC 13.6): in order of time, grouped by local day, with filters by kind and a
/// search. Static pages: the filters and "Mostra i giorni precedenti" are links with query values.
/// </summary>
internal sealed partial record DiaryView(IReadOnlyList<DiaryDay> Days, string Filter, string? Search, int Range, bool HasOlder, bool Truncated)
{
/// <summary>The risk kind of the filters: not a kind of its own in the journal, but the codes of the risk engine and its relatives.</summary>
public const string RiskKind = "Rischio";
public const int DefaultRange = 2;
public const int MaxSearchResults = 200;
/// <summary>The filter chips, in the order of the mockup: query value, label, kind.</summary>
public static readonly IReadOnlyList<(string Key, string Label, string? Kind)> Filters =
[
("tutto", "Tutto", null),
("decisioni", "Decisioni", DiaryKinds.Decisions),
("ordini", "Ordini", DiaryKinds.Orders),
("notizie", "Notizie", DiaryKinds.News),
("rischio", "Rischio", RiskKind),
("apprendimento", "Apprendimento", DiaryKinds.Learning),
("sistema", "Sistema", DiaryKinds.System),
];
/// <summary>Journal codes that speak of risk without passing through risk_events: refused orders, keys, prudent accounts, the guard.</summary>
private static readonly string[] _riskCodes = ["order_rejected", "stop_rejected", "key_can_withdraw", "account_prudent", "guard_intervention", "clock_gap", "sell_not_filled"];
private const string RiskCondition = "(code IN (SELECT kind FROM risk_events) OR code IN ('order_rejected', 'stop_rejected', 'key_can_withdraw', 'account_prudent', 'guard_intervention', 'clock_gap', 'sell_not_filled'))";
private static readonly string[] _daysLong = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
private static readonly string[] _monthsLong = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
private static readonly CompareInfo _compare = CultureInfo.GetCultureInfo("it-IT").CompareInfo;
public bool IsEmpty => Days.Count == 0;
/// <summary>The query string of this view with one value changed, for the links of the page.</summary>
public string Link(string? filter = null, int? range = null)
{
var parts = new List<string>();
var f = filter ?? Filter;
if (f != "tutto")
{
parts.Add("tipo=" + Uri.EscapeDataString(f));
}
if (!string.IsNullOrEmpty(Search))
{
parts.Add("cerca=" + Uri.EscapeDataString(Search));
}
var r = range ?? Range;
if (r != DefaultRange)
{
parts.Add("giorni=" + r.ToString(CultureInfo.InvariantCulture));
}
return "/diario" + (parts.Count == 0 ? "" : "?" + string.Join('&', parts));
}
public static async Task<DiaryView> LoadAsync(Database db, string? filter, string? search, string? days, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var key = Filters.Any(f => f.Key == filter) ? filter! : "tutto";
var kind = Filters.First(f => f.Key == key).Kind;
var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
if (text is { Length: > 100 })
{
text = text[..100];
}
var range = int.TryParse(days, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, 3650) : DefaultRange;
var (where, parameters) = kind switch
{
null => ("1 = 1", Array.Empty<(string, object?)>()),
RiskKind => (RiskCondition, []),
_ => ("kind = @k AND NOT " + RiskCondition, new (string, object?)[] { ("k", kind) }),
};
var (rows, older, truncated) = await db.ReadAsync(async s =>
{
const string columns = "SELECT occurred_at, kind, code, message FROM journal WHERE ";
if (text is not null)
{
// The search reads the whole diary, newest first; the comparison is done here, the same on both engines,
// ignoring case and accents.
var all = await s.QueryAsync(columns + where + " ORDER BY occurred_at DESC LIMIT 5000", Row, parameters).ConfigureAwait(false);
var found = all.Where(r => _compare.IndexOf(r.Message, text, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0).ToList();
return (found.Take(MaxSearchResults).ToList(), false, found.Count > MaxSearchResults);
}
// The range ends on the newest day that has an entry, so a quiet bot never shows an empty page.
var latest = await s.FirstOrDefaultAsync("SELECT MAX(occurred_at) AS at FROM journal WHERE " + where, r => r.MomentOrNull("at"), parameters).ConfigureAwait(false);
if (latest is null)
{
return ([], false, false);
}
var today = LocalDay(now, zone);
var anchor = LocalDay(latest.Value, zone) is var last && last < today ? last : today;
var from = Start(anchor.AddDays(1 - range), zone);
var withFrom = parameters.Append(("from", from)).ToArray();
var list = await s.QueryAsync(columns + where + " AND occurred_at >= @from ORDER BY occurred_at DESC LIMIT 2000", Row, withFrom).ConfigureAwait(false);
var before = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE " + where + " AND occurred_at < @from", withFrom).ConfigureAwait(false);
return (list.ToList(), before > 0, list.Count >= 2000);
}, cancellationToken).ConfigureAwait(false);
var risky = rows.Count == 0 ? new HashSet<string>(StringComparer.Ordinal)
: (await db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT kind FROM risk_events", r => r.Text("kind")), cancellationToken).ConfigureAwait(false))
.Concat(_riskCodes).ToHashSet(StringComparer.Ordinal);
var day0 = LocalDay(now, zone);
var grouped = rows
.GroupBy(r => LocalDay(r.At, zone))
.Select(g => new DiaryDay(g.Key, Heading(g.Key, day0), [.. g.Select(r => Entry(r.At, risky.Contains(r.Code) ? RiskKind : r.Kind, r.Code, r.Message))]))
.ToList();
return new DiaryView(grouped, key, text, range, older, truncated);
static (DateTimeOffset At, string Kind, string Code, string Message) Row(DbRow r) => (r.Moment("occurred_at"), r.Text("kind"), r.Text("code"), r.Text("message"));
}
/// <summary>"Oggi, venerdì 9 ottobre", "Ieri, giovedì 8 ottobre", "Mercoledì 7 ottobre"; the year when it is not this one.</summary>
public static string Heading(DateOnly day, DateOnly today)
{
var name = $"{_daysLong[(int)day.DayOfWeek]} {day.Day.ToString(CultureInfo.InvariantCulture)} {_monthsLong[day.Month - 1]}" +
(day.Year == today.Year ? "" : " " + day.Year.ToString(CultureInfo.InvariantCulture));
return day == today ? "Oggi, " + name : day == today.AddDays(-1) ? "Ieri, " + name : char.ToUpperInvariant(name[0]) + name[1..];
}
/// <summary>Splits a diary sentence the way the mockup draws it.</summary>
public static DiaryEntry Entry(DateTimeOffset at, string kind, string code, string message)
{
ArgumentNullException.ThrowIfNull(message);
// The demo's row of appendix F says in words where the link goes; the link is drawn, the words are not.
var text = DemoLink().Replace(message, "").Trim();
string main;
string? rest = null;
string? lead = null;
var reason = text.IndexOf(" Motivo: ", StringComparison.Ordinal);
var attention = reason > 0;
if (attention)
{
// A rule changed by the bot: what it decided, in bold up to the colon, then why.
main = text[..reason];
rest = text[(reason + 1)..];
var colon = main.IndexOf(':', StringComparison.Ordinal);
if (colon > 0)
{
lead = main[..(colon + 1)];
main = main[(colon + 1)..];
}
}
else if (text.Length > 80 && SentenceEnd().Match(text) is { Success: true } end)
{
// Long entries: the first sentence on the main line, the explanation underneath. Short ones stay on one line.
main = text[..end.Index];
rest = text[(end.Index + end.Length)..];
}
else
{
main = text;
}
string? trade = null;
if (kind == DiaryKinds.Orders && Sale().Match(text) is { Success: true } sale)
{
// A sale that closed a trade: its "why" is on the Operazioni page, found by the instrument.
trade = sale.Groups["symbol"].Value.Split('/')[0];
}
return new DiaryEntry(at, kind, IconOf(kind), lead, Pieces(main), rest, attention, trade);
}
private static List<DiaryPiece> Pieces(string text)
{
var pieces = new List<DiaryPiece>();
var position = 0;
foreach (Match m in SignedAmount().Matches(text))
{
if (m.Index > position)
{
pieces.Add(new DiaryPiece(text[position..m.Index]));
}
pieces.Add(new DiaryPiece(m.Value, m.Value[0] == '+' ? "gain" : "loss"));
position = m.Index + m.Length;
}
if (position < text.Length)
{
pieces.Add(new DiaryPiece(text[position..]));
}
return pieces;
}
private static string IconOf(string kind) => kind switch
{
DiaryKinds.Orders => "arrows",
DiaryKinds.Decisions => "layers",
DiaryKinds.News => "news",
DiaryKinds.Learning => "network",
RiskKind => "shield",
_ => "sliders",
};
private static DateOnly LocalDay(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime);
private static DateTimeOffset Start(DateOnly day, TimeZoneInfo zone)
{
var local = day.ToDateTime(TimeOnly.MinValue);
return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime();
}
[GeneratedRegex(@"\s*\(con il collegamento ""[^""]*""\)")]
private static partial Regex DemoLink();
[GeneratedRegex(@"(?<=[.!?])\s+(?=[A-ZÀ-Ý0-9])")]
private static partial Regex SentenceEnd();
[GeneratedRegex(@"^Vendut[oaie] \S+ (?<symbol>\S+) a [^:]+: [+−]")]
private static partial Regex Sale();
[GeneratedRegex(@"(?<![\w])[+−]\d[\d.,]*\s?[€$]")]
private static partial Regex SignedAmount();
}
+468
View File
@@ -0,0 +1,468 @@
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.");
}
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)));
}
+993
View File
@@ -0,0 +1,993 @@
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>
/// Form actions of the pages: plain HTML forms with the CSRF field, answered with a redirect (post, redirect, get).
/// Errors travel back as a short code in the address, never with the values typed in.
/// </summary>
internal static partial class Forms
{
public static void Map(WebApplication app)
{
var open = app.MapGroup("/azioni").AllowAnonymous();
open.MapPost("/accesso", SignInAsync);
open.MapPost("/primo-avvio/prova", TestDatabaseAsync);
open.MapPost("/primo-avvio", FirstRunAsync);
open.MapPost("/servizio/{choice}", ServiceChoiceAsync);
var signed = app.MapGroup("/azioni").RequireAuthorization();
signed.MapPost("/esci", SignOutAsync);
signed.MapPost("/primo-accesso", (IFormCollection form, AnubisHost host, StartupConfig config, HttpContext context, CancellationToken ct) =>
ChangePasswordAsync(form, host, context, config.AdminPassword, "/primo-accesso", "/", ct));
signed.MapPost("/password", (IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) =>
ChangePasswordAsync(form, host, context, null, "/impostazioni", "/impostazioni", ct));
signed.MapPost("/due-fattori/attiva", EnableSecondFactorAsync);
signed.MapPost("/due-fattori/disattiva", DisableSecondFactorAsync);
signed.MapPost("/impostazioni/{key}", SetSettingAsync);
signed.MapPost("/bot/{command}", BotAsync);
signed.MapPost("/salvataggio", BackupAsync);
signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync);
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/telegram", SaveTelegramAsync);
signed.MapPost("/telegram/prova", TestTelegramAsync);
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
}
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
private static async Task<IResult> AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct)
{
if (!host.IsDemo && host.Services is { } services)
{
await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false);
}
return Results.Redirect("/");
}
private static string Back(IFormCollection form, string fallback)
{
var back = form["ritorno"].ToString();
return IsLocalPath(back) ? back : fallback;
}
/// <summary>
/// Only paths of this site: "/x" yes; "//other.site", "https://..." no; no backslash and no control characters,
/// which browsers drop or turn into "/" while reading an address ("/\t/other.site" becomes "//other.site").
/// </summary>
internal static bool IsLocalPath(string path) =>
path.StartsWith('/') && !path.StartsWith("//", StringComparison.Ordinal) && !path.Any(c => char.IsControl(c) || c == '\\');
private static string With(string path, string key, string value)
{
var hash = path.IndexOf('#', StringComparison.Ordinal);
var anchor = hash >= 0 ? path[hash..] : "";
var bare = hash >= 0 ? path[..hash] : path;
return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor;
}
private static async Task<IResult> SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct)
{
var services = host.Services;
if (services is null)
{
return Results.Redirect("/");
}
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
var back = Back(form, "/");
var wait = limiter.Begin(address);
if (wait > TimeSpan.Zero)
{
var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
var code = form["codice"].ToString();
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
.ConfigureAwait(false);
switch (result)
{
case LoginResult.Ok:
limiter.Succeeded(address);
SessionAuthentication.WriteCookie(context, token!);
return Results.Redirect(back);
case LoginResult.SecondFactorNeeded:
limiter.Forgive(address);
return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back));
case LoginResult.WrongSecondFactor:
return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back));
default:
return Results.Redirect(With(With("/accesso", "errore", "password"), "ritorno", back));
}
}
private static async Task<IResult> SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services)
{
await services.Access.SignOutAsync(token, ct).ConfigureAwait(false);
}
SessionAuthentication.ClearCookie(context);
return Results.Redirect("/accesso");
}
private static async Task<IResult> ChangePasswordAsync(IFormCollection form, AnubisHost host, HttpContext context, string? initial, string page, string done, CancellationToken ct)
{
if (host.IsDemo)
{
return Results.Redirect(With(page, "errore", "demo"));
}
var replacement = form["nuova"].ToString();
if (replacement != form["conferma"].ToString())
{
return Results.Redirect(With(page, "errore", "diverse"));
}
if (Passwords.Problem(replacement, initial) is not null)
{
return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale"));
}
var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct)
.ConfigureAwait(false);
return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale"));
}
private static async Task<IResult> EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct)
{
// The secret shown on the page stays on the server, tied to this session: it never travels in a form or an address.
var session = CurrentUser.Session(context.User);
if (host.IsDemo || drafts.Peek(session) is not { } secret)
{
return Results.Redirect("/impostazioni?errore=segreto#sicurezza");
}
var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false);
if (ok)
{
drafts.Remove(session);
}
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza");
}
private static async Task<IResult> DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false);
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza");
}
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/impostazioni");
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "riunioni"));
}
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
}
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
private static async Task<IResult> ResolveAccountAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
if (choice is not ("allinea" or "escludi"))
{
return Results.Redirect("/conti?errore=scelta");
}
if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager)
{
return Results.Redirect("/conti?errore=motore");
}
var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false);
if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason)
{
return Results.Redirect("/conti?errore=chiave");
}
if (!state.WaitsForUser(clock.UtcNow, trading.Reconciler.Grace))
{
// The choice exists only after the 15 minutes (SPEC 7.4): before, the difference may still explain itself.
return Results.Redirect("/conti?errore=presto");
}
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect("/conti?ok=" + choice);
}
/// <summary>
/// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not
/// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them.
/// </summary>
private static async Task<IResult> SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(back + "?errore=conto#conti");
}
if (host.IsDemo || host.Services is not { Trading: { } trading } services)
{
return Results.Redirect(back + "?errore=motore#conti");
}
var fields = Anubis.Trading.TradingService.KeyFields(broker);
foreach (var (name, _) in fields)
{
if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment)
{
return Results.Redirect(back + "?errore=ambiente#conti");
}
}
var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList();
if (values.Any(v => v.Length == 0 || v.Length > 512))
{
return Results.Redirect(back + "?errore=chiavi-vuote#conti");
}
Anubis.Trading.KeyPermissions permissions;
try
{
permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false);
}
catch (Anubis.Trading.BrokerException)
{
return Results.Redirect(back + "?errore=chiavi-rifiutate#conti");
}
if (permissions.CanWithdraw)
{
return Results.Redirect(back + "?errore=prelievo#conti");
}
if (!permissions.CanTrade)
{
return Results.Redirect(back + "?errore=sola-lettura#conti");
}
var who = context.User.Identity?.Name ?? "utente";
for (var i = 0; i < fields.Count; i++)
{
await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false);
}
await host.RestartServicesAsync(ct).ConfigureAwait(false);
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect(back + "?ok=chiavi#conti");
}
/// <summary>
/// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
/// </summary>
private static async Task<IResult> SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment
|| (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment)
{
return Results.Redirect(back + "?errore=telegram-ambiente#telegram");
}
var token = form["token"].ToString().Trim();
var chat = form["chat"].ToString().Trim();
if (token.Length is 0 or > 200 || chat.Length is 0 or > 40)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null)
{
return Results.Redirect(back + "?errore=telegram-rifiutato#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false);
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram#telegram");
}
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
private static async Task<IResult> TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { } telegram }
|| await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings)
{
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
}
return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram");
}
private static async Task<IResult> RemoveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var who = context.User.Identity?.Name ?? "utente";
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false);
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=telegram-tolto#telegram");
}
/// <summary>The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.</summary>
private static async Task<IResult> SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
var address = form["indirizzo"].ToString().Trim();
if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null)
{
return Results.Redirect(back + "?errore=segnale#telegram");
}
var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult<Uri?>(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
if (!await probe.BeatAsync(ct).ConfigureAwait(false))
{
return Results.Redirect(back + "?errore=segnale-fallito#telegram");
}
await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale#telegram");
}
private static async Task<IResult> RemoveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#telegram");
}
await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect(back + "?ok=segnale-tolto#telegram");
}
private static async Task<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=conto#conti");
}
var who = context.User.Identity?.Name ?? "utente";
foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker))
{
await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false);
}
await host.RestartServicesAsync(ct).ConfigureAwait(false);
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect(back + "?ok=chiavi-tolte#conti");
}
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(back + "?errore=conto#conti");
}
if (host.IsDemo || host.Services?.Trading is not { } trading)
{
return Results.Redirect(back + "?errore=motore#conti");
}
if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m)
{
return Results.Redirect(back + "?errore=importo#conti");
}
// More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4).
if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before &&
await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#conti");
}
try
{
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
}
catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal))
{
return Results.Redirect(back + "?errore=cambio#conti");
}
catch (Anubis.Trading.CapitalException)
{
return Results.Redirect(back + "?errore=capitale#conti");
}
return Results.Redirect(back + "?ok=capitale#conti");
}
/// <summary>
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
/// </summary>
private static async Task<IResult> StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy))
{
return Results.Redirect("/strategie?errore=scelta");
}
if (services.Trading?.Stages is not { } stages)
{
return Results.Redirect("/strategie?errore=motore");
}
var by = context.User.Identity?.Name ?? "utente";
try
{
switch (choice)
{
case "simulazione":
var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (stage?.Qualification is not { Passed: true })
{
// A strategy that did not pass its backtest stays in observation (SPEC 12.3).
return Results.Redirect("/strategie?errore=backtest");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
case "osservazione":
var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage))
{
await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=osservazione");
case "reale" when Guid.TryParse(form["conto"].ToString(), out var account):
var code = form["codice"].ToString();
await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(),
string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=reale");
default:
return Results.Redirect("/strategie?errore=scelta");
}
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
var error = ex.Code switch
{
"phrase" => "frase",
"password" => "password",
"requirements" => "requisiti",
"backtest" => "backtest",
"observation" => "osservazione-giorni",
"account" => "conto",
Anubis.Risk.RiskReasons.NoConsent => "consenso",
_ => "scelta",
};
return Results.Redirect("/strategie?errore=" + error);
}
}
/// <summary>
/// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy
/// has real money needs the phrase, the password and the second factor (SPEC 12.4).
/// </summary>
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#rischio");
}
var current = new Dictionary<string, string>(StringComparer.Ordinal);
var next = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
{
current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value;
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
if (typed.Length == 0)
{
next[definition.Key] = current[definition.Key];
continue;
}
if (definition.Check?.Invoke(typed) is not null)
{
return Results.Redirect(back + "?errore=limite#rischio");
}
next[definition.Key] = typed;
}
var limits = Anubis.Risk.RiskSettings.From(k => next[k]);
if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss)
{
return Results.Redirect(back + "?errore=ordine-limiti#rischio");
}
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
{
if (await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
}
}
var by = context.User.Identity?.Name ?? "utente";
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
{
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
}
return Results.Redirect(back + "?ok=limiti#rischio");
}
/// <summary>The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure.</summary>
private static async Task<IResult> SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key)
{
return Results.Redirect(back + "?errore=impostazione#rischio");
}
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio");
}
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
private static async Task<string?> RaiseRefusalAsync(AppServices services, IClock clock, string? broker, IFormCollection form, CancellationToken ct)
{
// Without the trading engine no strategy can hold real money, so the stage book only has to say so.
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, clock, Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
try
{
var code = form["codice"].ToString();
await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false);
return null;
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
return ex.Code switch
{
"phrase" => "frase-rischio",
"demotion" => "retrocessione-rischio",
_ => "password-rischio",
};
}
}
/// <summary>
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.
/// </summary>
private static async Task<IResult> PlanTrialAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
{
var family = Anubis.Strategies.StrategyCatalog.Find(form["strategia"].ToString());
string Back(string code) => "/laboratorio?errore=" + code + (family is null ? "" : "&strategia=" + Uri.EscapeDataString(family.Id)) + "#nuovo";
if (host.IsDemo || host.Services?.Lab is not { } lab)
{
return Results.Redirect(Back("motore"));
}
if (family is null)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Strategy));
}
var source = form["origine"].ToString();
var venue = source == Anubis.Backtest.TrialSources.Research ? Anubis.Data.Venues.Binance : form["mercato"].ToString();
if (source == Anubis.Backtest.TrialSources.Database && venue is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Source));
}
if (ParseDay(form["dal"].ToString()) is not { } from || ParseDay(form["al"].ToString()) is not { } to)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Dates));
}
if (ParseEuro(form["capitale"].ToString()) is not { } capital)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Capital));
}
var grid = new Dictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal);
foreach (var p in family.Parameters)
{
var text = form["griglia_" + p.Name].ToString();
if (string.IsNullOrWhiteSpace(text))
{
continue;
}
if (ParseList(text) is not { } values)
{
return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Grid));
}
grid[p.Name] = values;
}
var symbols = form["strumenti"].ToString()
.Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(x => x.ToUpperInvariant())
.ToList();
try
{
var trial = await lab.PlanAsync(new Anubis.Backtest.TrialRequest(family.Id, source, venue, symbols, from, to, capital, grid), ct).ConfigureAwait(false);
return Results.Redirect("/laboratorio/" + trial.Id.ToString("D"));
}
catch (Anubis.Backtest.TrialRequestException ex)
{
return Results.Redirect(Back(ex.Code));
}
}
private static DateOnly? ParseDay(string text) =>
DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null;
/// <summary>Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point.</summary>
internal static IReadOnlyList<decimal>? ParseList(string text)
{
var result = new List<decimal>();
foreach (var item in (text ?? "").Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!decimal.TryParse(item, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value))
{
return null;
}
result.Add(value);
}
return result.Count is > 0 and <= 20 ? result : null;
}
/// <summary>An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50".</summary>
internal static decimal? ParseEuro(string text)
{
var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal);
if (clean.Contains(',', StringComparison.Ordinal))
{
clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.');
}
else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3)
{
clean = clean.Replace(".", "", StringComparison.Ordinal);
}
return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value)
? Math.Round(value, 2, MidpointRounding.ToZero)
: null;
}
private static async Task<IResult> BackupAsync(IFormCollection form, AnubisHost host, ILogger<AnubisHost> logger, CancellationToken ct)
{
var services = host.Services!;
try
{
await services.Backups.TakeAsync(services.Db, "a-mano", ct).ConfigureAwait(false);
return Results.Redirect("/impostazioni?ok=salvataggio#sistema");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
{
LogBackupFailed(logger, ex);
return Results.Redirect("/impostazioni?errore=salvataggio#sistema");
}
}
// ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ----
private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config)
{
if (form["motore"].ToString() != "postgres")
{
return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile };
}
return new DbSettings
{
Engine = DbEngine.Postgres,
Host = form["host"].ToString().Trim(),
Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432,
Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(),
User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(),
Password = form["dbpassword"].ToString(),
};
}
/// <summary>Opens the database without creating anything and asks it one question.</summary>
private static async Task<string?> TryConnectAsync(DbSettings settings, CancellationToken ct)
{
if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host))
{
return "Manca l'indirizzo del server PostgreSQL.";
}
Redactor.Register(settings.Password);
try
{
await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(8));
await db.PingAsync(timeout.Token).ConfigureAwait(false);
return null;
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
return Redactor.Redact(ex.Message);
}
}
private static bool WizardAllowed(AnubisHost host, HttpContext context) =>
host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context);
private static async Task<IResult> TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (!WizardAllowed(host, context))
{
return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio.");
}
var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false);
return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." });
}
private static async Task<IResult> FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
{
if (!WizardAllowed(host, context))
{
return Results.Redirect("/");
}
var password = form["password"].ToString();
if (password != form["conferma"].ToString())
{
return Results.Redirect("/primo-avvio?errore=diverse");
}
if (Passwords.Problem(password) is not null)
{
return Results.Redirect("/primo-avvio?errore=corta");
}
var config = host.Config;
if (!config.IsComplete)
{
var settings = ReadDatabase(form, config);
if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null)
{
return Results.Redirect("/primo-avvio?errore=database");
}
// config.toml without the database password: that goes to the protected store (SPEC 15.6).
DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false);
}
host.PendingPassword = password;
host.Wake();
try
{
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
LogFirstRunSlow(logger);
return Results.Redirect("/");
}
var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(),
context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false);
if (result == LoginResult.Ok)
{
SessionAuthentication.WriteCookie(context, token!);
}
return Results.Redirect("/");
}
// ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ----
private static async Task<IResult> ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
{
var config = host.Config;
if (config.Platform == PlatformKind.Docker)
{
// The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in.
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
if (limiter.Begin(address) > TimeSpan.Zero)
{
return Results.Redirect("/?errore=attesa");
}
if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword))
{
LogChoiceRefused(logger, choice);
return Results.Redirect("/?errore=password");
}
limiter.Succeeded(address);
}
else if (!CurrentUser.IsLocal(context))
{
return Results.Redirect("/?errore=password");
}
// The startup loop stays still until the choice is done and the installation renewed.
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
var status = host.Status;
var db = host.Database;
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
{
return Results.Redirect("/");
}
var verdict = status.Identity.Verdict;
try
{
switch (choice)
{
case "ripristina" when verdict == IdentityVerdict.EmptyDatabase:
var backup = new Backups(config.Data, clock).List().FirstOrDefault(b => b.Name == form["salvataggio"].ToString());
if (backup is null)
{
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
break;
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
if (folder is null)
{
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
break;
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
Installation.StartOver(config.Data, clock);
break;
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase:
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false);
break;
default:
return Results.Redirect("/?errore=scelta");
}
}
catch (Exception ex) when (IsArchiveProblem(ex))
{
LogChoiceFailed(logger, ex, choice);
return Results.Redirect("/?errore=importazione");
}
LogChoice(logger, choice);
// Reset while the loop is still held: released first, it could start the application again before the reset
// and then lose the services it had just built while showing "ready".
await host.ResetAsync().ConfigureAwait(false);
exclusive.Dispose();
await WaitBrieflyAsync(host).ConfigureAwait(false);
return Results.Redirect("/");
}
/// <summary>What a damaged or unsuitable archive throws: reported on the page, not as a crash.</summary>
internal static bool IsArchiveProblem(Exception ex) =>
ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException or FormatException or OverflowException
or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException;
private static async Task WaitBrieflyAsync(AnubisHost host)
{
try
{
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(10)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
[LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")]
private static partial void LogBackupFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")]
private static partial void LogFirstRunSlow(ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")]
private static partial void LogChoice(ILogger logger, string choice);
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} refused: wrong startup password")]
private static partial void LogChoiceRefused(ILogger logger, string choice);
[LoggerMessage(Level = LogLevel.Error, Message = "Error page choice {Choice} failed")]
private static partial void LogChoiceFailed(ILogger logger, Exception exception, string choice);
}
/// <summary>Second-factor secrets being set up, one per session, kept for 15 minutes.</summary>
internal sealed class SecondFactorDrafts(IClock clock)
{
private static readonly TimeSpan _life = TimeSpan.FromMinutes(15);
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, (byte[] Secret, DateTimeOffset Until)> _drafts = new();
/// <summary>The draft of this session, or a new one.</summary>
public byte[] For(Guid session)
{
var now = clock.UtcNow;
foreach (var expired in _drafts.Where(d => d.Value.Until <= now).Select(d => d.Key).ToList())
{
_drafts.TryRemove(expired, out _);
}
return _drafts.AddOrUpdate(session, _ => (Totp.NewSecret(), now + _life), (_, d) => d.Until > now ? d : (Totp.NewSecret(), now + _life)).Secret;
}
public byte[]? Peek(Guid session) => _drafts.TryGetValue(session, out var d) && d.Until > clock.UtcNow ? d.Secret : null;
public void Remove(Guid session) => _drafts.TryRemove(session, out _);
}
/// <summary>What the error page can offer.</summary>
internal static class ServiceChoices
{
/// <summary>Archives under data/import, one folder each with its index.json.</summary>
public static IReadOnlyList<string> ImportFolders(DataDirectory data) =>
!Directory.Exists(data.Import)
? []
: Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList();
}
+140
View File
@@ -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);
}
}
}
+90
View File
@@ -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",
};
}
+117
View File
@@ -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;
}
+214
View File
@@ -0,0 +1,214 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>The last 30 days of an account: the result net of flows and the daily values in euro for the small line.</summary>
internal sealed record AccountTrend(decimal Month, IReadOnlyList<decimal> Points);
/// <summary>A news item of the "Notizie che contano" tile; <paramref name="Active"/> when its effect is still on.</summary>
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
/// <summary>A strategy at a glance: result, the bar against the best one, its stage in words and its trades.</summary>
internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades);
/// <summary>
/// Everything under the top block of the Panoramica (SPEC 13.6, mockup 01): accounts with their last 30 days, the
/// four main limits, positions, strategies, news, model and system. In demo mode the values of appendix F that
/// exist only as totals come from the aggregates (SPEC 13.1); outside it news and the model are not active yet.
/// </summary>
internal sealed record PanoramaView(
AccountsView Accounts,
IReadOnlyDictionary<Guid, AccountTrend> Trends,
IReadOnlyList<PanoramaLimit> Limits,
bool LimitsKept,
IReadOnlyList<PanoramaStrategy> Strategies,
bool AnyLive,
SystemView System,
IReadOnlyList<NextMove>? DemoMoves,
IReadOnlyList<LastAction>? DemoLast,
string? NextDecision,
IReadOnlyList<PanoramaNews>? News,
PanoramaLearning? Learning,
DateTimeOffset? FractionStops)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
public static async Task<PanoramaView> LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(overview);
var services = host.Services!;
var clock = host.Clock;
var risk = await RiskView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var accounts = await AccountsView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var strategies = await StrategiesView.LoadAsync(services, clock, false, cancellationToken).ConfigureAwait(false);
var system = await SystemView.LoadAsync(host, shell, cancellationToken).ConfigureAwait(false);
var trends = await TrendsAsync(services, accounts, shell.Now, shell.Zone, cancellationToken).ConfigureAwait(false);
// The four limits of the Panoramica, read from the same rows as the Rischio page.
var rows = risk.Rows.ToDictionary(r => r.Key);
var day = rows[RiskSettings.DailyLoss.Key];
var invested = rows[RiskSettings.MaxInvested.Key];
var biggest = rows[RiskSettings.MaxPosition.Key];
var fall = risk.Risk.Measures.Drawdown;
decimal? worst = risk.Drawdown.Count > 0 ? risk.Drawdown.Min(d => d.Drawdown) : null;
var stop = risk.Limits.DrawdownStop;
var limits = new List<PanoramaLimit>
{
new("Perdita di oggi", day.Now, day.Threshold, day.Usage ?? 0m),
new("Calo dal massimo", Format.Percent(fall * 100m, 2), Format.Percent(-stop * 100m, 2), stop <= 0m ? 0m : Math.Clamp(-fall / stop, 0m, 1m),
worst is { } w && stop > 0m ? Math.Clamp(-w / stop, 0m, 1m) : null),
new("Capitale investito", invested.Now, invested.Threshold, invested.Usage ?? 0m),
new("Posizione più grande" + (biggest.Detail is { } symbol ? $" ({symbol.Split('/')[0]})" : ""), biggest.Now, biggest.Threshold, biggest.Usage ?? 0m),
};
var kept = !risk.AnyBlock && risk.Rows.All(r => r.Usage is null or < 1m);
// Strategies: the bar compares each result with the best one; the stage says what is still missing.
var best = strategies.Cards.Select(c => Math.Abs(c.ResultEur)).DefaultIfEmpty(0m).Max();
var cards = strategies.Cards.Select(c => new PanoramaStrategy(c.Name, c.Color, c.ResultEur, best == 0m ? 0m : Math.Abs(c.ResultEur) / best, Stage(c), Trades(c))).ToList();
var anyLive = strategies.Cards.Any(c => StrategyStages.IsLive(c.Stage.Stage));
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
using var aggregates = shell.Aggregates();
if (aggregates is null)
{
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), null, null, fractions);
}
var root = aggregates.RootElement;
var demo = root.GetProperty("panoramica");
var moves = demo.GetProperty("mosse").EnumerateArray().Select(m => new NextMove(m.GetProperty("ora").GetString()!, m.GetProperty("testo").GetString()!,
m.TryGetProperty("dove", out var where) ? where.GetString() : null, m.GetProperty("calendario").GetBoolean())).ToList();
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
var model = root.GetProperty("apprendimento");
var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
c => decimal.Parse(c.GetProperty("trenta_giorni").GetString()!, _it), StringComparer.Ordinal);
var demoTrends = accounts.Accounts.ToDictionary(a => a.Id,
a => new AccountTrend(month.GetValueOrDefault(a.Name, trends.GetValueOrDefault(a.Id)?.Month ?? 0m), trends.GetValueOrDefault(a.Id)?.Points ?? []));
return new PanoramaView(accounts, demoTrends, limits, kept, cards, anyLive, system, moves, last, demo.GetProperty("prossima_decisione").GetString(), news, learning, fractions);
}
private static async Task<Dictionary<Guid, AccountTrend>> TrendsAsync(AppServices services, AccountsView accounts, DateTimeOffset now, TimeZoneInfo zone,
CancellationToken cancellationToken)
{
var shown = accounts.Accounts.ToDictionary(a => a.Id);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT taken_at, account_id, currency, equity, flows FROM equity_snapshots WHERE scope = 'account' AND world = @w AND taken_at >= @f ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Account: r.IdOrNull("account_id"), Currency: r.TextOrNull("currency"), Equity: r.Money("equity"), Flows: r.MoneyOrNull("flows") ?? 0m),
("w", world), ("f", now.AddDays(-32))), cancellationToken).ConfigureAwait(false);
var result = new Dictionary<Guid, AccountTrend>();
foreach (var group in rows.Where(r => r.Account is { } id && shown.ContainsKey(id)).GroupBy(r => r.Account!.Value))
{
var account = shown[group.Key];
decimal Eur(decimal amount, string? currency) => currency == "USD" ? account.Eur(amount) : amount;
var daily = group.GroupBy(r => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(r.At, zone).DateTime)).Select(g => g.Last()).ToList();
var latest = daily[^1];
var latestDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(latest.At, zone).DateTime);
var start = daily.LastOrDefault(p => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime) <= latestDay.AddDays(-30));
start = start == default ? daily[0] : start;
var month = Eur(latest.Equity, latest.Currency) - Eur(start.Equity, start.Currency) - (Eur(latest.Flows, latest.Currency) - Eur(start.Flows, start.Currency));
var points = daily.Where(p => p.At >= start.At).Select(p => Eur(p.Equity - p.Flows, p.Currency)).ToList();
result[group.Key] = new AccountTrend(month, points);
}
return result;
}
/// <summary>Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60".</summary>
private static string Stage(StrategyCard card)
{
var stage = card.Stage.Stage;
if (stage == StrategyStages.Observation)
{
return "In osservazione";
}
if (stage == StrategyStages.Real)
{
return "Con soldi veri";
}
var where = stage == StrategyStages.Reduced ? "In reale ridotto" : "In simulazione";
var missing = card.Requirements
.Where(r => !r.Met && r.Key is "days" or "trades")
.Select(r => (r.Key, Value: Whole(r.Value), Target: Whole(r.Target)))
.Where(r => r.Value is not null && r.Target is > 0)
.OrderBy(r => (decimal)r.Value!.Value / r.Target!.Value)
.FirstOrDefault();
return missing.Key switch
{
"days" => $"{where}, giorno {missing.Value} di {missing.Target}",
"trades" => $"{where}, {missing.Value} operazioni su {missing.Target}",
_ => where,
};
static int? Whole(string text)
{
var digits = new string(text.Where(char.IsAsciiDigit).ToArray());
return int.TryParse(digits, NumberStyles.None, _it, out var n) ? n : null;
}
}
private static string Trades(StrategyCard card)
{
var open = card.Open.Distinct().Count();
var positions = open switch
{
0 => "Nessuna posizione aperta",
1 => "1 posizione aperta",
_ => $"{open} posizioni aperte",
};
var closed = card.Closed switch
{
0 => "nessuna operazione chiusa",
1 => $"1 operazione chiusa ({(card.Winners == 1 ? "in guadagno" : "in perdita")})",
_ => $"{card.Closed} operazioni chiuse ({card.Winners} in guadagno)",
};
return positions + ", " + closed;
}
/// <summary>"Prossima decisione tra 7 ore e 14 minuti, alle 15:35."</summary>
private static string? Decision(DateTimeOffset? due, DateTimeOffset now, TimeZoneInfo zone)
{
if (due is not { } at || at <= now)
{
return null;
}
var wait = at - now;
var hours = (int)wait.TotalHours;
var minutes = wait.Minutes;
var span = (hours, minutes) switch
{
(0, <= 1) => "un minuto",
(0, _) => $"{minutes} minuti",
(1, 0) => "un'ora",
(_, 0) => $"{hours} ore",
(1, _) => $"un'ora e {minutes} minuti",
_ => $"{hours} ore e {minutes} minuti",
};
var time = TimeZoneInfo.ConvertTime(at, zone).ToString("HH:mm", _it);
return wait < TimeSpan.FromHours(24) ? $"Prossima decisione tra {span}, alle {time}." : $"Prossima decisione {Format.ShortDate(at, now, zone).ToLowerInvariant()}.";
}
}
+31
View File
@@ -1,4 +1,35 @@
using Anubis.Server;
// "anubis db export <folder>" and "anubis db import <folder>" (SPEC 5.4) run with the engine stopped; anything else starts the server.
if (args.Length >= 1 && args[0] == "db")
{
return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis data report|binance|csv": the data quality report and the research imports (Phase 2).
if (args.Length >= 1 && args[0] == "data")
{
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5).
if (args.Length >= 1 && args[0] == "backtest")
{
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
if (args.Length >= 1 && args[0] == "soak")
{
return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis diagnostics": the data collected for the analysis of a long run, as one report to paste (issue #95).
if (args.Length >= 1 && args[0] == "diagnostics")
{
return await DiagnosticsCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;
+67
View File
@@ -0,0 +1,67 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The fixed templates that turn the reason codes of the decisions table into plain Italian (SPEC 5.2): the "why"
/// card of a trade and the diary use these, never free text written at decision time. An unknown code is shown as
/// it is, so nothing is ever hidden.
/// </summary>
internal static class ReasonTexts
{
// The exits in the few words of a table column; the full sentence stays for the "why" card.
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
{
["trend_exit"] = "La tendenza si è interrotta: prezzo sotto lo stop mobile",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti",
["momentum_exit_trend"] = "Il mercato è girato al ribasso",
["meanrev_exit_average"] = "Tornata sopra la media a 5 giorni",
["meanrev_exit_rsi"] = "Rimbalzo arrivato: forza tornata alta",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute",
["stop"] = "Stop di protezione raggiunto",
};
/// <summary>Why a trade was closed, in a short sentence.</summary>
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
public static string Text(string code) => ReasonCatalog.Text(code);
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
{
ArgumentNullException.ThrowIfNull(reasons);
var good = outcome is DecisionOutcomes.Passed or DecisionOutcomes.Proposed or DecisionOutcomes.Same;
if (stage == DecisionStages.Risk && outcome == DecisionOutcomes.Passed && reasons.Count == 0)
{
yield return new WhyLine("Tutti i limiti di rischio rispettati" + Asked(data), true);
yield break;
}
foreach (var reason in reasons)
{
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
}
}
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
private static string Asked(string? data)
{
if (data is null)
{
return "";
}
using var json = JsonDocument.Parse(data);
if (json.RootElement.TryGetProperty("asked", out var asked) && json.RootElement.TryGetProperty("allowed", out var allowed) &&
asked.TryGetDecimal(out var a) && allowed.TryGetDecimal(out var b) && b < a)
{
return $" (chiesti {Format.Quantity(a)}, passati {Format.Quantity(b)})";
}
return "";
}
}
+152
View File
@@ -0,0 +1,152 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A row of the limits table: what is used now against the threshold, and what happens beyond it.</summary>
internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key);
/// <summary>A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below.</summary>
internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown);
/// <summary>
/// The Rischio screen (SPEC 9, 13.6, mockup 07): the emergency switch, the automatic blocks, the limits with what
/// they use now, the fall from the high, the scenarios and the risk events. One world, as on Conti.
/// </summary>
internal sealed record RiskView(
string BotState,
bool StopFile,
bool CloseAllPending,
string World,
WorldRisk Risk,
RiskLimits Limits,
IReadOnlyList<LimitRow> Rows,
IReadOnlyList<DrawdownPoint> Drawdown,
IReadOnlyList<ScenarioResult> Scenarios,
IReadOnlyList<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)> Events,
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
bool PdtGuard,
bool HasPositions,
IReadOnlyList<WorldRisk> Tripped)
{
public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
/// <summary>The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto".</summary>
public bool WaitsForRestart => BotState == "stopped" || Tripped.Count > 0;
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var engine = services.Trading?.Risk ?? new RiskEngine(services.Db, clock, new Ledger(services.Db, clock),
new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), services.Settings, new FxStore(services.Db, clock),
(_, _) => Task.FromResult<Instrument?>(null), (_, _) => Task.FromResult<Quote?>(null));
var limits = await RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
var accounts = await AccountsView.LoadAsync(services, clock, zone, cancellationToken).ConfigureAwait(false);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var risk = await engine.WorldAsync(world, cancellationToken).ConfigureAwait(false);
// Both worlds: a switch tripped in the simulation must show even when the page measures the real one.
var tripped = new List<WorldRisk>();
foreach (var w in new[] { Worlds.Real, Worlds.Simulated })
{
var each = w == world ? risk : await engine.WorldAsync(w, cancellationToken).ConfigureAwait(false);
if (each.State.Tripped)
{
tripped.Add(each);
}
}
// Weights, crypto and the risk of a trade are measured on the reference equity, as the risk engine does (SPEC 9.2).
var reference = await engine.ReferenceAsync(cancellationToken).ConfigureAwait(false);
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var now = clock.UtcNow;
var (index, sent) = await services.Db.ReadAsync(async s =>
{
var i = await s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world)).ConfigureAwait(false);
var o = await s.QueryAsync(
"SELECT o.account_id, COUNT(*) AS n FROM orders o WHERE o.submitted_at >= @f AND o.purpose IN ('entry', 'exit') GROUP BY o.account_id",
r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", now - TimeSpan.FromMinutes(1))).ConfigureAwait(false);
return (i, o);
}, cancellationToken).ConfigureAwait(false);
var shown = accounts.Accounts.Select(a => a.Id).ToHashSet();
var equity = accounts.TotalEur;
var positions = accounts.Positions;
var biggest = positions.MaxBy(p => p.ValueEur);
var crypto = positions.Where(p => p.Broker == Venues.Okx).Sum(p => p.ValueEur);
decimal Rate(PositionRow p) => p.Last == 0m ? 0m : p.ValueEur / (p.Quantity * p.Last);
var atRisk = positions.Select(p => p.Stop is { } stop ? Math.Max(0m, p.ValueEur - (p.Quantity * stop * Rate(p))) : p.ValueEur).ToList();
var perMinute = sent.Where(x => shown.Contains(x.Account)).Select(x => x.Count).DefaultIfEmpty(0).Max();
string Pct(decimal fraction, int decimals = 2, bool sign = false) => Format.Percent(fraction * 100m, decimals, sign);
decimal? Use(decimal value, decimal limit) => limit <= 0m ? null : Math.Clamp(value / limit, 0m, 1m);
var m = risk.Measures;
var rows = new List<LimitRow>
{
new("Perdita in un giorno", m.DayChange >= 0m ? "nessuna" : Pct(m.DayChange), m.DayChange >= 0m ? $"oggi {Pct(m.DayChange, 2, true)}" : null,
Use(-m.DayChange, limits.DailyLoss), Pct(-limits.DailyLoss), "Niente nuovi ingressi per 24 ore", RiskSettings.DailyLoss.Key),
new("Perdita in una settimana", m.WeekChange >= 0m ? "nessuna" : Pct(m.WeekChange), m.WeekChange >= 0m ? $"{Pct(m.WeekChange, 2, true)}" : null,
Use(-m.WeekChange, limits.WeeklyLoss), Pct(-limits.WeeklyLoss), "Rischio dimezzato per sette giorni", RiskSettings.WeeklyLoss.Key),
new("Calo dal massimo", Pct(m.Drawdown), Worst(index, risk.State.PeakFrom) is { } worst && worst < m.Drawdown ? $"peggiore {Pct(worst)}" : null,
Use(-m.Drawdown, limits.DrawdownStop), $"{Pct(-limits.DrawdownHalf, 0)} e {Pct(-limits.DrawdownStop, 0)}",
$"A {Pct(-limits.DrawdownHalf, 0)} dimezzo il rischio. A {Pct(-limits.DrawdownStop, 0)} fermo tutto e aspetto te", RiskSettings.DrawdownStop.Key),
new("Capitale investito", equity > 0m ? Pct(accounts.InvestedEur / equity, 1) : "—", null, equity > 0m ? Use(accounts.InvestedEur / equity, limits.MaxInvested) : null,
Pct(limits.MaxInvested, 0), "Non compro altro: non uso mai soldi presi in prestito", RiskSettings.MaxInvested.Key),
new("Peso di una sola posizione", biggest is null || reference <= 0m ? "—" : Pct(biggest.ValueEur / reference, 1), biggest?.Symbol,
biggest is null || reference <= 0m ? 0m : Use(biggest.ValueEur / reference, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
RiskSettings.MaxPosition.Key),
new("Crypto sul totale", reference > 0m ? Pct(crypto / reference, 1) : "—", null, reference > 0m ? Use(crypto / reference, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
"Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key),
new("Rischio di una singola operazione", atRisk.Count == 0 || reference <= 0m ? "—" : Pct(atRisk.Average() / reference), atRisk.Count == 0 ? null : "in media, oggi fino allo stop",
atRisk.Count == 0 || reference <= 0m ? 0m : Use(atRisk.Average() / reference, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "All'acquisto rimpicciolisco l'ordine prima di inviarlo",
RiskSettings.MaxTradeRisk.Key),
new("Ordini al minuto", perMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), null, Use(perMinute, limits.OrdersPerMinute),
limits.OrdersPerMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), "Mi fermo e ti avviso: può essere un guasto", RiskSettings.OrdersPerMinute.Key),
new("Età dei prezzi", "controllata a ogni ordine", null, null, $"{(int)limits.MaxPriceAge.TotalSeconds} secondi", "Non apro posizioni finché i dati non tornano freschi",
RiskSettings.MaxPriceAge.Key),
};
var drawdown = new List<DrawdownPoint>();
var peak = 0m;
foreach (var p in index.Where(p => risk.State.PeakFrom is null || p.At >= risk.State.PeakFrom))
{
peak = Math.Max(peak, p.Index);
drawdown.Add(new DrawdownPoint(p.At, peak > 0m ? (p.Index / peak) - 1m : 0m));
}
var scenarioText = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, cancellationToken).ConfigureAwait(false)).Value;
var dollars = accounts.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity));
var scenarios = Anubis.Risk.Scenarios.Compute(Anubis.Risk.Scenarios.Parse(scenarioText),
[.. positions.Select(p => new ScenarioPosition(p.Broker == Venues.Okx, p.ValueEur, p.Stop is { } stop ? p.Quantity * stop * Rate(p) : null))], dollars, equity);
var calendar = await new CalendarEventStore(services.Db, clock).BetweenAsync(now.AddDays(-14), now.AddDays(14), cancellationToken).ConfigureAwait(false);
var windows = calendar.Select(e => (Event: e, Window: CalendarBlocks.Window(e))).Where(x => x.Window is not null)
.Select(x => (x.Window!.Value.From, x.Window.Value.To, x.Event.Title)).OrderBy(x => x.From).ToList();
(DateTimeOffset, DateTimeOffset, string)? next = windows.FirstOrDefault(w => w.To > now) is { Title: not null } n ? n : null;
(DateTimeOffset, DateTimeOffset, string)? last = windows.LastOrDefault(w => w.To <= now) is { Title: not null } l ? l : null;
return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios,
await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false),
positions.Count > 0, tripped);
}
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
{
decimal? worst = null;
var peak = 0m;
foreach (var p in index.Where(p => from is null || p.At >= from))
{
peak = Math.Max(peak, p.Index);
var d = peak > 0m ? (p.Index / peak) - 1m : 0m;
worst = worst is null ? d : Math.Min(worst.Value, d);
}
return worst;
}
}
+245 -6
View File
@@ -1,18 +1,257 @@
using System.Collections;
using Anubis.Access;
using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Server.Components;
using Anubis.Supervision;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
namespace Anubis.Server;
/// <summary>Builds the web application. Kept apart from Program so tests can host it.</summary>
internal static class ServerApp
{
public static WebApplication Build(string[] args)
public static WebApplication Build(string[] args, ServerOverrides? overrides = null)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var environment = overrides?.Environment ?? ReadEnvironment();
var options = ServerOptions.Parse(args, environment);
IClock clock = overrides?.Clock ?? (options.Demo ? new ManualClock(DemoMode.Now) : new Anubis.Core.SystemClock());
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok", AnubisInfo.Name, AnubisInfo.Version)));
// Demo mode never reads the configured database: it gets a brand-new folder of its own (trap 27).
var config = options.Demo ? DemoMode.Config(DemoMode.CreateFolder(new Anubis.Core.SystemClock())) : options.LoadConfig(environment);
RegisterSecrets(config);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = options.AspNetArgs,
ApplicationName = typeof(ServerApp).Assembly.GetName().Name,
ContentRootPath = AppContext.BaseDirectory,
});
if (!options.AspNetArgs.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
{
// Desktop and demo listen only on the computer itself unless the user allowed the home network (SPEC 15.6).
var local = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
builder.Logging.ClearProviders();
// Created by the container so it is disposed with the application and releases the log file.
builder.Services.AddSingleton<ILoggerProvider>(_ => new JsonLogProvider(config.Data.Logs, clock, console: true));
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Information);
// The form-token keys sit unencrypted in the data folder, which only the app's user can read (ADR 0007).
builder.Logging.AddFilter("Microsoft.AspNetCore.DataProtection", LogLevel.Error);
var services = builder.Services;
services.AddSingleton(options);
services.AddSingleton(config);
services.AddSingleton(environment);
services.AddSingleton(clock);
services.AddSingleton(overrides ?? new ServerOverrides());
services.AddSingleton<EventBus>();
// Started by the guard (SPEC 9.3): the channel to it. Never in demo mode, which protects nothing.
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides)
{
Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService<ILogger<GuardLink>>()),
});
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
services.AddSingleton(new LoginLimiter(clock));
services.AddSingleton<ShellData>();
services.AddSingleton<SecondFactorDrafts>();
services.AddAuthentication(SessionAuthentication.SchemeName)
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(SessionAuthentication.SchemeName, null);
services.AddAuthorization();
services.AddAntiforgery(o =>
{
o.Cookie.Name = "anubis_csrf";
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.HttpOnly = true;
o.HeaderName = Endpoints.CsrfHeader;
o.FormFieldName = "__csrf";
});
// The keys behind the form tokens live in the data folder, so a restart or a new container keeps open pages working
// (otherwise ASP.NET would use a home folder that in Docker belongs to root, or keys lost at every start).
services.AddDataProtection()
.SetApplicationName("Anubis")
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(config.Data.Root, "web-keys")));
services.AddRazorComponents();
// Pages in Italian stay readable: letters with accents and the euro sign are written as they are.
services.AddSingleton(System.Text.Encodings.Web.HtmlEncoder.Create(System.Text.Unicode.UnicodeRanges.All));
var app = builder.Build();
var host = app.Services.GetRequiredService<AnubisHost>();
if (host.Guard is { } guard)
{
// The guard asks for an orderly stop when the container stops; every stop of the engine is announced to it.
guard.StopRequested = app.Lifetime.StopApplication;
app.Lifetime.ApplicationStopping.Register(() => guard.AnnounceAsync("uscita").GetAwaiter().GetResult());
app.Lifetime.ApplicationStopped.Register(() => guard.DisposeAsync().AsTask().GetAwaiter().GetResult());
}
app.Use(SecurityHeaders);
app.Use((context, next) => LocalOnly(context, next, options, config));
app.Use((context, next) => Gate.InvokeAsync(context, next, host));
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
app.UseRouting();
app.UseAuthentication();
app.Use(MustChangePassword);
app.UseAuthorization();
app.UseAntiforgery();
Endpoints.Map(app);
app.MapRazorComponents<App>().RequireAuthorization();
return app;
}
private static Dictionary<string, string?> ReadEnvironment()
{
var result = new Dictionary<string, string?>(StringComparer.Ordinal);
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
result[(string)entry.Key] = entry.Value as string;
}
return result;
}
// Every secret the startup configuration knows is masked in logs and messages from the first line on.
private static void RegisterSecrets(StartupConfig config)
{
Redactor.Register(config.Db?.Password);
Redactor.Register(config.AdminPassword);
foreach (var value in config.EnvironmentKeys.Values)
{
Redactor.Register(value);
}
}
private static Task SecurityHeaders(HttpContext context, Func<Task> next)
{
var headers = context.Response.Headers;
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "same-origin";
headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " +
"font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'";
return next();
}
// Defence in depth: even if someone binds the server to every address, desktop and demo answer only the computer itself.
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options, StartupConfig config)
{
var localOnly = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
if (localOnly && !CurrentUser.IsLocal(context))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsync("Anubis risponde solo dal computer su cui gira.");
}
return next();
}
// Docker: the initial password works once, then the interface asks for a new one before anything else (SPEC 13.1).
private static Task MustChangePassword(HttpContext context, Func<Task> next)
{
if (context.User.Identity?.IsAuthenticated != true || !CurrentUser.MustChangePassword(context.User))
{
return next();
}
var path = context.Request.Path;
if (path.StartsWithSegments("/primo-accesso", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-accesso", StringComparison.Ordinal) ||
path.StartsWithSegments("/azioni/esci", StringComparison.Ordinal) || Gate.IsAlwaysOpen(path))
{
return next();
}
if (SessionAuthentication.IsApi(context.Request))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsJsonAsync(new ApiError("password_da_cambiare", "Scegli una nuova password prima di continuare."));
}
context.Response.Redirect("/primo-accesso");
return Task.CompletedTask;
}
}
/// <summary>Answer of <c>GET /health</c>.</summary>
internal sealed record HealthResponse(string Status, string Name, string Version);
/// <summary>
/// While the application is not ready, every page is the service page (error, first run): the engine does not start
/// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer.
/// </summary>
internal static class Gate
{
public static bool IsAlwaysOpen(PathString path) =>
path.StartsWithSegments("/health", StringComparison.Ordinal) || path.StartsWithSegments("/assets", StringComparison.Ordinal) ||
path.StartsWithSegments("/brand", StringComparison.Ordinal) || path == "/favicon.ico";
public static async Task InvokeAsync(HttpContext context, Func<Task> next, AnubisHost host)
{
var path = context.Request.Path;
var mode = host.Status.Mode;
if (IsAlwaysOpen(path))
{
await next().ConfigureAwait(false);
return;
}
if (mode == HostMode.Ready)
{
if (path.StartsWithSegments("/servizio", StringComparison.Ordinal) || path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal))
{
context.Response.Redirect("/");
return;
}
await next().ConfigureAwait(false);
return;
}
var api = SessionAuthentication.IsApi(context.Request);
if (mode == HostMode.FirstRun)
{
if (path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-avvio", StringComparison.Ordinal))
{
await next().ConfigureAwait(false);
return;
}
if (!api && HttpMethods.IsGet(context.Request.Method))
{
context.Response.Redirect("/primo-avvio");
return;
}
}
else if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal))
{
await next().ConfigureAwait(false);
return;
}
if (api)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsJsonAsync(new ApiError("non_pronto", ServiceText.Title(mode))).ConfigureAwait(false);
return;
}
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsync(ServiceText.Title(mode)).ConfigureAwait(false);
return;
}
// The service page answers in place of whatever was asked, with 503 so nothing caches it.
context.Request.Path = "/servizio";
await next().ConfigureAwait(false);
}
}
+84
View File
@@ -0,0 +1,84 @@
using Anubis.Core;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>
/// What the server process was asked to be, from its arguments and environment: Docker or desktop, which data
/// folder, demo mode. Tests pass a fake environment and clock through <see cref="ServerOverrides"/>.
/// </summary>
internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, bool Demo, string[] AspNetArgs)
{
public static ServerOptions Parse(string[] args, IReadOnlyDictionary<string, string?> environment)
{
var rest = new List<string>();
PlatformKind? platform = null;
string? dataDir = null;
var demo = false;
for (var i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--platform" when i + 1 < args.Length:
platform = args[++i].Equals("docker", StringComparison.OrdinalIgnoreCase) ? PlatformKind.Docker : PlatformKind.Desktop;
break;
case "--data-dir" when i + 1 < args.Length:
dataDir = Path.GetFullPath(args[++i]);
break;
case "--demo":
demo = true;
break;
default:
rest.Add(args[i]);
break;
}
}
platform ??= (environment.GetValueOrDefault("ANUBIS_PLATFORM") ?? "").ToLowerInvariant() switch
{
"docker" => PlatformKind.Docker,
"desktop" => PlatformKind.Desktop,
_ => environment.GetValueOrDefault("DOTNET_RUNNING_IN_CONTAINER") == "true" ? PlatformKind.Docker : PlatformKind.Desktop,
};
return new ServerOptions(platform.Value, dataDir, demo, [.. rest]);
}
/// <summary>Reads the startup configuration of the chosen platform.</summary>
public StartupConfig LoadConfig(IReadOnlyDictionary<string, string?> environment)
{
if (Platform == PlatformKind.Docker)
{
return DockerPlatform.Load(environment, DataDir ?? "/data");
}
var data = DataDir is null ? DataDirectory.ForCurrentUser() : new DataDirectory(DataDir);
return DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
}
}
/// <summary>Test hooks: a fake environment, a manual clock, a cheaper password hash.</summary>
internal sealed record ServerOverrides
{
public IReadOnlyDictionary<string, string?>? Environment { get; init; }
public IClock? Clock { get; init; }
public int? PasswordIterations { get; init; }
/// <summary>How often the database is checked while running and retried while it is missing.</summary>
public TimeSpan? DatabaseCheckInterval { get; init; }
/// <summary>False turns market data off (tests without network); null follows demo mode and ANUBIS_MARKET_DATA.</summary>
public bool? MarketData { get; init; }
/// <summary>Answers the market data requests instead of the network (tests).</summary>
public HttpMessageHandler? MarketHttp { get; init; }
public Func<Anubis.Brokers.IWebSocketTransport>? MarketSockets { get; init; }
/// <summary>Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram.</summary>
public HttpMessageHandler? TelegramHttp { get; init; }
/// <summary>True starts the accounts and the order managers in a test; off by default in tests.</summary>
public bool? Trading { get; init; }
}
+124
View File
@@ -0,0 +1,124 @@
using System.Globalization;
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Anubis.Access;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace Anubis.Server;
/// <summary>
/// Sign-in by session cookie (SPEC 15.4): the cookie holds a random token, the database only its hash. HttpOnly,
/// SameSite=Strict, Secure when the request is HTTPS. In demo mode everyone on the computer itself is signed in.
/// </summary>
internal sealed class SessionAuthentication(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AnubisHost host) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "anubis";
public const string Cookie = "anubis_session";
public const string SessionClaim = "anubis:session";
public const string MustChangeClaim = "anubis:must_change";
public const string SecondFactorClaim = "anubis:second_factor";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var services = host.Services;
if (services is null)
{
return AuthenticateResult.NoResult();
}
if (host.IsDemo)
{
var user = await services.Access.GetUserAsync(Context.RequestAborted).ConfigureAwait(false);
return user is null ? AuthenticateResult.NoResult() : Success(user, Guid.Empty);
}
if (!Request.Cookies.TryGetValue(Cookie, out var token) || string.IsNullOrEmpty(token))
{
return AuthenticateResult.NoResult();
}
var session = await services.Access.ValidateAsync(token, Context.RequestAborted).ConfigureAwait(false);
return session is null ? AuthenticateResult.Fail("Sessione scaduta") : Success(session.User, session.Id);
}
private static AuthenticateResult Success(User user, Guid session)
{
Claim[] claims =
[
new(ClaimTypes.NameIdentifier, user.Id.ToString("D")),
new(ClaimTypes.Name, user.Username),
new(SessionClaim, session.ToString("D")),
new(MustChangeClaim, user.MustChangePassword ? "1" : "0"),
new(SecondFactorClaim, user.HasSecondFactor ? "1" : "0"),
];
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (IsApi(Request))
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
return Response.WriteAsJsonAsync(new ApiError("non_autenticato", "Accedi di nuovo."));
}
var back = Request.Path + Request.QueryString;
Response.Redirect("/accesso" + (back == "/" ? "" : "?ritorno=" + Uri.EscapeDataString(back)));
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
}
internal static bool IsApi(HttpRequest request) =>
request.Path.StartsWithSegments("/api", StringComparison.Ordinal) || request.Path.StartsWithSegments("/ws", StringComparison.Ordinal);
public static void WriteCookie(HttpContext context, string token) =>
context.Response.Cookies.Append(Cookie, token, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = context.Request.IsHttps,
Path = "/",
MaxAge = AccessStore.MaxLifetime,
IsEssential = true,
});
public static void ClearCookie(HttpContext context) =>
context.Response.Cookies.Delete(Cookie, new CookieOptions { Path = "/", HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps });
}
/// <summary>Who is signed in, read from the claims.</summary>
internal static class CurrentUser
{
public static Guid Id(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!, CultureInfo.InvariantCulture);
public static Guid Session(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(SessionAuthentication.SessionClaim) ?? Guid.Empty.ToString(), CultureInfo.InvariantCulture);
public static bool MustChangePassword(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.MustChangeClaim) == "1";
public static bool HasSecondFactor(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.SecondFactorClaim) == "1";
/// <summary>
/// The request comes from the computer the server runs on, addressed to it by a local name. The name matters too:
/// a web page that points its own name at 127.0.0.1 (DNS rebinding) arrives from the loopback with a foreign Host.
/// </summary>
public static bool IsLocal(HttpContext context) =>
context.Connection.RemoteIpAddress is { } address && IPAddress.IsLoopback(address) && IsLocalName(context.Request.Host.Host);
internal static bool IsLocalName(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host is "127.0.0.1" or "[::1]" or "::1";
}
/// <summary>Error body of the API: a code for programs and a sentence for people.</summary>
internal sealed record ApiError(string Code, string Message);
+105
View File
@@ -0,0 +1,105 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>What the top bar shows and the WebSocket sends: state of the bot, mode, currency, how fresh the data are.</summary>
internal sealed record ShellSnapshot(
string Mode,
string Bot,
string BotLabel,
string BotShort,
bool RealMoney,
string Currency,
string Theme,
string Now,
int AgeSeconds,
bool Demo,
string Version);
/// <summary>Reads the shell state once per request; also the money formatter with the chosen display currency.</summary>
internal sealed class ShellData(AnubisHost host, IClock clock)
{
private decimal? _demoRate;
private int? _demoAge;
public bool IsDemo => host.IsDemo;
public TimeZoneInfo Zone => host.Config.TimeZone;
public DateTimeOffset Now => clock.UtcNow;
public async Task<ShellSnapshot> SnapshotAsync(CancellationToken cancellationToken)
{
var services = host.Services;
var bot = "active";
var currency = "EUR";
var theme = "auto";
if (services is not null)
{
bot = (await services.Settings.GetAsync(Core.SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
currency = (await services.Settings.GetAsync(Core.SettingsStore.Currency.Key, cancellationToken).ConfigureAwait(false)).Value;
theme = (await services.Settings.GetAsync(Core.SettingsStore.Theme.Key, cancellationToken).ConfigureAwait(false)).Value;
}
var (label, shortLabel) = bot switch
{
"paused" => ("Bot in pausa", "In pausa"),
"stopped" => ("Bot fermo", "Fermo"),
_ => ("Bot attivo", "Attivo"),
};
var age = DemoAge() ?? (host.LastCheckUtc is { } last ? (int)Math.Max(0, (clock.UtcNow - last).TotalSeconds) : 0);
return new ShellSnapshot(host.Status.Mode.ToString(), bot, label, shortLabel, RealMoney: false, currency, theme,
Format.LongDateTime(clock.UtcNow, Zone), age, host.IsDemo, AnubisInfo.Version);
}
/// <summary>
/// An amount in euro shown in the display currency. Exchange rates arrive with the market data (phase 2): until
/// then dollars appear only in demo mode, with the rate of appendix F, and otherwise amounts stay in euro.
/// </summary>
public string Money(decimal euro, string currency, bool withSign = false, int decimals = 2) =>
Format.Money(Convert(euro, currency), Effective(currency), withSign, decimals);
public decimal Convert(decimal euro, string currency) => currency == "USD" && DemoRate() is { } rate ? euro * rate : euro;
/// <summary>The display currency that <see cref="Money"/> can honour.</summary>
public string Effective(string currency) => currency == "USD" && DemoRate() is not null ? "USD" : "EUR";
private decimal? DemoRate()
{
if (!host.IsDemo)
{
return null;
}
if (_demoRate is null && Aggregates() is { } doc)
{
_demoRate = decimal.Parse(doc.RootElement.GetProperty("cambio_eur_usd").GetString()!, CultureInfo.InvariantCulture);
}
return _demoRate;
}
private int? DemoAge()
{
if (!host.IsDemo)
{
return null;
}
if (_demoAge is null && Aggregates() is { } doc)
{
_demoAge = doc.RootElement.GetProperty("dati_aggiornati_secondi").GetInt32();
}
return _demoAge;
}
/// <summary>The aggregates of appendix F; only in demo mode (SPEC 13.1).</summary>
public JsonDocument? Aggregates() => host.IsDemo ? DemoMode.ReadAggregates(host.Config.Data) : null;
public PlatformKind Platform => host.Config.Platform;
}
+77
View File
@@ -0,0 +1,77 @@
using System.Collections;
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
using Anubis.Supervision;
namespace Anubis.Server;
/// <summary>
/// "anubis soak": the report of an endurance run in real time (SPEC 17, phase 6) from the bot's own records. It only
/// reads, so it can run while the bot works: in Docker with <c>docker exec</c>, on desktop from a second terminal.
/// </summary>
internal static class SoakCommand
{
private const string Usage =
"Uso: anubis soak [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--hours 48] [--out file.md]\n" +
" senza --from la prova è delle ultime --hours ore fino a --to (o adesso).\n" +
"Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
/// <summary>0 when the run is in order, 4 when something must be looked at, 1 when the report could not be made.</summary>
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null, IClock? clock = null)
{
output ??= Console.Out;
clock ??= new SystemClock();
var own = new Dictionary<string, string>(StringComparer.Ordinal);
var rest = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length)
{
own[args[i]] = args[++i];
}
else if (args[i] is "--help" or "-h")
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
else
{
rest.Add(args[i]);
}
}
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
try
{
var hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : 48;
var to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : clock.UtcNow;
var from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : to - TimeSpan.FromHours(hours);
var options = ServerOptions.Parse([.. rest], environment);
var config = options.LoadConfig(environment);
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
return 1;
}
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
var report = await SoakReporter.BuildAsync(db, from, to, TimeSpan.FromHours(hours), config.TimeZone, CancellationToken.None).ConfigureAwait(false);
var text = report.Markdown(config.TimeZone);
if (own.TryGetValue("--out", out var file))
{
await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false);
}
await output.WriteAsync(text).ConfigureAwait(false);
return report.Passed ? 0 : 4;
}
catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException
or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
}
+210
View File
@@ -0,0 +1,210 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A strategy of the Strategie screen: its stage, results, requirements and what the user can do next.</summary>
internal sealed record StrategyCard(
StrategyStage Stage,
string Name,
string Description,
IReadOnlyList<string> Rules,
string Account,
string Currency,
decimal CapitalEur,
decimal ResultEur,
decimal ResultPercent,
decimal WorstFall,
int Closed,
int Winners,
IReadOnlyList<string> Open,
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo,
IReadOnlyList<string> Summary,
decimal? TwinGap)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
public bool AllMet => Requirements.All(r => r.Met);
}
/// <summary>
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
/// strategy with its requirements, and the ones in observation with the reason.
/// </summary>
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
{
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
{
[StrategyNames.CryptoTrend] =
[
"Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC",
"Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni",
"Più una moneta è agitata, meno ne compra",
"Mai a leva, mai al ribasso",
],
[StrategyNames.EquityMomentum] =
[
"Rifà la classifica ogni lunedì e tiene fino a 12 titoli",
"Vende chi esce dai primi 30 o tocca lo stop",
"Compra solo quando il mercato nel suo insieme sale",
"Solo azioni singole, nessun ETF americano",
],
[StrategyNames.EquityMeanrev] =
[
"Solo titoli sopra la loro media a 200 giorni",
"Esce al rimbalzo, oppure dopo 5 sedute",
"Salta i giorni prima delle trimestrali",
"Mai uscita nello stesso giorno dell'acquisto",
],
};
public static async Task<StrategiesView> LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts",
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken)
.ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
var limits = await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
decimal? reference = services.Trading?.Risk is { } risk ? await risk.ReferenceAsync(cancellationToken).ConfigureAwait(false) : null;
async Task<string> SymbolAsync(Guid instrument) =>
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
.ConfigureAwait(false) ?? "?";
var cards = new List<StrategyCard>();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
{
continue;
}
var family = StrategyCatalog.Find(stage.Strategy);
var ledgerAccount = stage.OrdersAccount ?? stage.AccountId;
var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount);
var usd = account.Currency == "USD";
decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount;
var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy);
// As on Conti: each position is valued to the cent before the sum, so both pages show the same figure.
var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero));
var result = equity is null ? 0m : equity.Cash + held - equity.Flows;
var since = stage.StageSince ?? DateTimeOffset.MinValue;
var (curve, trades) = await services.Db.ReadAsync(async s =>
{
var c = await s.QueryAsync(
"SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"),
("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
return (c, t);
}, cancellationToken).ConfigureAwait(false);
var peak = 0m;
var worst = 0m;
foreach (var p in curve)
{
peak = Math.Max(peak, p.Index);
worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m);
}
var symbols = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
{
symbols.Add(await SymbolAsync(p.InstrumentId).ConfigureAwait(false));
}
// What the confirmation of SPEC 12.4 changes: the capital used, the purchases of the first cycle (estimated
// from what the simulation holds today) and the limits with their base.
var summary = new List<string>();
if (stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
{
var toReduced = stage.Stage == StrategyStages.Simulation;
var factor = toReduced ? StrategyStages.ReducedShare : 1m;
var simEquity = equities.FirstOrDefault(e => e.AccountId == stage.AccountId && e.Strategy == stage.Strategy);
var simUsd = accounts.FirstOrDefault(a => a.Id == stage.AccountId).Currency == "USD";
decimal SimEur(decimal amount) => simUsd ? (rate > 0m ? amount / rate : 0m) : amount;
summary.Add(toReduced
? $"Capitale usato: un quarto di quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m) * factor, decimals: 0)}."
: $"Capitale usato: tutto quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m), decimals: 0)}.");
var buys = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == stage.AccountId && p.Strategy == stage.Strategy && p.Quantity > 0m))
{
buys.Add($"{await SymbolAsync(p.InstrumentId).ConfigureAwait(false)} per circa {Format.Money(SimEur(p.Value) * factor, decimals: 0)}");
}
summary.Add(buys.Count == 0
? "Acquisti al primo ciclo: nessuno per ora, la simulazione non tiene posizioni."
: (toReduced ? "Acquisti al primo ciclo, stimati da ciò che la simulazione tiene oggi: " : "Al primo ciclo le posizioni vere crescono fino alla misura piena: ") +
string.Join(", ", buys) + ".");
summary.Add("Limiti che valgono: perdita in un giorno " + Format.Percent(limits.DailyLoss * 100m, 1) + ", calo dal massimo " +
Format.Percent(limits.DrawdownHalf * 100m, 0) + " e " + Format.Percent(limits.DrawdownStop * 100m, 0) + ", una posizione " +
Format.Percent(limits.MaxPosition * 100m, 0) + ", rischio di un'operazione " + Format.Percent(limits.MaxTradeRisk * 100m, 1) +
", misurati sul patrimonio di riferimento" + (reference is { } r ? $" (oggi {Format.Money(r, decimals: 0)})" : "") +
(toReduced ? ", e in reale ridotto su un quarto di esso." : "."));
}
// The simulated twin against the real account (SPEC 12.3): the gap of results, as a share of the capital used.
decimal? twinGap = null;
if (stage.HasTwin && stage.AccountId is { } twinAccount &&
equities.FirstOrDefault(e => e.AccountId == twinAccount && e.Strategy == stage.Strategy) is { Flows: > 0m } twin && equity is { Flows: > 0m } real)
{
twinGap = ((real.Equity - real.Flows) / real.Flows * 100m) - ((twin.Equity - twin.Flows) / twin.Flows * 100m);
}
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced;
var days = requirements.FirstOrDefault(r => r.Key == "days");
int? toGo = days is { Met: false } && stage.StageSince is { } from
? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays)))
: null;
var flows = equity?.Flows ?? 0m;
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
}
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
public static bool IsPending(Requirement requirement)
{
ArgumentNullException.ThrowIfNull(requirement);
return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione");
}
/// <summary>Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice.</summary>
public static string ObservationReason(StrategyStage stage)
{
ArgumentNullException.ThrowIfNull(stage);
if (stage.Qualification is { Passed: false } q)
{
return q.Verdict;
}
if (stage.Qualification is null)
{
return "Il backtest non è ancora stato fatto: finché manca resta in osservazione.";
}
return stage.StageReason switch
{
"user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.",
var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".",
};
}
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
}
+332
View File
@@ -0,0 +1,332 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>How a component is doing: working, off by choice or not there yet, or in need of a look.</summary>
internal enum PartState
{
Ok,
Off,
Warn,
}
/// <summary>A component of the system with a line on how it is doing.</summary>
internal sealed record SystemPart(string Name, string Detail, PartState State);
/// <summary>A resource of the computer: what is used, out of how much, as a share for the bar.</summary>
internal sealed record HostResource(string Label, string Value, string? Of, decimal Share);
/// <summary>A job in the scheduler, with its time as people say it ("15:35", "Dom 03:00").</summary>
internal sealed record PlannedJob(string Time, string Text);
/// <summary>
/// The "Diario e sistema" right column and the Sistema tile of the Panoramica (SPEC 13.6, mockups 01 and 08): the
/// components with their state, the jobs in the scheduler, the resources of the computer, version and platform.
/// In demo mode the values of appendix F.10 (SPEC 13.1); otherwise the real services, process and disk.
/// </summary>
internal sealed record SystemView(
IReadOnlyList<SystemPart> Parts,
IReadOnlyList<SystemPart> Tiles,
IReadOnlyList<PlannedJob> Jobs,
IReadOnlyList<HostResource> Resources,
string Running)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
private static readonly string[] _days = ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"];
private static readonly string[] _months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
/// <summary>Nothing needs a look; components that are off by choice or not active yet do not count.</summary>
public bool AllWell => Parts.All(p => p.State != PartState.Warn);
public static async Task<SystemView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(shell);
using var aggregates = shell.Aggregates();
return aggregates is not null ? Demo(aggregates.RootElement, shell) : await RealAsync(host, shell, cancellationToken).ConfigureAwait(false);
}
private static SystemView Demo(JsonElement root, ShellData shell)
{
var system = root.GetProperty("sistema");
var accounts = root.GetProperty("conti").EnumerateArray().ToList();
var okxMs = accounts[0].GetProperty("risposta_ms").GetInt32();
var alpacaMs = accounts[1].GetProperty("risposta_ms").GetInt32();
var database = root.GetProperty("database").GetString()!;
var size = Format.Number(Dec(system, "database_gb"), 1) + " GB";
var telegram = system.GetProperty("telegram_ultimo").GetString();
var parts = new List<SystemPart>
{
new("Motore di trading", $"attivo, un controllo ogni {system.GetProperty("controllo_secondi").GetInt32()} secondi", PartState.Ok),
new("Prezzi da OKX Europe", $"in diretta, risposta in {okxMs} ms", PartState.Ok),
new("Prezzi da Alpaca", "collegato, " + Market(shell), PartState.Ok),
new("Lettura delle notizie", $"{system.GetProperty("notizie_fonti").GetInt32()} fonti, ultima lettura alle {system.GetProperty("notizie_ultima").GetString()}", PartState.Ok),
new("Database " + database, $"{size}, ultimo salvataggio alle {system.GetProperty("ultimo_salvataggio").GetString()}", PartState.Ok),
new("Telegram", $"collegato, ultimo messaggio alle {telegram}", PartState.Ok),
};
var tiles = new List<SystemPart>
{
new("OKX Europe", $"connesso, {okxMs} ms", PartState.Ok),
new("Alpaca", $"connesso, {alpacaMs} ms", PartState.Ok),
new("Prezzi di mercato", $"aggiornati {root.GetProperty("dati_aggiornati_secondi").GetInt32()} s fa", PartState.Ok),
new("Notizie", $"{root.GetProperty("notizie").GetProperty("lette_24h").GetInt32()} lette in 24 ore", PartState.Ok),
new("Database", $"{database}, {size}", PartState.Ok),
new("Telegram", $"ultimo messaggio alle {telegram}", PartState.Ok),
};
var jobs = system.GetProperty("lavori").EnumerateArray()
.Select(j => new PlannedJob(j.GetProperty("ora").GetString()!, j.GetProperty("testo").GetString()!)).ToList();
var memory = Dec(system, "memoria_gb");
var memoryTotal = system.GetProperty("memoria_totale_gb").GetDecimal();
var disk = Dec(system, "disco_gb");
var diskTotal = system.GetProperty("disco_totale_gb").GetDecimal();
var resources = new List<HostResource>
{
new("Processore", system.GetProperty("cpu_pct").GetInt32().ToString(_it) + "%", null, system.GetProperty("cpu_pct").GetDecimal() / 100m),
new("Memoria", Format.Number(memory, 1) + " GB", Format.Number(memoryTotal), memory / memoryTotal),
new("Spazio per i dati", Format.Number(disk, 1) + " GB", Format.Number(diskTotal), disk / diskTotal),
};
var started = DateOnly.ParseExact(root.GetProperty("avvio").GetString()!, "yyyy-MM-dd", _it);
var running = $"Anubis {root.GetProperty("versione").GetString()} in {root.GetProperty("piattaforma").GetString()}, acceso dal {started.Day} {_months[started.Month - 1]}: " +
$"{root.GetProperty("giorno").GetInt32()} giorni senza interruzioni.";
return new SystemView(parts, tiles, jobs, resources, running);
}
private static async Task<SystemView> RealAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
{
var services = host.Services!;
var now = shell.Now;
var zone = shell.Zone;
var parts = new List<SystemPart>();
var tiles = new List<SystemPart>();
// The trading engine, and the state the user chose for the bot.
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var trading = services.Trading;
parts.Add(trading switch
{
null => new SystemPart("Motore di trading", "spento: le strategie non lavorano", PartState.Off),
{ IsStarted: false } => new SystemPart("Motore di trading", "non è ancora partito: se non parte entro qualche minuto, guarda i registri tecnici", PartState.Warn),
_ when bot == "stopped" => new SystemPart("Motore di trading", "fermo con Ferma tutto: riparte solo con la tua conferma, dalla pagina Rischio", PartState.Warn),
_ => new SystemPart("Motore di trading",
$"{(bot == "paused" ? "in pausa" : "attivo")}, un controllo ogni {(int)trading.TickInterval.TotalSeconds} secondi", PartState.Ok),
});
// The two price feeds: the live OKX connection, the state of the Alpaca source.
var market = services.MarketData;
var sources = market is null ? [] : await new SourceStateStore(services.Db, host.Clock).ListAsync(cancellationToken).ConfigureAwait(false);
var okx = sources.FirstOrDefault(s => s.Source == MarketDataService.OkxSource);
var (okxPart, okxTile) = market switch
{
null => (new SystemPart("Prezzi da OKX Europe", "spenti", PartState.Off), new SystemPart("OKX Europe", "spento", PartState.Off)),
{ LiveConnected: true } => (new SystemPart("Prezzi da OKX Europe", "in diretta", PartState.Ok), new SystemPart("OKX Europe", "connesso", PartState.Ok)),
_ when Failing(okx) => (new SystemPart("Prezzi da OKX Europe", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("OKX Europe", "non risponde", PartState.Warn)),
_ => (new SystemPart("Prezzi da OKX Europe", "in collegamento", PartState.Off), new SystemPart("OKX Europe", "in collegamento", PartState.Off)),
};
parts.Add(okxPart);
var alpaca = sources.FirstOrDefault(s => s.Source == MarketDataService.AlpacaSource);
var (alpacaPart, alpacaTile) = (market, alpaca) switch
{
(null, _) => (new SystemPart("Prezzi da Alpaca", "spenti", PartState.Off), new SystemPart("Alpaca", "spento", PartState.Off)),
(_, null) => (new SystemPart("Prezzi da Alpaca", "in attesa del primo collegamento", PartState.Off), new SystemPart("Alpaca", "in attesa", PartState.Off)),
(_, { Enabled: false }) => (new SystemPart("Prezzi da Alpaca", "spenti: mancano le chiavi del conto di prova, in Impostazioni", PartState.Off),
new SystemPart("Alpaca", "senza chiavi", PartState.Off)),
_ when Failing(alpaca) => (new SystemPart("Prezzi da Alpaca", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("Alpaca", "non risponde", PartState.Warn)),
_ => (new SystemPart("Prezzi da Alpaca", "collegato, " + Market(shell, market.UsCalendar), PartState.Ok), new SystemPart("Alpaca", "connesso", PartState.Ok)),
};
parts.Add(alpacaPart);
tiles.Add(okxTile);
tiles.Add(alpacaTile);
var newest = market?.Freshness.Snapshot().Select(s => s.LastDataAt).Max();
tiles.Add(newest is { } at
? new SystemPart("Prezzi di mercato", "aggiornati " + Ago(now - at), now - at > TimeSpan.FromMinutes(5) ? PartState.Warn : PartState.Ok)
: new SystemPart("Prezzi di mercato", "in attesa dei primi prezzi", PartState.Off));
// News arrive with phase 7 (SPEC 10).
parts.Add(new SystemPart("Lettura delle notizie", "non ancora attiva", PartState.Off));
tiles.Add(new SystemPart("Notizie", "non ancora attive", PartState.Off));
// The database: engine, size, last backup.
var engine = services.Db.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite";
var bytes = await SizeAsync(services.Db, host.Config.Db, cancellationToken).ConfigureAwait(false);
var backups = services.Backups.List();
var lastBackup = backups.Count == 0 ? null : (DateTimeOffset?)backups.Max(b => b.TakenAt);
var size = bytes is { } b ? Bytes(b) : null;
var saved = lastBackup is { } l ? "ultimo salvataggio " + When(l, now, zone) : "nessun salvataggio ancora";
parts.Add(new SystemPart("Database " + engine, (size is null ? "" : size + ", ") + saved, PartState.Ok));
tiles.Add(new SystemPart("Database", engine + (size is null ? "" : ", " + size), PartState.Ok));
// Telegram: the last message that really left (SPEC 14), never one only queued.
var telegram = services.Telegram;
var settings = telegram is null ? null : await telegram.ReadAsync(cancellationToken).ConfigureAwait(false);
if (telegram is null || settings is null)
{
parts.Add(new SystemPart("Telegram", "non configurato: si imposta in Impostazioni", PartState.Off));
tiles.Add(new SystemPart("Telegram", "non configurato", PartState.Off));
}
else
{
var summary = await telegram.Sender.SummaryAsync(cancellationToken).ConfigureAwait(false);
var last = summary.LastSentAt is { } sent ? "ultimo messaggio " + When(sent, now, zone) : "nessun messaggio inviato ancora";
var stuck = summary.Retrying + summary.GaveUp > 0;
parts.Add(new SystemPart("Telegram", stuck ? "alcuni messaggi non sono partiti: riprovo da solo; " + last : "collegato, " + last, stuck ? PartState.Warn : PartState.Ok));
tiles.Add(new SystemPart("Telegram", last, stuck ? PartState.Warn : PartState.Ok));
}
// Appointments only: the jobs that run every minute or every hour are background work.
var jobs = services.Scheduler.Upcoming(200).Where(u => !u.Periodic).Take(7)
.Select(u => new PlannedJob(JobTime(u.DueUtc, now, zone), u.Description)).ToList();
var since = host.Status.Since;
var platform = host.Config.Platform == PlatformKind.Docker ? "in Docker" : "come applicazione desktop";
var localSince = TimeZoneInfo.ConvertTime(since, zone);
var days = (int)Math.Floor((now - since).TotalDays);
var running = days >= 1
? $"Anubis {AnubisInfo.Version} {platform}, acceso dal {localSince.Day} {_months[localSince.Month - 1]}: {days} {(days == 1 ? "giorno" : "giorni")} senza interruzioni."
: $"Anubis {AnubisInfo.Version} {platform}, acceso oggi alle {localSince.ToString("HH:mm", _it)}.";
return new SystemView(parts, tiles, jobs, MeasureHost(host.Config.Data), running);
}
private static bool Failing(SourceState? state) =>
state is { LastError: not null } && (state.LastSuccessAt is null || state.LastRequestAt > state.LastSuccessAt);
private static string Market(ShellData shell, IMarketCalendar? calendar = null)
{
var (open, next) = AccountsView.MarketState(calendar, shell.Now);
var time = TimeZoneInfo.ConvertTime(next, shell.Zone).ToString("HH:mm", _it);
return open ? "mercato aperto fino alle " + time : "mercato chiuso fino alle " + time;
}
private static async Task<long?> SizeAsync(Database db, DbSettings? settings, CancellationToken cancellationToken)
{
try
{
if (db.Engine == DbEngine.Postgres)
{
return await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT pg_database_size(current_database()) AS n", r => (long?)r.Number("n")), cancellationToken)
.ConfigureAwait(false);
}
if (settings?.SqlitePath is { } path && File.Exists(path))
{
var wal = path + "-wal";
return new FileInfo(path).Length + (File.Exists(wal) ? new FileInfo(wal).Length : 0);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
{
// The size is a detail: without it the line still says engine and backups.
}
return null;
}
/// <summary>
/// Processor of this process (share of all cores since the last look, or since it started), its memory against
/// what the container or computer gives it, and the disk that holds the data folder.
/// </summary>
private static List<HostResource> MeasureHost(DataDirectory data)
{
var list = new List<HostResource>();
var cpu = CpuSampler.Share();
list.Add(new HostResource("Processore", Format.Number(cpu * 100m) + "%", null, cpu));
using var process = Process.GetCurrentProcess();
var used = process.WorkingSet64;
var total = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes;
if (total > 0)
{
list.Add(new HostResource("Memoria", Bytes(used), Bytes(total, unit: false), Math.Clamp((decimal)used / total, 0m, 1m)));
}
try
{
var drive = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(data.Root))!);
if (drive.IsReady && drive.TotalSize > 0)
{
var taken = drive.TotalSize - drive.AvailableFreeSpace;
list.Add(new HostResource("Spazio per i dati", Bytes(taken), Bytes(drive.TotalSize, unit: false), Math.Clamp((decimal)taken / drive.TotalSize, 0m, 1m)));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
// A disk that cannot be measured is left out rather than shown wrong.
}
return list;
}
/// <summary>A size as people read it: "780 MB", "1,8 GB"; without the unit for the "su 50" after the value.</summary>
public static string Bytes(long bytes, bool unit = true)
{
const decimal giga = 1024m * 1024m * 1024m;
var gb = bytes / giga;
if (!unit)
{
return Format.Number(gb, gb >= 10m ? 0 : 1);
}
return gb >= 1m ? Format.Number(gb, 1) + " GB" : Format.Number(Math.Max(1m, bytes / (1024m * 1024m))) + " MB";
}
private static string When(DateTimeOffset moment, DateTimeOffset now, TimeZoneInfo zone)
{
var text = Format.ShortDate(moment, now, zone);
return text.StartsWith("Oggi ", StringComparison.Ordinal) ? "alle " + text["Oggi ".Length..] : text.StartsWith("Ieri ", StringComparison.Ordinal) ? "ieri alle " + text["Ieri ".Length..] : "del " + text;
}
private static string Ago(TimeSpan elapsed) => elapsed.TotalSeconds < 60 ? $"{Math.Max(0, (int)elapsed.TotalSeconds)} s fa" : Format.Ago(elapsed);
/// <summary>The time alone within a day, otherwise the day too: "15:35", "Dom 03:00".</summary>
public static string JobTime(DateTimeOffset due, DateTimeOffset now, TimeZoneInfo zone)
{
var local = TimeZoneInfo.ConvertTime(due, zone);
var time = local.ToString("HH:mm", _it);
return due - now < TimeSpan.FromHours(24) ? time : _days[(int)local.DayOfWeek] + " " + time;
}
private static decimal Dec(JsonElement element, string name) => decimal.Parse(element.GetProperty(name).GetString()!, _it);
/// <summary>The processor used by this process between two looks, as a share of all cores.</summary>
private static class CpuSampler
{
private static readonly Lock _gate = new();
private static (long Ticks, TimeSpan Cpu)? _last;
public static decimal Share()
{
using var process = Process.GetCurrentProcess();
var cpu = process.TotalProcessorTime;
var ticks = Stopwatch.GetTimestamp();
lock (_gate)
{
TimeSpan wall;
TimeSpan used;
if (_last is { } last && Stopwatch.GetElapsedTime(last.Ticks, ticks) >= TimeSpan.FromSeconds(1))
{
wall = Stopwatch.GetElapsedTime(last.Ticks, ticks);
used = cpu - last.Cpu;
}
else
{
// First look, or two looks too close together: the average since the process started.
wall = Uptime(process);
used = cpu;
}
_last = (ticks, cpu);
var share = wall <= TimeSpan.Zero ? 0d : used.TotalMilliseconds / (wall.TotalMilliseconds * Environment.ProcessorCount);
return Math.Clamp((decimal)share, 0m, 1m);
}
}
// A measure of the process, not a business time: the system clock against the process's own start, since the
// injected clock may stand still (demo) or run in another world (tests).
private static TimeSpan Uptime(Process process) => DateTime.UtcNow - process.StartTime.ToUniversalTime();
}
}
+176
View File
@@ -0,0 +1,176 @@
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Notifications;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as
/// the Panoramica: one world, the simulated one until there is a real account.
/// </summary>
internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk
{
private const string By = "Telegram";
private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco.");
private TimeZoneInfo Zone => host.Config.TimeZone;
public async Task<string> StatusAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" })
.Append(" · solo denaro finto").AppendLine(".");
if (overview.HasData)
{
var today = overview.Cells[0];
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true))
.Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(").");
}
text.Append(Positions(overview.Positions, overview.PositionsWithoutStop));
if (overview.OpenOrders > 0)
{
text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso.");
}
text.AppendLine();
if (overview.Next.Count > 0 && overview.Next[0] is var next)
{
text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine(".");
}
return text.ToString().TrimEnd();
}
public async Task<string> PositionsAsync(CancellationToken cancellationToken)
{
var services = Services;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " +
"JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol",
r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"),
Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken)
.ConfigureAwait(false);
var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)];
if (rows.Count == 0)
{
return "Nessuna posizione aperta.";
}
var text = new StringBuilder();
foreach (var r in rows)
{
var last = r.Last ?? r.Average;
var gain = (last - r.Average) * r.Quantity;
text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency))
.Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ")
.Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP")
.Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine();
}
return text.ToString().TrimEnd();
}
public async Task<string> TodayAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var local = TimeZoneInfo.ConvertTime(now, Zone);
var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime();
var entries = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at",
r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false);
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder();
if (overview.HasData)
{
text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true))
.AppendLine(").");
}
if (entries.Count == 0)
{
text.Append("Nessun ordine oggi.");
return text.ToString();
}
const int Shown = 15;
foreach (var e in entries.TakeLast(Shown))
{
text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text);
}
if (entries.Count > Shown)
{
text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario.");
}
return text.ToString().TrimEnd();
}
public Task<string> PauseAsync(CancellationToken cancellationToken) =>
CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken);
public Task<string> ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken);
public Task<string> StopAllAsync(CancellationToken cancellationToken) =>
CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.",
cancellationToken);
/// <summary>The morning summary (SPEC 14): the night, the positions, what comes today.</summary>
public async Task<string> MorningAsync(CancellationToken cancellationToken)
{
var services = Services;
var now = host.Clock.UtcNow;
var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false);
var text = new StringBuilder("Buongiorno.").AppendLine();
if (overview.HasData)
{
text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true))
.AppendLine(".");
}
text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop));
var local = TimeZoneInfo.ConvertTime(now, Zone).Date;
var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(200)
.Where(u => u.IsMove && TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local)
.Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description)
.ToList();
if (today.Count > 0)
{
text.AppendLine("Oggi:");
foreach (var line in today)
{
text.AppendLine(line);
}
}
return text.ToString().TrimEnd();
}
private static string Positions(int count, int withoutStop) => count switch
{
0 => "Nessuna posizione aperta.",
1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.",
_ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.",
};
private async Task<string> CommandAsync(string command, string done, CancellationToken cancellationToken)
{
if (host.IsDemo)
{
return "Nella modalità dimostrativa il bot non si comanda.";
}
var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false);
return ok ? done : message;
}
}
Loaded 100 of 372 files, more files were not shown because too many files have changed in this diff. Show more