Commit Graph
64 Commits
Author SHA1 Message Date
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
fase-6
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
fase-5
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
fase-4
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
fase-3
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
fase-2
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