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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 20:29:02 +01:00
1 parent 74d4c4fa6f
commit 1419457fe4
50 files changed
+7327 -5

No files matched your search

+41 -3
View File
@@ -4,6 +4,7 @@ using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Trading;
namespace Anubis.Server;
@@ -36,7 +37,7 @@ internal sealed record HostChanged(HostMode Mode);
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler,
MarketDataService? MarketData = null);
MarketDataService? MarketData = null, TradingService? Trading = null);
/// <summary>
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
@@ -63,6 +64,7 @@ internal sealed partial class AnubisHost(
private Task? _schedulerLoop;
private CancellationTokenSource? _schedulerStop;
private MarketDataService? _market;
private TradingService? _trading;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
@@ -286,7 +288,11 @@ internal sealed partial class AnubisHost(
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger)
: null;
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market);
_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)
: null;
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading);
StartScheduler(scheduler, backups);
SetStatus(HostMode.Ready, null);
}
@@ -389,12 +395,20 @@ internal sealed partial class AnubisHost(
!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)
{
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2) });
foreach (var job in _market?.Jobs() ?? [])
foreach (var job in (_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []))
{
scheduler.Add(job);
}
@@ -402,11 +416,13 @@ internal sealed partial class AnubisHost(
_schedulerStop = new CancellationTokenSource();
var token = _schedulerStop.Token;
var market = _market;
var trading = _trading;
_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);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
@@ -416,6 +432,7 @@ internal sealed partial class AnubisHost(
}
await collecting.ConfigureAwait(false);
await dealing.ConfigureAwait(false);
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
@@ -435,6 +452,22 @@ internal sealed partial class AnubisHost(
}
}
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)
{
@@ -488,6 +521,8 @@ internal sealed partial class AnubisHost(
_schedulerLoop = null;
_market?.Dispose();
_market = null;
_trading?.Dispose();
_trading = null;
}
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
@@ -527,6 +562,9 @@ internal sealed partial class AnubisHost(
[LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")]
private static partial void LogMarketDataFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Error, Message = "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);
}
+3
View File
@@ -75,4 +75,7 @@ internal sealed record ServerOverrides
public HttpMessageHandler? MarketHttp { get; init; }
public Func<Anubis.Brokers.IWebSocketTransport>? MarketSockets { 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; }
}