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);
}
+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());
}
}
+23
View File
@@ -5,6 +5,7 @@ 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;
@@ -138,6 +139,28 @@ internal static partial class Endpoints
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 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));
+6
View File
@@ -6,6 +6,12 @@ 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);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;
+8
View File
@@ -67,4 +67,12 @@ internal sealed record ServerOverrides
/// <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; }
}