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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 15:42:10 +01:00
1 parent 49ed73e6f6
commit 1e71038209
10 files changed
+898 -6

No files matched your search

+44 -2
View File
@@ -1,5 +1,6 @@
using Anubis.Access;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
@@ -34,7 +35,8 @@ public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Id
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);
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler,
MarketDataService? MarketData = null);
/// <summary>
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
@@ -60,6 +62,7 @@ internal sealed partial class AnubisHost(
private Database? _db;
private Task? _schedulerLoop;
private CancellationTokenSource? _schedulerStop;
private MarketDataService? _market;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
@@ -280,7 +283,10 @@ internal sealed partial class AnubisHost(
}
var scheduler = new Scheduler(clock, bus);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler);
_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);
StartScheduler(scheduler, backups);
SetStatus(HostMode.Ready, null);
}
@@ -375,17 +381,32 @@ internal sealed partial class AnubisHost(
Wake();
}
/// <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");
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() ?? [])
{
scheduler.Add(job);
}
_schedulerStop = new CancellationTokenSource();
var token = _schedulerStop.Token;
var market = _market;
_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);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
@@ -394,10 +415,26 @@ internal sealed partial class AnubisHost(
{
}
await collecting.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);
}
}
// 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)
{
@@ -449,6 +486,8 @@ internal sealed partial class AnubisHost(
_schedulerStop.Dispose();
_schedulerStop = null;
_schedulerLoop = null;
_market?.Dispose();
_market = null;
}
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
@@ -485,6 +524,9 @@ internal sealed partial class AnubisHost(
[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.Warning, Message = "Could not record the run of job {Job}")]
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
}