Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.
@(Shell.IsDemo ? "Nella modalità dimostrativa i dati di mercato non si scaricano." : "La raccolta dei dati di mercato è spenta (ANUBIS_MARKET_DATA).")
+ } + else + { +| Fonte | Stato | Ultima risposta | Note |
|---|---|---|---|
| @SourceName(s.Source) | +@(!s.Enabled ? "spenta" : s.LastError is null ? "attiva" : "in errore") | +@(s.LastSuccessAt is { } at ? Format.ShortDate(at, Shell.Now, Shell.Zone) : "—") | +@(s.LastError ?? s.Note) | +
Rapporto sulla qualità dei dati degli ultimi 30 giorni
+ +FetchQuoteAsync(string symbol, CancellationToken cancellationToken) + { + using var json = await GetAsync(_options.DataUrl, "/v2/stocks/quotes/latest?feed=iex&symbols=" + Uri.EscapeDataString(symbol), cancellationToken) + .ConfigureAwait(false); + if (!json.RootElement.GetProperty("quotes").TryGetProperty(symbol, out var item)) + { + throw new MarketDataException("Alpaca: nessuna quotazione per " + symbol, retryable: false); + } + + return ReadQuote(symbol, item); + } + + ///Exchange sessions from + public async Taskto , in UTC (times are New York's). > FetchCalendarAsync(DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + using var json = await GetAsync(_options.TradingUrl, + $"/v2/calendar?start={first:yyyy-MM-dd}&end={last:yyyy-MM-dd}", cancellationToken).ConfigureAwait(false); + return json.RootElement.EnumerateArray().Select(ReadSession).ToList(); + } + + public static MarketSession ReadSession(JsonElement item) + { + var date = DateOnly.ParseExact(Text(item, "date"), "yyyy-MM-dd", CultureInfo.InvariantCulture); + return new MarketSession(date, NewYorkMoment(date, Text(item, "open")), NewYorkMoment(date, Text(item, "close"))); + } + + public async Task FetchClockAsync(CancellationToken cancellationToken) + { + using var json = await GetAsync(_options.TradingUrl, "/v2/clock", cancellationToken).ConfigureAwait(false); + return ReadClock(json.RootElement); + } + + public static MarketClock ReadClock(JsonElement item) => new( + Moment(Text(item, "timestamp")), item.GetProperty("is_open").GetBoolean(), Moment(Text(item, "next_open")), Moment(Text(item, "next_close"))); + + /// Splits, dividends and symbol changes with ex-date (process date for name changes) in the range (SPEC 6.10). + public async Task> FetchCorporateActionsAsync(IReadOnlyCollection symbols, DateOnly first, DateOnly last, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(symbols); + var actions = new List (); + foreach (var chunk in symbols.Distinct().Chunk(SymbolsPerRequest)) + { + string? page = null; + do + { + var path = $"/v1/corporate-actions?symbols={Uri.EscapeDataString(string.Join(',', chunk))}&types={ActionTypes}" + + $"&start={first:yyyy-MM-dd}&end={last:yyyy-MM-dd}&limit=1000" + (page is null ? "" : "&page_token=" + Uri.EscapeDataString(page)); + using var json = await GetAsync(_options.DataUrl, path, cancellationToken).ConfigureAwait(false); + actions.AddRange(ReadCorporateActions(json.RootElement.GetProperty("corporate_actions"))); + page = NextPage(json.RootElement); + } + while (page is not null); + } + + return actions; + } + + /// The + public static IReadOnlyListcorporate_actions object of the response, grouped by type.ReadCorporateActions(JsonElement groups) + { + var list = new List (); + foreach (var group in groups.EnumerateObject()) + { + foreach (var item in group.Value.EnumerateArray()) + { + var key = "alpaca:" + Text(item, "id"); + switch (group.Name) + { + case "forward_splits" or "reverse_splits" or "forward_split" or "reverse_split": + var oldRate = Decimal(item, "old_rate"); + var newRate = Decimal(item, "new_rate"); + if (oldRate > 0 && newRate > 0) + { + list.Add(new CorporateAction(Text(item, "symbol"), CorporateActionKinds.Split, Day(item, "ex_date"), Venues.Alpaca, key) + { + Ratio = newRate / oldRate, + NewSymbol = Text(item, "new_symbol") is { Length: > 0 } s ? s : null, + }); + } + + break; + case "cash_dividends" or "cash_dividend": + list.Add(new CorporateAction(Text(item, "symbol"), CorporateActionKinds.CashDividend, Day(item, "ex_date"), Venues.Alpaca, key) + { + CashAmount = Decimal(item, "rate"), + Currency = Text(item, "currency") is { Length: > 0 } c ? c : "USD", + }); + break; + case "stock_dividends" or "stock_dividend": + list.Add(new CorporateAction(Text(item, "symbol"), CorporateActionKinds.StockDividend, Day(item, "ex_date"), Venues.Alpaca, key) + { + Ratio = 1m + Decimal(item, "rate"), + }); + break; + case "name_changes" or "name_change": + list.Add(new CorporateAction(Text(item, "old_symbol"), CorporateActionKinds.SymbolChange, Day(item, "process_date"), Venues.Alpaca, key) + { + NewSymbol = Text(item, "new_symbol"), + }); + break; + default: + break; + } + } + } + + return list; + } + + public async IAsyncEnumerable StreamAsync(IReadOnlyCollection symbols, [EnumeratorCancellation] CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(symbols); + var credentials = RequireCredentials(); + if (symbols.Count > _options.MaxStreamSymbols) + { + throw new MarketDataException( + $"Alpaca: il piano gratuito segue al massimo {_options.MaxStreamSymbols} titoli dal vivo, ne sono stati chiesti {symbols.Count}.", retryable: false); + } + + if (symbols.Count == 0) + { + yield break; + } + + await using var socket = _sockets(); + await socket.ConnectAsync(_options.StreamUrl, null, cancellationToken).ConfigureAwait(false); + await socket.SendAsync(JsonSerializer.Serialize(new { action = "auth", key = credentials.KeyId, secret = credentials.Secret }), cancellationToken) + .ConfigureAwait(false); + await socket.SendAsync(JsonSerializer.Serialize(new { action = "subscribe", bars = symbols, quotes = symbols }), cancellationToken).ConfigureAwait(false); + while (await socket.ReceiveAsync(cancellationToken).ConfigureAwait(false) is { } message) + { + foreach (var item in ParseStreamMessage(message)) + { + yield return item; + } + } + } + + /// Events in one stream message (always an array). Control messages give none; errors stop the feed. + public static IReadOnlyListParseStreamMessage(string message) + { + using var json = JsonDocument.Parse(message); + var events = new List (); + foreach (var item in json.RootElement.EnumerateArray()) + { + var symbol = Text(item, "S"); + switch (Text(item, "T")) + { + case "b": + events.Add(new BarEvent(symbol, ReadBar(item), Closed: true)); + break; + case "q": + events.Add(new QuoteEvent(ReadQuote(symbol, item))); + break; + case "t": + events.Add(new TradeEvent(symbol, Moment(Text(item, "t")), Decimal(item, "p"), Decimal(item, "s"))); + break; + case "error": + var code = item.TryGetProperty("code", out var c) ? c.GetRawText() : "?"; + throw new MarketDataException($"Alpaca: errore del flusso {code}: {Text(item, "msg")}", + retryable: code is "406" or "407" or "500"); + default: + break; + } + } + + return events; + } + + private async Task >> BarsAsync(IReadOnlyCollection symbols, string timeframe, string feed, string adjustment, + DateTimeOffset start, DateTimeOffset end, CancellationToken cancellationToken) + { + var result = new Dictionary >(StringComparer.Ordinal); + if (end < start) + { + return result; + } + + string? page = null; + do + { + // The feed is always explicit: its default changes with the endpoint and the subscription (API-NOTES). + var path = $"/v2/stocks/bars?symbols={Uri.EscapeDataString(string.Join(',', symbols))}&timeframe={timeframe}" + + $"&start={Rfc3339(start)}&end={Rfc3339(end)}&feed={feed}&adjustment={adjustment}&limit=10000&sort=asc" + + (page is null ? "" : "&page_token=" + Uri.EscapeDataString(page)); + using var json = await GetAsync(_options.DataUrl, path, cancellationToken).ConfigureAwait(false); + if (json.RootElement.TryGetProperty("bars", out var bars) && bars.ValueKind == JsonValueKind.Object) + { + foreach (var symbol in bars.EnumerateObject()) + { + if (!result.TryGetValue(symbol.Name, out var list)) + { + result[symbol.Name] = list = []; + } + + list.AddRange(symbol.Value.EnumerateArray().Select(ReadBar)); + } + } + + page = NextPage(json.RootElement); + } + while (page is not null); + + return result; + } + + private async Task GetAsync(Uri host, string pathAndQuery, CancellationToken cancellationToken) + { + var credentials = RequireCredentials(); + var headers = new Dictionary { ["APCA-API-KEY-ID"] = credentials.KeyId, ["APCA-API-SECRET-KEY"] = credentials.Secret }; + var text = await _http.GetStringAsync(new Uri(host, pathAndQuery), _limiter, headers, cancellationToken).ConfigureAwait(false); + return JsonDocument.Parse(text); + } + + private AlpacaCredentials RequireCredentials() => + _credentials ?? throw new MarketDataException("Alpaca: mancano le chiavi. La parte azionaria resta in attesa finché non le inserisci.", retryable: false); + + internal static Bar ReadBar(JsonElement item) => + new(Moment(Text(item, "t")), item.GetProperty("o").GetDouble(), item.GetProperty("h").GetDouble(), item.GetProperty("l").GetDouble(), + item.GetProperty("c").GetDouble(), item.GetProperty("v").GetDouble()); + + private static Quote ReadQuote(string symbol, JsonElement item) => + new(symbol, Decimal(item, "bp"), Decimal(item, "ap"), Moment(Text(item, "t"))) + { + BidSize = Decimal(item, "bs"), + AskSize = Decimal(item, "as"), + }; + + /// A daily bar's time is midnight in New York expressed in UTC: its day is the New York date. + public static DateOnly NewYorkDay(DateTimeOffset moment) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, NewYork).DateTime); + + private static DateTimeOffset DayStart(DateOnly day) + { + var local = day.ToDateTime(TimeOnly.MinValue); + return new DateTimeOffset(local, NewYork.GetUtcOffset(local)).ToUniversalTime(); + } + + private static DateTimeOffset NewYorkMoment(DateOnly day, string time) + { + var local = day.ToDateTime(TimeOnly.ParseExact(time, "HH:mm", CultureInfo.InvariantCulture)); + return new DateTimeOffset(local, NewYork.GetUtcOffset(local)).ToUniversalTime(); + } + + private static string Rfc3339(DateTimeOffset moment) => + Uri.EscapeDataString(moment.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'", CultureInfo.InvariantCulture)); + + private static string? NextPage(JsonElement root) => + root.TryGetProperty("next_page_token", out var token) && token.ValueKind == JsonValueKind.String && token.GetString() is { Length: > 0 } t ? t : null; + + private static DateTimeOffset Moment(string text) => + DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); + + private static DateOnly Day(JsonElement item, string name) => DateOnly.ParseExact(Text(item, name), "yyyy-MM-dd", CultureInfo.InvariantCulture); + + private static string Text(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; + + private static decimal Decimal(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number ? value.GetDecimal() : 0m; +} diff --git a/src/Anubis/Brokers/Http.cs b/src/Anubis/Brokers/Http.cs new file mode 100644 index 0000000..862e263 --- /dev/null +++ b/src/Anubis/Brokers/Http.cs @@ -0,0 +1,258 @@ +using System.Net; +using System.Net.WebSockets; +using System.Text; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Brokers; + +///+/// At most +public sealed class RateLimiter(IClock clock, int permits, TimeSpan window) +{ + private readonly Lock _gate = new(); + private readonly Queuepermits requests in any window ofwindow , on the injected clock. Every source keeps under +/// its published limits (SPEC 2.2: limits are never bypassed). +///_recent = new(); + + public int Permits { get; } = permits > 0 ? permits : throw new ArgumentOutOfRangeException(nameof(permits)); + + public TimeSpan Window { get; } = window; + + public async Task WaitAsync(CancellationToken cancellationToken) + { + while (true) + { + DateTimeOffset reopensAt; + lock (_gate) + { + var now = clock.UtcNow; + while (_recent.Count > 0 && now - _recent.Peek() >= Window) + { + _recent.Dequeue(); + } + + if (_recent.Count < Permits) + { + _recent.Enqueue(now); + return; + } + + reopensAt = _recent.Peek() + Window; + } + + await clock.WaitUntilAsync(reopensAt, cancellationToken).ConfigureAwait(false); + } + } +} + +/// +/// GET requests with a rate limiter and a few retries on 429 and server errors, waiting on the injected clock. +/// Errors never carry request headers, so keys and signatures do not reach the logs (trap 17). +/// +public sealed class ApiHttp(HttpClient http, IClock clock, string sourceName) +{ + public const int Attempts = 4; + + public string SourceName { get; } = sourceName; + + public HttpClient Client { get; } = http; + + public async TaskGetStringAsync(Uri url, RateLimiter? limiter, IReadOnlyDictionary ? headers, CancellationToken cancellationToken) + { + var bytes = await GetBytesAsync(url, limiter, headers, cancellationToken).ConfigureAwait(false); + return Encoding.UTF8.GetString(bytes ?? throw new MarketDataException($"{SourceName}: nessun dato a {Describe(url)}.", retryable: false)); + } + + /// The body of a successful response; null for 404, which several archives use for "not published yet". + public async TaskGetBytesAsync(Uri url, RateLimiter? limiter, IReadOnlyDictionary ? headers, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(url); + for (var attempt = 1; ; attempt++) + { + if (limiter is not null) + { + await limiter.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + using var request = new HttpRequestMessage(HttpMethod.Get, url); + foreach (var (name, value) in headers ?? new Dictionary ()) + { + request.Headers.TryAddWithoutValidation(name, value); + } + + HttpResponseMessage response; + try + { + response = await Client.SendAsync(request, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException ex) when (attempt < Attempts) + { + _ = ex; + await BackOffAsync(attempt, null, cancellationToken).ConfigureAwait(false); + continue; + } + catch (HttpRequestException ex) + { + throw new MarketDataException($"{SourceName}: rete non raggiungibile ({Describe(url)}).", retryable: true, ex); + } + catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested) + { + if (attempt < Attempts) + { + await BackOffAsync(attempt, null, cancellationToken).ConfigureAwait(false); + continue; + } + + throw new MarketDataException($"{SourceName}: nessuna risposta entro il tempo massimo ({Describe(url)}).", retryable: true, ex); + } + + using (response) + { + if (response.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + + if (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500) + { + if (attempt < Attempts) + { + await BackOffAsync(attempt, RetryAfter(response), cancellationToken).ConfigureAwait(false); + continue; + } + + throw new MarketDataException($"{SourceName}: risposta {(int)response.StatusCode} ripetuta da {Describe(url)}.", retryable: true); + } + + if (!response.IsSuccessStatusCode) + { + var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + throw new MarketDataException( + $"{SourceName}: risposta {(int)response.StatusCode} da {Describe(url)}: {Redactor.Redact(Shorten(text))}", + retryable: response.StatusCode is HttpStatusCode.RequestTimeout); + } + + return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + } + } + } + + /// Waits 2, 4, 8 seconds…, or what the server asked for, on the injected clock. + public Task BackOffAsync(int attempt, TimeSpan? requested, CancellationToken cancellationToken) + { + var wait = requested ?? TimeSpan.FromSeconds(Math.Pow(2, attempt)); + if (wait > TimeSpan.FromMinutes(2)) + { + wait = TimeSpan.FromMinutes(2); + } + + return clock.WaitUntilAsync(clock.UtcNow + wait, cancellationToken); + } + + ///The address without its query, which may carry a key (FRED, Finnhub). + public static string Describe(Uri url) => url?.GetLeftPart(UriPartial.Path) ?? ""; + + private TimeSpan? RetryAfter(HttpResponseMessage response) + { + if (response.Headers.RetryAfter?.Delta is { } delta) + { + return delta; + } + + // Alpaca: X-RateLimit-Reset is the UNIX second at which the window reopens. + if (response.Headers.TryGetValues("X-RateLimit-Reset", out var values) + && long.TryParse(values.FirstOrDefault(), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var reset)) + { + var wait = DateTimeOffset.FromUnixTimeSeconds(reset) - clock.UtcNow; + return wait > TimeSpan.Zero ? wait + TimeSpan.FromSeconds(1) : TimeSpan.FromSeconds(1); + } + + return null; + } + + private static string Shorten(string text) => text.Length <= 300 ? text : text[..300] + "…"; +} + +///A text WebSocket. Behind an interface so tests can play a recorded conversation. +public interface IWebSocketTransport : IAsyncDisposable +{ + Task ConnectAsync(Uri url, IReadOnlyDictionary? headers, CancellationToken cancellationToken); + + Task SendAsync(string text, CancellationToken cancellationToken); + + /// The next text message, or null when the connection closed. + TaskReceiveAsync(CancellationToken cancellationToken); +} + +/// The real transport on +public sealed class ClientWebSocketTransport : IWebSocketTransport +{ + private readonly ClientWebSocket _socket = new(); + + public async Task ConnectAsync(Uri url, IReadOnlyDictionary. ? headers, CancellationToken cancellationToken) + { + foreach (var (name, value) in headers ?? new Dictionary ()) + { + _socket.Options.SetRequestHeader(name, value); + } + + _socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); + await _socket.ConnectAsync(url, cancellationToken).ConfigureAwait(false); + } + + public Task SendAsync(string text, CancellationToken cancellationToken) => + _socket.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, endOfMessage: true, cancellationToken); + + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + var buffer = new byte[16 * 1024]; + using var message = new MemoryStream(); + while (true) + { + WebSocketReceiveResult result; + try + { + result = await _socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (WebSocketException) + { + return null; + } + + if (result.MessageType == WebSocketMessageType.Close) + { + return null; + } + + message.Write(buffer, 0, result.Count); + if (message.Length > 4 * 1024 * 1024) + { + return null; + } + + if (result.EndOfMessage) + { + return Encoding.UTF8.GetString(message.GetBuffer(), 0, (int)message.Length); + } + } + } + + public async ValueTask DisposeAsync() + { + if (_socket.State == WebSocketState.Open) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + try + { + await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "bye", timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is WebSocketException or OperationCanceledException) + { + // Closing is a courtesy: the socket is dropped anyway. + } + } + + _socket.Dispose(); + } +} diff --git a/src/Anubis/Brokers/Okx.cs b/src/Anubis/Brokers/Okx.cs new file mode 100644 index 0000000..df27db2 --- /dev/null +++ b/src/Anubis/Brokers/Okx.cs @@ -0,0 +1,452 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Brokers; + +/// Addresses of OKX Europe (SPEC 4.2, docs re-read on 10/11/2026: API-NOTES). +public sealed record OkxOptions +{ + public Uri RestUrl { get; init; } = new("https://eea.okx.com"); + + public Uri PublicStreamUrl { get; init; } = new("wss://wseea.okx.com/ws/v5/public"); + + ///Candle channels live here, not on the public stream (error 60018 otherwise). + public Uri BusinessStreamUrl { get; init; } = new("wss://wseea.okx.com/ws/v5/business"); + + ///Demo trading: same REST address with the + public bool Demo { get; init; } + + ///x-simulated-trading: 1 header, other stream host.Quote currency traded. Only EUR: USDT is not tradable in Europe (trap 14) and USDC pairs are not used (SPEC 8.1). + public string QuoteCurrency { get; init; } = "EUR"; + + ///Seconds without messages before the stream sends + public TimeSpan PingAfter { get; init; } = TimeSpan.FromSeconds(20); + + public static OkxOptions ForDemo() => new() + { + Demo = true, + PublicStreamUrl = new("wss://wseeapap.okx.com/ws/v5/public"), + BusinessStreamUrl = new("wss://wseeapap.okx.com/ws/v5/business"), + }; +} + +///ping ; the server drops a silent connection after 30.Key, secret and passphrase of an OKX API key. Never logged (trap 17). +public sealed record OkxCredentials(string Key, string Secret, string Passphrase) +{ + public override string ToString() => "OkxCredentials(***)"; +} + +///+/// The REST signature of OKX: Base64(HMAC-SHA256(secret, timestamp + method + path with query + body)), with the +/// timestamp in ISO 8601 UTC with milliseconds. Used by the order part in Phase 3; written here with its test. +/// +public static class OkxSigner +{ + public static string Timestamp(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture); + + public static string Sign(string timestamp, string method, string requestPath, string body, string secret) + { + ArgumentNullException.ThrowIfNull(secret); + var payload = Encoding.UTF8.GetBytes(timestamp + method.ToUpperInvariant() + requestPath + body); + return Convert.ToBase64String(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), payload)); + } + + public static DictionaryHeaders(OkxCredentials credentials, DateTimeOffset at, string method, string requestPath, string body, bool demo) + { + ArgumentNullException.ThrowIfNull(credentials); + var timestamp = Timestamp(at); + var headers = new Dictionary + { + ["OK-ACCESS-KEY"] = credentials.Key, + ["OK-ACCESS-SIGN"] = Sign(timestamp, method, requestPath, body, credentials.Secret), + ["OK-ACCESS-TIMESTAMP"] = timestamp, + ["OK-ACCESS-PASSPHRASE"] = credentials.Passphrase, + }; + if (demo) + { + headers["x-simulated-trading"] = "1"; + } + + return headers; + } +} + +/// Funding rate of a perpetual swap: an indicator of crowding (SPEC 10.4). +public sealed record FundingRate(string InstrumentId, double Rate, DateTimeOffset FundingTime, TimeSpan Interval, DateTimeOffset At); + +///Open interest of a perpetual swap, in coins and dollars. +public sealed record OpenInterest(string InstrumentId, double Coins, double Usd, DateTimeOffset At); + +///+/// The data part of the OKX Europe adapter (issue #18), written in house: instruments with their rules, daily +/// candles that close at 00:00 UTC ( +public sealed class OkxClient : IMarketDataSource +{ + ///1Dutc , trap 23), one-minute candles, ticker and the live streams. +/// Every answer carriescode : OKX reports errors with HTTP 200, so the code is what counts. +///Daily bars: + public const string DailyBar = "1Dutc"; + + ///1D opens at 16:00 UTC (Hong Kong midnight),1Dutc at 00:00 UTC.Rows per candle request (the documented maximum for both endpoints). + public const int CandleLimit = 300; + + private readonly ApiHttp _http; + private readonly IClock _clock; + private readonly OkxOptions _options; + private readonly Func_sockets; + + // Published limits, with some room: candles 40/2s, history 20/2s, instruments, ticker 20/2s, funding 10/2s. + private readonly RateLimiter _candles; + private readonly RateLimiter _history; + private readonly RateLimiter _public; + private readonly RateLimiter _derivatives; + + public OkxClient(HttpClient http, IClock clock, OkxOptions? options = null, Func ? sockets = null) + { + _clock = clock; + _options = options ?? new OkxOptions(); + _http = new ApiHttp(http, clock, "OKX"); + _sockets = sockets ?? (() => new ClientWebSocketTransport()); + _candles = new RateLimiter(clock, 30, TimeSpan.FromSeconds(2)); + _history = new RateLimiter(clock, 15, TimeSpan.FromSeconds(2)); + _public = new RateLimiter(clock, 15, TimeSpan.FromSeconds(2)); + _derivatives = new RateLimiter(clock, 8, TimeSpan.FromSeconds(2)); + } + + public string Venue => Venues.Okx; + + public async Task > ListInstrumentsAsync(CancellationToken cancellationToken) + { + using var json = await GetAsync("/api/v5/public/instruments?instType=SPOT", _public, cancellationToken).ConfigureAwait(false); + var list = new List (); + foreach (var item in json.RootElement.GetProperty("data").EnumerateArray()) + { + var quote = Text(item, "quoteCcy"); + if (quote != _options.QuoteCurrency) + { + continue; + } + + var baseCcy = Text(item, "baseCcy"); + list.Add(new InstrumentSpec(Venues.Okx, Text(item, "instId"), baseCcy + "/" + quote, AssetClasses.Crypto, quote) + { + BaseCurrency = baseCcy, + TickSize = DecimalOrNull(item, "tickSz"), + LotSize = DecimalOrNull(item, "lotSz"), + MinSize = DecimalOrNull(item, "minSz"), + Status = Text(item, "state"), + ListedAt = Text(item, "listTime") is { Length: > 0 } ms ? Millis(ms) : null, + }); + } + + return list; + } + + public async Task > FetchDailyBarsAsync(string symbol, DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + var from = QualityChecks.Midnight(first); + var until = QualityChecks.Midnight(last.AddDays(1)); + var rows = await CandlesAsync(symbol, DailyBar, from, until, useHistory: true, cancellationToken).ConfigureAwait(false); + var bars = new List (rows.Count); + foreach (var row in rows) + { + if (row.OpensAt.TimeOfDay != TimeSpan.Zero) + { + throw new MarketDataException($"OKX: la candela giornaliera di {symbol} apre alle {row.OpensAt:HH:mm} UTC e non a mezzanotte.", retryable: false); + } + + bars.Add(new DailyBar(DateOnly.FromDateTime(row.OpensAt.UtcDateTime), row.Open, row.High, row.Low, row.Close, row.Volume) + { + QuoteVolume = row.QuoteVolume, + }); + } + + return bars; + } + + public async Task > FetchMinuteBarsAsync(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken cancellationToken) + { + // The recent endpoint holds the last 1,440 candles; older ones come from the history endpoint. + var useHistory = start < _clock.UtcNow.AddMinutes(-1400); + return await CandlesAsync(symbol, "1m", start, until, useHistory, cancellationToken).ConfigureAwait(false); + } + + public async Task FetchQuoteAsync(string symbol, CancellationToken cancellationToken) + { + using var json = await GetAsync("/api/v5/market/ticker?instId=" + Uri.EscapeDataString(symbol), _public, cancellationToken).ConfigureAwait(false); + var data = json.RootElement.GetProperty("data"); + if (data.GetArrayLength() == 0) + { + throw new MarketDataException("OKX: nessuna quotazione per " + symbol, retryable: false); + } + + return ReadTicker(data[0]); + } + + ///Funding rate of a perpetual swap, e.g. + public async TaskBTC-USDT-SWAP : public data, used only as an indicator.FetchFundingRateAsync(string swap, CancellationToken cancellationToken) + { + using var json = await GetAsync("/api/v5/public/funding-rate?instId=" + Uri.EscapeDataString(swap), _derivatives, cancellationToken).ConfigureAwait(false); + var item = json.RootElement.GetProperty("data")[0]; + var fundingTime = Millis(Text(item, "fundingTime")); + var next = Text(item, "nextFundingTime") is { Length: > 0 } n ? Millis(n) : fundingTime.AddHours(8); + return new FundingRate(swap, Double(item, "fundingRate"), fundingTime, next - fundingTime, Millis(Text(item, "ts"))); + } + + public async Task FetchOpenInterestAsync(string swap, CancellationToken cancellationToken) + { + using var json = await GetAsync("/api/v5/public/open-interest?instType=SWAP&instId=" + Uri.EscapeDataString(swap), _derivatives, cancellationToken) + .ConfigureAwait(false); + var item = json.RootElement.GetProperty("data")[0]; + return new OpenInterest(swap, Double(item, "oiCcy"), Double(item, "oiUsd"), Millis(Text(item, "ts"))); + } + + /// Server time, to check the local clock. + public async TaskServerTimeAsync(CancellationToken cancellationToken) + { + using var json = await GetAsync("/api/v5/public/time", _public, cancellationToken).ConfigureAwait(false); + return Millis(Text(json.RootElement.GetProperty("data")[0], "ts")); + } + + public async IAsyncEnumerable StreamAsync(IReadOnlyCollection symbols, [EnumeratorCancellation] CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(symbols); + if (symbols.Count == 0) + { + yield break; + } + + var channel = Channel.CreateUnbounded (new UnboundedChannelOptions { SingleReader = true }); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var tickers = RunSocketAsync(_options.PublicStreamUrl, symbols.Select(s => ("tickers", s)), channel.Writer, stop.Token); + var candles = RunSocketAsync(_options.BusinessStreamUrl, symbols.Select(s => ("candle1m", s)), channel.Writer, stop.Token); + + // The feed ends as soon as one of the two connections drops: the collector reconnects both and recovers the gap. + var ended = Task.WhenAny(tickers, candles).ContinueWith(t => channel.Writer.TryComplete(t.Result.Exception?.InnerException), + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + try + { + await foreach (var item in channel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + yield return item; + } + } + finally + { + await stop.CancelAsync().ConfigureAwait(false); + await Task.WhenAll(Quietly(tickers), Quietly(candles), ended).ConfigureAwait(false); + } + } + + private async Task RunSocketAsync(Uri url, IEnumerable<(string Channel, string Symbol)> subscriptions, ChannelWriter writer, CancellationToken cancellationToken) + { + await using var socket = _sockets(); + await socket.ConnectAsync(url, null, cancellationToken).ConfigureAwait(false); + var args = subscriptions.Select(s => new Dictionary { ["channel"] = s.Channel, ["instId"] = s.Symbol }).ToList(); + await socket.SendAsync(JsonSerializer.Serialize(new { id = "1", op = "subscribe", args }), cancellationToken).ConfigureAwait(false); + + var receive = socket.ReceiveAsync(cancellationToken); + var lastMessage = _clock.UtcNow; + var pinged = false; + while (true) + { + using var tick = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var timer = _clock.WaitUntilAsync(lastMessage + _options.PingAfter, tick.Token); + var done = await Task.WhenAny(receive, timer).ConfigureAwait(false); + if (done != timer) + { + await tick.CancelAsync().ConfigureAwait(false); + } + else + { + cancellationToken.ThrowIfCancellationRequested(); + if (pinged) + { + return; // No pong either: the connection is dead even if it looks open (trap 10). + } + + await socket.SendAsync("ping", cancellationToken).ConfigureAwait(false); + pinged = true; + lastMessage = _clock.UtcNow; + continue; + } + + var message = await receive.ConfigureAwait(false); + if (message is null) + { + return; + } + + lastMessage = _clock.UtcNow; + pinged = false; + receive = socket.ReceiveAsync(cancellationToken); + if (message == "pong") + { + continue; + } + + foreach (var item in ParseStreamMessage(message)) + { + // The channel is unbounded, so a write fails only once the other connection has ended the feed. + if (!writer.TryWrite(item)) + { + return; + } + } + } + } + + /// Events in one message of the public or business stream. Subscriptions and notices give none. + public static IReadOnlyListParseStreamMessage(string message) + { + using var json = JsonDocument.Parse(message); + var root = json.RootElement; + if (root.TryGetProperty("event", out var evt)) + { + if (evt.GetString() == "error") + { + throw new MarketDataException($"OKX: errore del flusso {Text(root, "code")}: {Text(root, "msg")}", retryable: false); + } + + return []; + } + + if (!root.TryGetProperty("arg", out var arg) || !root.TryGetProperty("data", out var data)) + { + return []; + } + + var channel = Text(arg, "channel"); + var symbol = Text(arg, "instId"); + var events = new List (); + foreach (var item in data.EnumerateArray()) + { + if (channel == "tickers") + { + events.Add(new QuoteEvent(ReadTicker(item))); + } + else if (channel.StartsWith("candle", StringComparison.Ordinal)) + { + var bar = ReadCandle(item); + events.Add(new BarEvent(symbol, bar.Bar, bar.Confirmed)); + } + } + + return events; + } + + /// Candles opening in [from, until), oldest first, closed only. Pages backwards with + private async Taskafter (rows older than it).> CandlesAsync(string symbol, string bar, DateTimeOffset from, DateTimeOffset until, bool useHistory, CancellationToken cancellationToken) + { + var found = new SortedDictionary
(); + var cursor = until; + while (cursor > from) + { + var path = $"/api/v5/market/{(useHistory ? "history-candles" : "candles")}?instId={Uri.EscapeDataString(symbol)}&bar={bar}" + + $"&after={cursor.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture)}&limit={CandleLimit}"; + using var json = await GetAsync(path, useHistory ? _history : _candles, cancellationToken).ConfigureAwait(false); + var rows = json.RootElement.GetProperty("data"); + if (rows.GetArrayLength() == 0) + { + break; // Before the first candle of the instrument. + } + + var oldest = cursor; + foreach (var row in rows.EnumerateArray()) + { + var candle = ReadCandle(row); + oldest = candle.Bar.OpensAt < oldest ? candle.Bar.OpensAt : oldest; + if (candle.Confirmed && candle.Bar.OpensAt >= from && candle.Bar.OpensAt < until) + { + found[candle.Bar.OpensAt] = candle.Bar; + } + } + + if (oldest >= cursor) + { + break; + } + + cursor = oldest; + } + + return found.Values.ToList(); + } + + private async Task GetAsync(string pathAndQuery, RateLimiter limiter, CancellationToken cancellationToken) + { + var headers = _options.Demo ? new Dictionary { ["x-simulated-trading"] = "1" } : null; + for (var attempt = 1; ; attempt++) + { + var text = await _http.GetStringAsync(new Uri(_options.RestUrl, pathAndQuery), limiter, headers, cancellationToken).ConfigureAwait(false); + var json = JsonDocument.Parse(text); + var code = Text(json.RootElement, "code"); + if (code == "0") + { + return json; + } + + var message = Text(json.RootElement, "msg"); + json.Dispose(); + + // 50011 too many requests, 50013 busy, 50001 unavailable, 50026 system error: wait and retry. + if (code is "50011" or "50013" or "50001" or "50026" && attempt < ApiHttp.Attempts) + { + await _http.BackOffAsync(attempt, null, cancellationToken).ConfigureAwait(false); + continue; + } + + throw new MarketDataException($"OKX: errore {code}: {message}", retryable: code.StartsWith('5') && code.Length == 5 && code[1] == '0'); + } + } + + internal static (Bar Bar, bool Confirmed) ReadCandle(JsonElement row) + { + // [ts, o, h, l, c, vol (base), volCcy, volCcyQuote (quote), confirm] + var bar = new Bar(Millis(row[0].GetString()!), Number(row[1]), Number(row[2]), Number(row[3]), Number(row[4]), Number(row[5])) + { + QuoteVolume = row.GetArrayLength() > 7 && row[7].GetString() is { Length: > 0 } q ? double.Parse(q, CultureInfo.InvariantCulture) : null, + }; + return (bar, row.GetArrayLength() <= 8 || row[8].GetString() == "1"); + } + + private static Quote ReadTicker(JsonElement item) => + new(Text(item, "instId"), DecimalOrNull(item, "bidPx") ?? 0m, DecimalOrNull(item, "askPx") ?? 0m, Millis(Text(item, "ts"))) + { + BidSize = DecimalOrNull(item, "bidSz"), + AskSize = DecimalOrNull(item, "askSz"), + }; + + private static async Task Quietly(Task task) + { + try + { + await task.ConfigureAwait(false); + } + catch (Exception ex) when (ex is OperationCanceledException or MarketDataException or System.Net.WebSockets.WebSocketException or JsonException + or ChannelClosedException or IOException or HttpRequestException or TimeoutException) + { + // Already reported through the channel, or the feed was stopped on purpose. + } + } + + private static DateTimeOffset Millis(string text) => + DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(text, NumberStyles.None, CultureInfo.InvariantCulture)); + + private static string Text(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; + + private static double Number(JsonElement value) => double.Parse(value.GetString()!, CultureInfo.InvariantCulture); + + private static double Double(JsonElement item, string name) => + Text(item, name) is { Length: > 0 } text ? double.Parse(text, CultureInfo.InvariantCulture) : double.NaN; + + private static decimal? DecimalOrNull(JsonElement item, string name) => + Text(item, name) is { Length: > 0 } text ? decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture) : null; +} diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index fe9eaf8..fc66c67 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -3,8 +3,11 @@ using Anubis.Db; namespace Anubis.Core; -/// A setting the interface may change: key, default and allowed values. -public sealed record SettingDefinition(string Key, string Label, string Default, IReadOnlyList? Allowed = null); +/// +/// A setting the interface may change: key, default and allowed values. +public sealed record SettingDefinition(string Key, string Label, string Default, IReadOnlyList, when present, returns +/// the reason a free-text value is refused, in the words the interface shows, or null when it is valid. +/// ? Allowed = null, Func ? Check = null); /// A value fixed by the startup configuration: it wins and is shown read-only with where to change it (SPEC 13.5). public sealed record StartupOverride(string Value, string Source); @@ -34,7 +37,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead ///Bot state behind the top bar buttons: active, paused (no new entries) or stopped (kill switch, SPEC 9.3). public static readonly SettingDefinition BotState = new("bot.state", "Stato del bot", "active", ["active", "paused", "stopped"]); - public static readonly IReadOnlyListAll = [Theme, Currency, BotState]; + /// Fed and ECB decision days, one per line (SPEC 4.4: a yearly list the user edits). + public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE", + Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check); + + public static readonly IReadOnlyListAll = [Theme, Currency, BotState, CentralBankMeetings]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary (); @@ -68,6 +75,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead throw new ArgumentException($"Valore non ammesso per {definition.Label}: {value}.", nameof(value)); } + if (definition.Check?.Invoke(value) is { } problem) + { + throw new ArgumentException(problem, nameof(value)); + } + var now = clock.UtcNow; var json = new DbJson(JsonSerializer.Serialize(value)); var changed = await db.WriteAsync(async s => diff --git a/src/Anubis/Data/Adjustments.cs b/src/Anubis/Data/Adjustments.cs new file mode 100644 index 0000000..f7d0e4f --- /dev/null +++ b/src/Anubis/Data/Adjustments.cs @@ -0,0 +1,185 @@ +using System.Globalization; + +namespace Anubis.Data; + +/// +/// Adjusted series and the effect of corporate actions (SPEC 6.10, trap 9). +/// +public static class Adjustments +{ + ///+///
+///- Signals use the adjusted series anchored at the decision day: its last price equals the real one, so +/// averages, highs and stop levels are already in today's prices.
+///- A backtest that sees day t uses the final adjusted series rescaled so that day t matches the real price.
+///- When an action hits a followed instrument, saved levels are converted with its factor; quantities change +/// only with splits and stock dividends.
+///+ /// The factor that brings prices before the ex-date in line with prices from the ex-date on: 1/ratio for a + /// split, (close − dividend) / close for a cash dividend, using the last real close before the ex-date. + /// + public static double PriceFactor(CorporateAction action, double? closeBeforeEx) + { + ArgumentNullException.ThrowIfNull(action); + if (action.ChangesShares) + { + return 1.0 / (double)action.Ratio!.Value; + } + + if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is { } cash && closeBeforeEx is { } close && close > (double)cash && cash > 0) + { + return (close - (double)cash) / close; + } + + return 1.0; + } + + ///+ /// The series as known on + public static IReadOnlyList: bars up to that day, with + /// computed from the real prices and the actions whose ex-date is not later than the anchor. The anchor bar's + /// adjusted prices equal its real ones. Actions after the anchor are ignored: on that day nobody knew them. + /// Anchored(IReadOnlyList raw, IEnumerable actions, DateOnly anchor) + { + ArgumentNullException.ThrowIfNull(raw); + ArgumentNullException.ThrowIfNull(actions); + var bars = raw.Where(b => b.Day <= anchor).OrderBy(b => b.Day).ToList(); + var known = actions.Where(a => a.ExDate <= anchor && a.ExDate > (bars.Count > 0 ? bars[0].Day : anchor)).OrderBy(a => a.ExDate).ToList(); + var factors = known.Select(a => + { + var before = bars.LastOrDefault(b => b.Day < a.ExDate); + return (a.ExDate, Price: PriceFactor(a, before?.Close), Shares: a.ChangesShares ? (double)a.Ratio!.Value : 1.0); + }).ToList(); + + var result = new List (bars.Count); + foreach (var bar in bars) + { + double price = 1, shares = 1; + foreach (var f in factors.Where(f => f.ExDate > bar.Day)) + { + price *= f.Price; + shares *= f.Shares; + } + + result.Add(bar with { Adjusted = bar.Prices.Scale(price), Volume = bar.Volume * shares }); + } + + return result; + } + + /// + /// The backtest view at day + public static IReadOnlyList: the source's final adjusted series up to that day, rescaled + /// so that its price on that day equals the real one. Needs on every bar. + /// RescaledAt(IReadOnlyList bars, DateOnly day) + { + ArgumentNullException.ThrowIfNull(bars); + var upTo = bars.Where(b => b.Day <= day).OrderBy(b => b.Day).ToList(); + if (upTo.Count == 0) + { + return []; + } + + var last = upTo[^1]; + var adjusted = last.Adjusted ?? throw new InvalidOperationException("Bar without adjusted prices: " + last.Day); + var factor = last.Close / adjusted.Close; + return upTo.Select(b => (b.Adjusted ?? throw new InvalidOperationException("Bar without adjusted prices: " + b.Day)).Scale(factor)).ToList(); + } + + /// + /// Converts a saved level (entry price, highest close, stop) across an action: a stop at 100 before a 2-for-1 + /// split becomes 50. + public static decimal ConvertLevel(decimal level, CorporateAction action, decimal? closeBeforeEx) + { + ArgumentNullException.ThrowIfNull(action); + if (action.ChangesShares) + { + return level / action.Ratio!.Value; + } + + if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is { } cash && closeBeforeEx is { } close && close > cash && cash > 0) + { + return level * (close - cash) / close; + } + + return level; + } + + ///is needed for cash dividends. + /// Quantity held after the action: only splits and stock dividends change it (SPEC 6.10). + public static decimal ConvertQuantity(decimal quantity, CorporateAction action) + { + ArgumentNullException.ThrowIfNull(action); + return action.ChangesShares ? quantity * action.Ratio!.Value : quantity; + } + + ///+ /// Recognises actions from the jump in the ratio between the real and the adjusted series, for when the + /// corporate actions endpoint is not available (SPEC 4.1). A jump close to a simple ratio (2, 3, 1/10…) is a + /// split; a small one is a cash dividend. + /// + public static IReadOnlyListDetect(string symbol, IReadOnlyList bars, double tolerance = 0.002) + { + ArgumentNullException.ThrowIfNull(bars); + var found = new List (); + var series = bars.Where(b => b.Adjusted is { Close: > 0 } && b.Close > 0).OrderBy(b => b.Day).ToList(); + for (var i = 1; i < series.Count; i++) + { + var before = series[i - 1].Adjusted!.Value.Close / series[i - 1].Close; + var after = series[i].Adjusted!.Value.Close / series[i].Close; + + // The adjusted/real ratio is constant between actions; from the ex-date on it is multiplied by the inverse factor. + var change = after / before; + if (Math.Abs(change - 1) <= tolerance) + { + continue; + } + + var day = series[i].Day; + var key = $"detected:{symbol}:{day:yyyy-MM-dd}"; + var ratio = SimpleRatio(change, tolerance); + if (ratio is { } r) + { + found.Add(new CorporateAction(symbol, CorporateActionKinds.Split, day, "detected", key) { Ratio = r }); + } + else if (change > 1 && change < 1.25) + { + // Prices before the ex-date were multiplied by f = 1/change: dividend = close before × (1 − f). + var dividend = series[i - 1].Close * (1 - (1 / change)); + found.Add(new CorporateAction(symbol, CorporateActionKinds.CashDividend, day, "detected", key) + { + CashAmount = Math.Round((decimal)dividend, 4), + }); + } + } + + return found; + } + + /// A split ratio n or 1/n (n from 2 to 50), or 3/2, 5/4, 4/3, 2/3…, matching + private static decimal? SimpleRatio(double value, double tolerance) + { + for (var n = 2; n <= 50; n++) + { + if (Math.Abs(value - n) <= tolerance * n) + { + return n; + } + + if (Math.Abs(value - (1.0 / n)) <= tolerance / n) + { + return decimal.Parse((1.0m / n).ToString("0.##########", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); + } + } + + foreach (var (num, den) in new[] { (3, 2), (5, 4), (4, 3), (5, 2), (2, 3), (4, 5), (3, 4), (2, 5) }) + { + if (Math.Abs(value - ((double)num / den)) <= tolerance * num / den) + { + return (decimal)num / den; + } + } + + return null; + } +} diff --git a/src/Anubis/Data/BarStore.cs b/src/Anubis/Data/BarStore.cs new file mode 100644 index 0000000..bd8e666 --- /dev/null +++ b/src/Anubis/Data/BarStore.cs @@ -0,0 +1,150 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +///. +/// Daily and one-minute bars in the database (SPEC 5.4, 6.2). Writes are upserts on (instrument, day) and +/// (instrument, minute) with +public sealed class BarStore(Database db, IClock clock) +{ + ///ON CONFLICT , which both engines understand. The research history lives in +/// files instead (). +/// One-minute bars are kept this long (SPEC 5.4). + public static readonly TimeSpan MinuteRetention = TimeSpan.FromDays(400); + + public const string DayFormat = "yyyy-MM-dd"; + + public static string DayText(DateOnly day) => day.ToString(DayFormat, CultureInfo.InvariantCulture); + + public static DateOnly ParseDay(string text) => DateOnly.ParseExact(text, DayFormat, CultureInfo.InvariantCulture); + + public async TaskUpsertDailyAsync(Guid instrumentId, IEnumerable bars, string source, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bars); + var list = bars.ToList(); + if (list.Count == 0) + { + return 0; + } + + var now = clock.UtcNow; + return await db.WriteAsync(async s => + { + foreach (var bar in list) + { + await s.ExecuteAsync( + "INSERT INTO bars_1d (id, instrument_id, day, open, high, low, close, volume, quote_volume, adj_open, adj_high, adj_low, adj_close, " + + "source, quality, created_at, updated_at) VALUES (@id, @i, @d, @o, @h, @l, @c, @v, @qv, @ao, @ah, @al, @ac, @src, @q, @now, @now) " + + "ON CONFLICT (instrument_id, day) DO UPDATE SET open = excluded.open, high = excluded.high, low = excluded.low, close = excluded.close, " + + "volume = excluded.volume, quote_volume = excluded.quote_volume, adj_open = excluded.adj_open, adj_high = excluded.adj_high, " + + "adj_low = excluded.adj_low, adj_close = excluded.adj_close, source = excluded.source, quality = excluded.quality, updated_at = excluded.updated_at", + cancellationToken, + ("id", Ids.NewId(clock)), ("i", instrumentId), ("d", DayText(bar.Day)), ("o", bar.Open), ("h", bar.High), ("l", bar.Low), ("c", bar.Close), + ("v", bar.Volume), ("qv", bar.QuoteVolume), ("ao", bar.Adjusted?.Open), ("ah", bar.Adjusted?.High), ("al", bar.Adjusted?.Low), + ("ac", bar.Adjusted?.Close), ("src", source), ("q", bar.Quality), ("now", now)).ConfigureAwait(false); + } + + return list.Count; + }, cancellationToken).ConfigureAwait(false); + } + + /// Daily bars from + public async Taskto , both included, oldest first. > DailyAsync(Guid instrumentId, DateOnly from, DateOnly to, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT day, open, high, low, close, volume, quote_volume, adj_open, adj_high, adj_low, adj_close, quality FROM bars_1d " + + "WHERE instrument_id = @i AND day >= @f AND day <= @t ORDER BY day", + ReadDaily, ("i", instrumentId), ("f", DayText(from)), ("t", DayText(to))), cancellationToken).ConfigureAwait(false); + + public async Task LastDayAsync(Guid instrumentId, CancellationToken cancellationToken) + { + var text = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MAX(day) AS d FROM bars_1d WHERE instrument_id = @i", + r => r.TextOrNull("d"), ("i", instrumentId)), cancellationToken).ConfigureAwait(false); + return text is null ? null : ParseDay(text); + } + + public async Task FirstDayAsync(Guid instrumentId, CancellationToken cancellationToken) + { + var text = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(day) AS d FROM bars_1d WHERE instrument_id = @i", + r => r.TextOrNull("d"), ("i", instrumentId)), cancellationToken).ConfigureAwait(false); + return text is null ? null : ParseDay(text); + } + + public Task CountDailyAsync(Guid instrumentId, CancellationToken cancellationToken) => + db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM bars_1d WHERE instrument_id = @i", ("i", instrumentId)), cancellationToken); + + /// + /// Multiplies the adjusted prices of the days up to + public Taskby : a new + /// split or dividend changes the basis of every older adjusted price, and the history must stay on one basis. + /// RescaleAdjustedAsync(Guid instrumentId, DateOnly through, double factor, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync( + "UPDATE bars_1d SET adj_open = adj_open * @f, adj_high = adj_high * @f, adj_low = adj_low * @f, adj_close = adj_close * @f, updated_at = @now " + + "WHERE instrument_id = @i AND day <= @d AND adj_close IS NOT NULL", cancellationToken, + ("f", factor), ("now", clock.UtcNow), ("i", instrumentId), ("d", DayText(through))), cancellationToken); + + public Task SetDailyQualityAsync(Guid instrumentId, DateOnly day, string quality, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE bars_1d SET quality = @q, updated_at = @now WHERE instrument_id = @i AND day = @d", cancellationToken, + ("q", quality), ("now", clock.UtcNow), ("i", instrumentId), ("d", DayText(day))), cancellationToken); + + public Task DeleteDailyAsync(Guid instrumentId, DateOnly day, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("DELETE FROM bars_1d WHERE instrument_id = @i AND day = @d", cancellationToken, + ("i", instrumentId), ("d", DayText(day))), cancellationToken); + + public async Task UpsertMinuteAsync(Guid instrumentId, IEnumerable bars, string source, string quality, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bars); + var list = bars.ToList(); + if (list.Count == 0) + { + return 0; + } + + var now = clock.UtcNow; + return await db.WriteAsync(async s => + { + foreach (var bar in list) + { + await s.ExecuteAsync( + "INSERT INTO bars_1m (id, instrument_id, opens_at, open, high, low, close, volume, source, quality, created_at) " + + "VALUES (@id, @i, @t, @o, @h, @l, @c, @v, @src, @q, @now) " + + "ON CONFLICT (instrument_id, opens_at) DO UPDATE SET open = excluded.open, high = excluded.high, low = excluded.low, " + + "close = excluded.close, volume = excluded.volume, source = excluded.source, quality = excluded.quality", + cancellationToken, + ("id", Ids.NewId(clock)), ("i", instrumentId), ("t", bar.OpensAt), ("o", bar.Open), ("h", bar.High), ("l", bar.Low), ("c", bar.Close), + ("v", bar.Volume), ("src", source), ("q", quality), ("now", now)).ConfigureAwait(false); + } + + return list.Count; + }, cancellationToken).ConfigureAwait(false); + } + + /// One-minute bars opening from + public async Task(included) to (excluded), oldest first. > MinuteAsync(Guid instrumentId, DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT opens_at, open, high, low, close, volume FROM bars_1m WHERE instrument_id = @i AND opens_at >= @f AND opens_at < @t ORDER BY opens_at", + r => new Bar(r.Moment("opens_at"), r.Measure("open"), r.Measure("high"), r.Measure("low"), r.Measure("close"), r.Measure("volume")), + ("i", instrumentId), ("f", from), ("t", to)), cancellationToken).ConfigureAwait(false); + + public Task DeleteMinuteAsync(Guid instrumentId, DateTimeOffset opensAt, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("DELETE FROM bars_1m WHERE instrument_id = @i AND opens_at = @t", cancellationToken, ("i", instrumentId), ("t", opensAt)), + cancellationToken); + + public Task LastMinuteAsync(Guid instrumentId, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT opens_at FROM bars_1m WHERE instrument_id = @i ORDER BY opens_at DESC", + r => (DateTimeOffset?)r.Moment("opens_at"), ("i", instrumentId)), cancellationToken); + + /// Deletes one-minute bars older than the retention (SPEC 5.4). Returns how many went. + public TaskPruneMinutesAsync(CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("DELETE FROM bars_1m WHERE opens_at < @t", cancellationToken, ("t", clock.UtcNow - MinuteRetention)), + cancellationToken); + + private static DailyBar ReadDaily(DbRow r) => + new(ParseDay(r.Text("day")), r.Measure("open"), r.Measure("high"), r.Measure("low"), r.Measure("close"), r.Measure("volume")) + { + QuoteVolume = r.IsNull("quote_volume") ? null : r.Measure("quote_volume"), + Adjusted = r.IsNull("adj_close") ? null : new Ohlc(r.Measure("adj_open"), r.Measure("adj_high"), r.Measure("adj_low"), r.Measure("adj_close")), + Quality = r.Text("quality"), + }; +} diff --git a/src/Anubis/Data/Collector.cs b/src/Anubis/Data/Collector.cs new file mode 100644 index 0000000..5380e05 --- /dev/null +++ b/src/Anubis/Data/Collector.cs @@ -0,0 +1,446 @@ +using Anubis.Core; +using Anubis.Db; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Data; + +/// What a collection pass did, for the log and the quality report. +public sealed record CollectionResult(int Stored, int Suspect, int Confirmed, int Corrected, int Gaps, int Recovered, int Unrecoverable) +{ + public static readonly CollectionResult None = new(0, 0, 0, 0, 0, 0, 0); + + public CollectionResult Add(CollectionResult other) => new(Stored + other.Stored, Suspect + other.Suspect, + Confirmed + other.Confirmed, Corrected + other.Corrected, Gaps + other.Gaps, Recovered + other.Recovered, Unrecoverable + other.Unrecoverable); +} + +///The live feed of a venue connected, dropped or came back (SPEC 6.2). +public sealed record FeedChanged(string Venue, bool Connected, DateTimeOffset At, string? Reason); + +///+/// The collector of SPEC 6.2–6.4 for one venue: downloads what is missing at startup and after every drop of the +/// live feed, checks every bar, and never corrects in silence. A suspect bar is stored as suspect, blocks new +/// entries on its instrument (see +public sealed partial class MarketCollector +{ + ///) and is read a second +/// time: the same values confirm it, different ones replace it, and an impossible bar is dropped. Gaps are +/// downloaded again once; what the source still lacks is recorded as unrecoverable. +/// History of minute bars downloaded the first time an instrument is followed. + public static readonly TimeSpan InitialMinutes = TimeSpan.FromDays(2); + + ///Waits between reconnection attempts: 1, 2, 5, 10, 30 seconds, then 60. + public static readonly IReadOnlyListBackoff = + [TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60)]; + + /// Closes used as context for the jump check of new bars. + private const int Context = QualityChecks.JumpWindow + 1; + + private readonly IMarketDataSource _source; + private readonly IClock _clock; + private readonly EventBus _bus; + private readonly FreshnessMonitor _freshness; + private readonly Func?> _expectedMinutes; + private readonly Func ?> _expectedDays; + private readonly ILogger _logger; + private readonly BarStore _bars; + private readonly DataIssueStore _issues; + + /// Minutes a bar should exist for; by default every minute for crypto and none (no gap check) for stocks. + /// Days a daily bar should exist for; by default every day for crypto and none for stocks. + public MarketCollector( + IMarketDataSource source, + Database db, + IClock clock, + EventBus bus, + FreshnessMonitor freshness, + Func ?>? expectedMinutes = null, + Func ?>? expectedDays = null, + ILogger? logger = null) + { + ArgumentNullException.ThrowIfNull(source); + _source = source; + _clock = clock; + _bus = bus; + _freshness = freshness; + _expectedMinutes = expectedMinutes ?? ((i, from, to) => i.IsCrypto ? QualityChecks.EveryMinute(from, to) : null); + _expectedDays = expectedDays ?? ((i, from, to) => i.IsCrypto ? QualityChecks.EveryDay(from, to) : null); + _logger = logger ?? NullLogger.Instance; + _bars = new BarStore(db, clock); + _issues = new DataIssueStore(db, clock); + } + + public string Venue => _source.Venue; + + /// True while the live feed is connected. + public bool Connected { get; private set; } + + ///+ /// Downloads the daily bars after the last one stored (from + public async Taskthe first time) up to yesterday. + /// , when given, are bars already downloaded for many symbols at once: only the second + /// readings and the gaps call the source again. is the last day to collect: yesterday + /// (UTC) unless the caller knows a later closed session, as for stocks after the New York close. + /// BackfillDailyAsync(Instrument instrument, DateOnly from, CancellationToken cancellationToken, + IReadOnlyList ? prefetched = null, DateOnly? lastDay = null) + { + ArgumentNullException.ThrowIfNull(instrument); + var yesterday = lastDay ?? DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime).AddDays(-1); + var last = await _bars.LastDayAsync(instrument.Id, cancellationToken).ConfigureAwait(false); + var first = last?.AddDays(1) ?? from; + if (first > yesterday) + { + return CollectionResult.None; + } + + // The download starts from the last day held, which works as a witness: if its adjusted prices changed, a split + // or dividend arrived meanwhile and the whole stored history is brought onto the new basis first. + var downloaded = prefetched is null + ? await _source.FetchDailyBarsAsync(instrument.Symbol, last ?? first, yesterday, cancellationToken).ConfigureAwait(false) + : prefetched; + if (last is { } witnessDay && downloaded.FirstOrDefault(b => b.Day == witnessDay) is { Adjusted: { } fresh } witness) + { + await RebaseAdjustedAsync(instrument, witnessDay, witness.Close, fresh.Close, cancellationToken).ConfigureAwait(false); + } + + var fetched = downloaded.Where(b => b.Day >= first && b.Day <= yesterday).OrderBy(b => b.Day).ToList(); + if (fetched.Count == 0) + { + return CollectionResult.None; + } + + var context = await _bars.DailyAsync(instrument.Id, first.AddDays(-Context * 2), first.AddDays(-1), cancellationToken).ConfigureAwait(false); + var held = context.Where(b => b.Day < fetched[0].Day).TakeLast(Context).ToList(); + var all = held.Concat(fetched).ToList(); + var newFrom = QualityChecks.Midnight(fetched[0].Day); + // A gap is new when it ends after the last bar already held: that includes the hole between the stored history + // and the first bar of this download. Gaps among the held bars were handled when those bars arrived. + var lastHeld = held.Count > 0 ? QualityChecks.Midnight(held[^1].Day) : DateTimeOffset.MinValue; + var findings = QualityChecks.CheckDaily(all, _expectedDays(instrument, all[0].Day, all[^1].Day)) + .Where(f => f.Kind == IssueKinds.Gap ? f.EndsAt > lastHeld : f.StartsAt >= newFrom).ToList(); + + var result = CollectionResult.None; + var suspectDays = findings.Where(f => IssueKinds.MakesSuspect(f.Kind)).Select(f => DateOnly.FromDateTime(f.StartsAt.UtcDateTime)).ToHashSet(); + var impossible = findings.Where(f => f.Kind is IssueKinds.NonPositive or IssueKinds.HighBelowLow) + .Select(f => DateOnly.FromDateTime(f.StartsAt.UtcDateTime)).ToHashSet(); + var stored = fetched.DistinctBy(b => b.Day) + .Where(b => !impossible.Contains(b.Day)) + .Select(b => suspectDays.Contains(b.Day) ? b with { Quality = BarQuality.Suspect } : b) + .ToList(); + await _bars.UpsertDailyAsync(instrument.Id, stored, Venue, cancellationToken).ConfigureAwait(false); + result = result with { Stored = stored.Count }; + + foreach (var finding in findings) + { + var id = await _issues.RecordAsync(instrument.Id, Timeframes.Day, finding, cancellationToken).ConfigureAwait(false); + if (IssueKinds.MakesSuspect(finding.Kind)) + { + result = result.Add(await SecondDailyReadingAsync(instrument, id, finding, cancellationToken).ConfigureAwait(false)); + } + else if (finding.Kind == IssueKinds.Gap) + { + result = result.Add(await RecoverDailyGapAsync(instrument, id, finding, cancellationToken).ConfigureAwait(false)); + } + } + + return result; + } + + private async Task RebaseAdjustedAsync(Instrument instrument, DateOnly day, double close, double adjustedClose, CancellationToken cancellationToken) + { + var held = await _bars.DailyAsync(instrument.Id, day, day, cancellationToken).ConfigureAwait(false); + if (held.Count == 0 || held[0].Adjusted is not { } old || old.Close <= 0 || held[0].Close <= 0 || close <= 0) + { + return; + } + + // Ratios of adjusted to real close, before and now; the real close itself does not change. + var factor = adjustedClose / close / (old.Close / held[0].Close); + if (double.IsFinite(factor) && factor > 0 && Math.Abs(factor - 1) > 1e-6) + { + await _bars.RescaleAdjustedAsync(instrument.Id, day, factor, cancellationToken).ConfigureAwait(false); + } + } + + /// Downloads the minute bars after the last one stored, up to the last closed minute. + public async TaskBackfillMinutesAsync(Instrument instrument, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(instrument); + var until = Minute(_clock.UtcNow); + var last = await _bars.LastMinuteAsync(instrument.Id, cancellationToken).ConfigureAwait(false); + var start = last?.AddMinutes(1) ?? until - InitialMinutes; + if (start >= until) + { + return CollectionResult.None; + } + + var fetched = await _source.FetchMinuteBarsAsync(instrument.Symbol, start, until, cancellationToken).ConfigureAwait(false); + var context = last is { } l + ? await _bars.MinuteAsync(instrument.Id, l.AddMinutes(-Context), l.AddMinutes(1), cancellationToken).ConfigureAwait(false) + : []; + // Minutes the source has not published yet are not gaps: the next pass starts again from the last bar held, + // and a minute still missing then lies between two bars and is found by the check. + return await AcceptMinutesAsync(instrument, context, fetched, cancellationToken).ConfigureAwait(false); + } + + /// + /// Follows + public async Task RunLiveAsync(IReadOnlyListon the live feed until cancelled: every datum refreshes the freshness of + /// its instrument, every closed bar is checked and stored, and every drop is followed by a reconnection and by the + /// download of what was missed meanwhile. + /// instruments, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(instruments); + var bySymbol = instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal); + foreach (var instrument in instruments) + { + _freshness.Follow(instrument.Id, instrument.Symbol); + } + + var recent = new Dictionary >(); + var failures = 0; + while (!cancellationToken.IsCancellationRequested) + { + string? reason = null; + try + { + foreach (var instrument in instruments) + { + var recovered = await BackfillMinutesAsync(instrument, cancellationToken).ConfigureAwait(false); + if (recovered.Stored > 0) + { + LogRecovered(_logger, Venue, instrument.Symbol, recovered.Stored); + } + + var last = await _bars.LastMinuteAsync(instrument.Id, cancellationToken).ConfigureAwait(false); + recent[instrument.Id] = last is { } l + ? (await _bars.MinuteAsync(instrument.Id, l.AddMinutes(-Context), l.AddMinutes(1), cancellationToken).ConfigureAwait(false)).ToList() + : []; + } + + await foreach (var item in _source.StreamAsync(bySymbol.Keys, cancellationToken).ConfigureAwait(false)) + { + if (!Connected) + { + Connected = true; + failures = 0; + _bus.Publish(new FeedChanged(Venue, true, _clock.UtcNow, null)); + } + + if (!bySymbol.TryGetValue(item.Symbol, out var instrument)) + { + continue; + } + + if (item is BarEvent { Closed: true } closed) + { + var context = recent[instrument.Id]; + await AcceptMinutesAsync(instrument, context, [closed.Bar], cancellationToken).ConfigureAwait(false); + if (Possible(closed.Bar)) + { + context.RemoveAll(b => b.OpensAt == closed.Bar.OpensAt); + context.Add(closed.Bar); + } + + if (context.Count > Context * 2) + { + context.RemoveRange(0, context.Count - Context); + } + + _freshness.Touch(instrument.Id, closed.Bar.OpensAt.AddMinutes(1)); + } + else if (item is not BarEvent) + { + _freshness.Touch(instrument.Id, item.At); + } + + _bus.Publish(item); + } + + reason = "il flusso si è chiuso"; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // Any failure, the network's or the database's (a PostgreSQL restart, a busy SQLite file): the feed is + // marked down, then it waits and starts again. The loop never ends on its own. + reason = Redactor.Redact(ex.Message); + LogFeedError(_logger, Venue, reason); + } + + if (Connected) + { + Connected = false; + _bus.Publish(new FeedChanged(Venue, false, _clock.UtcNow, reason)); + } + + var wait = Backoff[Math.Min(failures, Backoff.Count - 1)]; + failures++; + try + { + await _clock.WaitUntilAsync(_clock.UtcNow + wait, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + } + + if (Connected) + { + Connected = false; + _bus.Publish(new FeedChanged(Venue, false, _clock.UtcNow, "arresto")); + } + } + + /// Checks new minute bars against their context, stores them, and handles what the checks found. + private async TaskAcceptMinutesAsync(Instrument instrument, IReadOnlyList context, IReadOnlyList fresh, CancellationToken cancellationToken) + { + if (fresh.Count == 0) + { + return CollectionResult.None; + } + + var times = fresh.Select(b => b.OpensAt).ToHashSet(); + var held = context.Where(b => !times.Contains(b.OpensAt)).OrderBy(b => b.OpensAt).TakeLast(Context).ToList(); + var all = held.Concat(fresh).ToList(); + var newFrom = fresh.Min(b => b.OpensAt); + var expected = _expectedMinutes(instrument, all.Min(b => b.OpensAt), all.Max(b => b.OpensAt).AddMinutes(1)); + // As for days: a gap ending after the last minute held is new, including a minute the live feed skipped. + var lastHeld = held.Count > 0 ? held[^1].OpensAt : DateTimeOffset.MinValue; + var findings = QualityChecks.CheckMinutes(all, expected) + .Where(f => f.Kind == IssueKinds.Gap ? f.EndsAt > lastHeld : f.StartsAt >= newFrom).ToList(); + var suspect = findings.Where(f => IssueKinds.MakesSuspect(f.Kind)).Select(f => f.StartsAt).ToHashSet(); + var impossible = findings.Where(f => f.Kind is IssueKinds.NonPositive or IssueKinds.HighBelowLow).Select(f => f.StartsAt).ToHashSet(); + + var good = fresh.DistinctBy(b => b.OpensAt).Where(b => !suspect.Contains(b.OpensAt)).ToList(); + var doubtful = fresh.DistinctBy(b => b.OpensAt).Where(b => suspect.Contains(b.OpensAt) && !impossible.Contains(b.OpensAt)).ToList(); + await _bars.UpsertMinuteAsync(instrument.Id, good, Venue, BarQuality.Ok, cancellationToken).ConfigureAwait(false); + await _bars.UpsertMinuteAsync(instrument.Id, doubtful, Venue, BarQuality.Suspect, cancellationToken).ConfigureAwait(false); + var result = CollectionResult.None with { Stored = good.Count + doubtful.Count }; + + foreach (var finding in findings) + { + if (IssueKinds.MakesSuspect(finding.Kind)) + { + var id = await _issues.RecordAsync(instrument.Id, Timeframes.Minute, finding, cancellationToken).ConfigureAwait(false); + result = result.Add(await SecondMinuteReadingAsync(instrument, id, finding, cancellationToken).ConfigureAwait(false)); + } + else if (finding.Kind == IssueKinds.Gap) + { + result = result.Add(await RecordMinuteGapAsync(instrument, finding, cancellationToken).ConfigureAwait(false)); + } + } + + return result; + } + + private async Task RecordMinuteGapAsync(Instrument instrument, QualityFinding gap, CancellationToken cancellationToken) + { + var id = await _issues.RecordAsync(instrument.Id, Timeframes.Minute, gap, cancellationToken).ConfigureAwait(false); + await _issues.AttemptAsync(id, cancellationToken).ConfigureAwait(false); + var bars = await _source.FetchMinuteBarsAsync(instrument.Symbol, gap.StartsAt, gap.EndsAt.AddMinutes(1), cancellationToken).ConfigureAwait(false); + var found = bars.Where(b => b.OpensAt >= gap.StartsAt && b.OpensAt <= gap.EndsAt && Possible(b)).ToList(); + await _bars.UpsertMinuteAsync(instrument.Id, found, Venue, BarQuality.Ok, cancellationToken).ConfigureAwait(false); + var missing = (int)((gap.EndsAt - gap.StartsAt).TotalMinutes + 1) - found.Count; + if (missing <= 0) + { + await _issues.ResolveAsync(id, IssueStatus.Recovered, $"{gap.Detail}: recuperati {found.Count}", cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Gaps = 1, Recovered = 1, Stored = found.Count }; + } + + await _issues.ResolveAsync(id, IssueStatus.Unrecoverable, + $"{gap.Detail}: la fonte non ha {missing} barre" + (found.Count > 0 ? $" (recuperate {found.Count})" : "") + ", forse minuti senza scambi", + cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Gaps = 1, Unrecoverable = 1, Stored = found.Count }; + } + + private async Task SecondMinuteReadingAsync(Instrument instrument, Guid issue, QualityFinding finding, CancellationToken cancellationToken) + { + await _issues.AttemptAsync(issue, cancellationToken).ConfigureAwait(false); + var at = finding.StartsAt; + var stored = FirstOf(await _bars.MinuteAsync(instrument.Id, at, at.AddMinutes(1), cancellationToken).ConfigureAwait(false)); + var again = (await _source.FetchMinuteBarsAsync(instrument.Symbol, at, at.AddMinutes(1), cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(b => b.OpensAt == at); + return await ConcludeAsync(issue, finding, stored is null ? null : Prices(stored), again is null ? null : Prices(again), + q => _bars.UpsertMinuteAsync(instrument.Id, [again!], Venue, q, cancellationToken), + () => _bars.DeleteMinuteAsync(instrument.Id, at, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + private async Task SecondDailyReadingAsync(Instrument instrument, Guid issue, QualityFinding finding, CancellationToken cancellationToken) + { + await _issues.AttemptAsync(issue, cancellationToken).ConfigureAwait(false); + var day = DateOnly.FromDateTime(finding.StartsAt.UtcDateTime); + var stored = FirstOf(await _bars.DailyAsync(instrument.Id, day, day, cancellationToken).ConfigureAwait(false)); + var again = (await _source.FetchDailyBarsAsync(instrument.Symbol, day, day, cancellationToken).ConfigureAwait(false)).FirstOrDefault(b => b.Day == day); + return await ConcludeAsync(issue, finding, stored?.Prices, again?.Prices, + q => _bars.UpsertDailyAsync(instrument.Id, [again! with { Quality = q }], Venue, cancellationToken), + () => _bars.DeleteDailyAsync(instrument.Id, day, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// + /// The outcome of a second reading: impossible or absent again → unrecoverable and the bar is dropped; the same + /// prices → confirmed; different prices → the new ones replace the old (corrected). + /// + private async TaskConcludeAsync(Guid issue, QualityFinding finding, Ohlc? stored, Ohlc? again, + Func > save, Func drop, CancellationToken cancellationToken) + { + if (again is not { } second || !Possible(second)) + { + await drop().ConfigureAwait(false); + await _issues.ResolveAsync(issue, IssueStatus.Unrecoverable, finding.Detail + ": la seconda lettura non dà un dato valido, barra scartata", + cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Suspect = 1, Unrecoverable = 1 }; + } + + if (stored is { } first && Same(first, second)) + { + await save(BarQuality.Confirmed).ConfigureAwait(false); + await _issues.ResolveAsync(issue, IssueStatus.Confirmed, finding.Detail + ": confermato dalla seconda lettura", cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Suspect = 1, Confirmed = 1 }; + } + + await save(BarQuality.Ok).ConfigureAwait(false); + await _issues.ResolveAsync(issue, IssueStatus.Corrected, + finding.Detail + (stored is { } old ? $": la seconda lettura dà chiusura {second.Close:G6} invece di {old.Close:G6}" : ": la seconda lettura dà una barra valida"), + cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Suspect = 1, Corrected = 1 }; + } + + private async Task RecoverDailyGapAsync(Instrument instrument, Guid issue, QualityFinding gap, CancellationToken cancellationToken) + { + await _issues.AttemptAsync(issue, cancellationToken).ConfigureAwait(false); + var first = DateOnly.FromDateTime(gap.StartsAt.UtcDateTime); + var last = DateOnly.FromDateTime(gap.EndsAt.UtcDateTime); + var found = (await _source.FetchDailyBarsAsync(instrument.Symbol, first, last, cancellationToken).ConfigureAwait(false)) + .Where(b => b.Day >= first && b.Day <= last && Possible(b.Prices)).ToList(); + await _bars.UpsertDailyAsync(instrument.Id, found, Venue, cancellationToken).ConfigureAwait(false); + var missing = last.DayNumber - first.DayNumber + 1 - found.Count; + await _issues.ResolveAsync(issue, missing <= 0 ? IssueStatus.Recovered : IssueStatus.Unrecoverable, + missing <= 0 ? gap.Detail + ": recuperato" : $"{gap.Detail}: la fonte non ha {missing} giorni", cancellationToken).ConfigureAwait(false); + return CollectionResult.None with { Gaps = 1, Recovered = missing <= 0 ? 1 : 0, Unrecoverable = missing <= 0 ? 0 : 1, Stored = found.Count }; + } + + private static T? FirstOf (IReadOnlyList list) where T : class => list.Count > 0 ? list[0] : null; + + private static Ohlc Prices(Bar b) => new(b.Open, b.High, b.Low, b.Close); + + private static bool Possible(Bar b) => Possible(Prices(b)); + + private static bool Possible(Ohlc p) => p.Open > 0 && p.High > 0 && p.Low > 0 && p.Close > 0 && p.High >= p.Low; + + private static bool Same(Ohlc a, Ohlc b) => Close(a.Open, b.Open) && Close(a.High, b.High) && Close(a.Low, b.Low) && Close(a.Close, b.Close); + + private static bool Close(double a, double b) => Math.Abs(a - b) <= 1e-9 * Math.Max(Math.Abs(a), Math.Abs(b)); + + private static DateTimeOffset Minute(DateTimeOffset t) => new(t.UtcTicks - t.UtcTicks % TimeSpan.TicksPerMinute, TimeSpan.Zero); + + [LoggerMessage(Level = LogLevel.Information, Message = "{Venue} {Symbol}: recovered {Count} minute bars")] + private static partial void LogRecovered(ILogger logger, string venue, string symbol, int count); + + [LoggerMessage(Level = LogLevel.Warning, Message = "{Venue} live feed dropped: {Reason}")] + private static partial void LogFeedError(ILogger logger, string venue, string reason); +} diff --git a/src/Anubis/Data/FreeSources.cs b/src/Anubis/Data/FreeSources.cs new file mode 100644 index 0000000..b225f57 --- /dev/null +++ b/src/Anubis/Data/FreeSources.cs @@ -0,0 +1,482 @@ +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Xml.Linq; + +namespace Anubis.Data; + +/// +/// Readers of the free sources of SPEC 4.4. Each is a pure function from the published text to Anubis records, tested +/// on recorded responses; +public static class Ecb +{ + public const string Source = "ecb"; + + public static readonly Uri Daily = new("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); + + public static readonly Uri Last90Days = new("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml"); + + public static readonly Uri History = new("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip"); + + private static readonly XNamespace _ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"; + + ///downloads them within their limits. +/// Rates of the daily or 90-day XML for the + public static IReadOnlyListasked, EUR as base. ParseXml(string xml, IReadOnlyCollection currencies) + { + var document = XDocument.Parse(xml); + return document.Descendants(_ns + "Cube") + .Where(day => day.Attribute("time") is not null) + .SelectMany(day => day.Elements(_ns + "Cube").Select(rate => (Day: day, Rate: rate))) + .Where(x => currencies.Contains((string?)x.Rate.Attribute("currency") ?? "")) + .Select(x => new FxRate("EUR", (string)x.Rate.Attribute("currency")!, + DateOnly.ParseExact((string)x.Day.Attribute("time")!, "yyyy-MM-dd", CultureInfo.InvariantCulture), + decimal.Parse((string)x.Rate.Attribute("rate")!, NumberStyles.Float, CultureInfo.InvariantCulture), Source)) + .OrderBy(r => r.Date) + .ToList(); + } + + /// The full history CSV (inside eurofxref-hist.zip): newest first, a trailing comma on every line, N/A where missing. + public static IReadOnlyListParseHistoryCsv(string csv, IReadOnlyCollection currencies) + { + ArgumentNullException.ThrowIfNull(csv); + var lines = csv.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var header = lines[0].Split(','); + var rates = new List (); + foreach (var line in lines.Skip(1)) + { + var fields = line.Split(','); + var date = DateOnly.ParseExact(fields[0], "yyyy-MM-dd", CultureInfo.InvariantCulture); + for (var i = 1; i < Math.Min(header.Length, fields.Length); i++) + { + if (currencies.Contains(header[i]) && decimal.TryParse(fields[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var rate)) + { + rates.Add(new FxRate("EUR", header[i], date, rate, Source)); + } + } + } + + return rates.OrderBy(r => r.Date).ToList(); + } + + public static string ExtractHistoryCsv(byte[] zip) + { + using var archive = new ZipArchive(new MemoryStream(zip), ZipArchiveMode.Read); + var entry = archive.Entries.Single(e => e.Name.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)); + using var reader = new StreamReader(entry.Open()); + return reader.ReadToEnd(); + } +} + +/// The weekly economic calendar of Forex Factory (faireconomy.media). It has no actual values. +public static class ForexFactory +{ + public const string Source = "forexfactory"; + + public static readonly Uri ThisWeek = new("https://nfs.faireconomy.media/ff_calendar_thisweek.json"); + + public static IReadOnlyListParse(string json) + { + using var document = JsonDocument.Parse(json); + var events = new List (); + foreach (var item in document.RootElement.EnumerateArray()) + { + var title = Text(item, "title"); + var country = Text(item, "country"); + var at = DateTimeOffset.Parse(Text(item, "date"), CultureInfo.InvariantCulture).ToUniversalTime(); + var impact = Text(item, "impact"); + var holiday = impact == "Holiday"; + events.Add(new CalendarEvent(holiday ? CalendarEventKinds.Holiday : CalendarEventKinds.Economic, title, at, TimeKnown: !holiday, Source, + $"ff:{country}:{at:yyyy-MM-ddTHH:mm}:{title}") + { + Currency = country == "All" ? null : country, + Impact = holiday ? null : impact, + Forecast = Empty(Text(item, "forecast")), + Previous = Empty(Text(item, "previous")), + }); + } + + return events; + } + + private static string? Empty(string text) => text.Length == 0 ? null : text; + + internal static string Text(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; +} + +/// +/// Future release dates of the main US data from FRED (optional key). FRED gives only the day: the time is +/// 08:30 New York and the impact high (SPEC 4.4). +/// +public static class Fred +{ + public const string Source = "fred"; + + ///Releases followed, with the title the calendar shows (ids checked on fred.stlouisfed.org). + public static readonly IReadOnlyList<(int Id, string Title)> Releases = + [ + (10, "CPI (inflazione USA)"), + (50, "Employment Situation (occupazione USA)"), + (53, "PIL USA"), + (54, "Personal Income and Outlays (PCE)"), + ]; + + public static Uri ReleaseDates(int releaseId, string apiKey, DateOnly from) => new( + "https://api.stlouisfed.org/fred/release/dates?release_id=" + releaseId.ToString(CultureInfo.InvariantCulture) + + "&api_key=" + Uri.EscapeDataString(apiKey) + "&file_type=json&include_release_dates_with_no_data=true&sort_order=asc" + + "&realtime_start=" + from.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); + + public static IReadOnlyListParse(string json, string title, DateOnly from) + { + using var document = JsonDocument.Parse(json); + var events = new List (); + foreach (var item in document.RootElement.GetProperty("release_dates").EnumerateArray()) + { + var day = DateOnly.ParseExact(ForexFactory.Text(item, "date"), "yyyy-MM-dd", CultureInfo.InvariantCulture); + if (day < from) + { + continue; + } + + var id = item.GetProperty("release_id").GetInt32(); + events.Add(new CalendarEvent(CalendarEventKinds.Economic, title, Zones.At(day, new TimeOnly(8, 30), Zones.NewYork), TimeKnown: true, Source, + $"fred:{id}:{day:yyyy-MM-dd}") + { + Currency = "USD", + Impact = "High", + }); + } + + return events; + } +} + +/// Earnings dates from Finnhub (optional key, free plan: 60 calls a minute). +public static class Finnhub +{ + public const string Source = "finnhub"; + + public static Uri Earnings(DateOnly from, DateOnly to, string apiKey) => new( + $"https://finnhub.io/api/v1/calendar/earnings?from={from:yyyy-MM-dd}&to={to:yyyy-MM-dd}&token={Uri.EscapeDataString(apiKey)}"); + + ///+ /// + public static IReadOnlyListhour : bmo before the open (08:00 New York), amc after the close (16:05), dmh during market hours + /// (12:00); empty means unknown and the event keeps only its day. + ///Parse(string json, IReadOnlySet ? symbols = null) + { + using var document = JsonDocument.Parse(json); + var events = new List (); + foreach (var item in document.RootElement.GetProperty("earningsCalendar").EnumerateArray()) + { + var symbol = ForexFactory.Text(item, "symbol"); + if (symbols is not null && !symbols.Contains(symbol)) + { + continue; + } + + var day = DateOnly.ParseExact(ForexFactory.Text(item, "date"), "yyyy-MM-dd", CultureInfo.InvariantCulture); + var hour = ForexFactory.Text(item, "hour"); + TimeOnly? time = hour switch + { + "bmo" => new TimeOnly(8, 0), + "amc" => new TimeOnly(16, 5), + "dmh" => new TimeOnly(12, 0), + _ => null, + }; + events.Add(new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale " + symbol, Zones.At(day, time ?? TimeOnly.MinValue, Zones.NewYork), + time is not null, Source, $"finnhub:{symbol}:{day:yyyy-MM-dd}") + { + Symbol = symbol, + Currency = "USD", + TimeHint = hour.Length == 0 ? null : hour, + Impact = "High", + }); + } + + return events; + } +} + +/// +/// Meetings of the Fed and the ECB from the yearly list in the settings (SPEC 4.4): one per line, +/// +public static class CentralBanks +{ + public const string Source = "central_banks"; + + ///FED 2026-12-09 orBCE 2026-12-17 . Fed decisions come at 14:00 New York, ECB ones at 14:15 Frankfurt. +///Decision days from the official calendars, read on 10/11/2026 (API-NOTES). + public const string DefaultList = + "FED 2026-12-09\nFED 2027-01-27\nFED 2027-03-17\nFED 2027-04-28\nFED 2027-06-09\nFED 2027-07-28\nFED 2027-09-15\nFED 2027-10-27\nFED 2027-12-08\n" + + "BCE 2026-12-17\nBCE 2027-02-04\nBCE 2027-03-18\nBCE 2027-04-29\nBCE 2027-06-10\nBCE 2027-07-22\nBCE 2027-09-09\nBCE 2027-10-28\nBCE 2027-12-16"; + + ///Null when the list is valid, otherwise what is wrong with it. + public static string? Check(string list) + { + try + { + Parse(list); + return null; + } + catch (FormatException ex) + { + return ex.Message; + } + } + + public static IReadOnlyListParse(string list) + { + ArgumentNullException.ThrowIfNull(list); + var events = new List (); + var number = 0; + foreach (var raw in list.Split('\n')) + { + number++; + var line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) + { + continue; + } + + var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length != 2 || !DateOnly.TryParseExact(parts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)) + { + throw new FormatException($"Riga {number} dell'elenco delle banche centrali non valida: «{line}». Scrivi per esempio «FED 2026-12-09»."); + } + + var bank = parts[0].ToUpperInvariant(); + var (title, currency, at) = bank switch + { + "FED" => ("Decisione sui tassi della Fed", "USD", Zones.At(day, new TimeOnly(14, 0), Zones.NewYork)), + "BCE" or "ECB" => ("Decisione sui tassi della BCE", "EUR", Zones.At(day, new TimeOnly(14, 15), Zones.Frankfurt)), + _ => throw new FormatException($"Riga {number}: banca «{parts[0]}» sconosciuta, usa FED o BCE."), + }; + events.Add(new CalendarEvent(CalendarEventKinds.CentralBank, title, at, TimeKnown: true, Source, $"cb:{currency}:{day:yyyy-MM-dd}") + { + Currency = currency, + Impact = "High", + }); + } + + return events; + } +} + +/// Crypto Fear and Greed index of alternative.me (attribution required: the interface names the source). +public static class FearGreed +{ + public const string Source = "alternative.me"; + + public const string Attribution = "Indice di paura e avidità: alternative.me"; + + public static Uri Latest(int days) => new($"https://api.alternative.me/fng/?limit={days.ToString(CultureInfo.InvariantCulture)}&format=json"); + + public static IReadOnlyListParse(string json) + { + using var document = JsonDocument.Parse(json); + return document.RootElement.GetProperty("data").EnumerateArray() + .Select(item => + { + var value = double.Parse(ForexFactory.Text(item, "value"), CultureInfo.InvariantCulture); + var at = DateTimeOffset.FromUnixTimeSeconds(long.Parse(ForexFactory.Text(item, "timestamp"), CultureInfo.InvariantCulture)); + return new MoodReading(MoodIndicators.FearGreed, at, value, MoodLabels.FearGreed(value), Source); + }) + .OrderBy(m => m.AsOf) + .ToList(); + } +} + +/// Daily VIX history from Cboe (no key). The file answers with a redirect to cdn-api.cboe.com. +public static class VixHistory +{ + public const string Source = "cboe"; + + public static readonly Uri Csv = new("https://cdn.cboe.com/api/global/us_indices/daily_prices/VIX_History.csv"); + + ///Closes on or after + public static IReadOnlyList, dated at midnight UTC of the session day. Parse(string csv, DateOnly from) + { + ArgumentNullException.ThrowIfNull(csv); + var readings = new List (); + foreach (var line in csv.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Skip(1)) + { + var f = line.Split(','); + var day = DateOnly.ParseExact(f[0], "MM/dd/yyyy", CultureInfo.InvariantCulture); + if (day < from || f.Length < 5) + { + continue; + } + + var close = double.Parse(f[4], CultureInfo.InvariantCulture); + readings.Add(new MoodReading(MoodIndicators.Vix, QualityChecks.Midnight(day), close, MoodLabels.Vix(close), Source)); + } + + return readings; + } +} + +/// A row of nasdaqtraded.txt: every security traded in the USA with its ETF flag. +public sealed record ListedSecurity(string Symbol, string Name, string Exchange, bool IsEtf, bool IsTest, string FinancialStatus) +{ + ///+ /// ETF, ETN, fund, or not a common share (preferred, warrant, right, unit, note): excluded from the stock universe + /// (SPEC 4.6, 8.2). The ETF flag misses many ETNs and every closed-end fund, so the name is read too. + /// + public bool IsExcluded => IsEtf || IsTest || NotCommon().IsMatch(Name); + + private static Regex NotCommon() => NasdaqTraded.NotCommonPattern(); +} + +///The public list of US securities (SPEC 4.1): https://www.nasdaqtrader.com/dynamic/SymDir/nasdaqtraded.txt. +public static partial class NasdaqTraded +{ + public const string Source = "nasdaqtrader"; + + public static readonly Uri File = new("https://www.nasdaqtrader.com/dynamic/SymDir/nasdaqtraded.txt"); + + ///Listing exchange codes: Q Nasdaq, N NYSE, A NYSE American, P NYSE Arca, Z Cboe BZX, V IEX, F Texas Stock Exchange, M NYSE Texas. + public static readonly IReadOnlyDictionaryExchanges = new Dictionary + { + ["Q"] = "NASDAQ", + ["N"] = "NYSE", + ["A"] = "AMEX", + ["P"] = "ARCA", + ["Z"] = "BATS", + ["V"] = "IEX", + ["F"] = "TXSE", + ["M"] = "NYSETX", + }; + + [GeneratedRegex(@"\b(ETF|ETN|ETNs|Exchange[- ]Traded|Fund|Funds|Trust Units?|Warrants?|Rights?|Units?|Preferred|Notes?|Debentures?|Depositary Shares? representing a fraction|Closed[- ]End|Income Shares|Beneficial Interest|Index|Leveraged|Inverse|SPAC)\b", RegexOptions.IgnoreCase)] + internal static partial Regex NotCommonPattern(); + + /// + /// Marks as funds the broker's instruments that this list (or their own name) shows are not common shares. Symbols + /// the list does not know keep only the name check. + /// + public static IReadOnlyListMarkFunds(IEnumerable specs, IReadOnlyList listed) + { + ArgumentNullException.ThrowIfNull(specs); + ArgumentNullException.ThrowIfNull(listed); + var bySymbol = listed.GroupBy(l => l.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); + return specs.Select(s => s with + { + IsFund = s.IsFund == true || (bySymbol.TryGetValue(s.Symbol, out var l) && l.IsExcluded) || NotCommonPattern().IsMatch(s.Name), + }).ToList(); + } + + /// Rows of the pipe-separated file (CRLF), header and footer skipped. + public static IReadOnlyListParse(string text) + { + ArgumentNullException.ThrowIfNull(text); + var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var header = lines[0].Split('|'); + int Column(string name) => Array.IndexOf(header, name) is var i and >= 0 ? i : throw new FormatException("nasdaqtraded.txt: manca la colonna " + name); + int symbol = Column("Symbol"), name = Column("Security Name"), exchange = Column("Listing Exchange"), etf = Column("ETF"), + test = Column("Test Issue"), status = Column("Financial Status"); + var list = new List (); + foreach (var line in lines.Skip(1)) + { + if (line.StartsWith("File Creation Time", StringComparison.Ordinal)) + { + continue; + } + + var f = line.Split('|'); + if (f.Length < header.Length) + { + continue; + } + + list.Add(new ListedSecurity(f[symbol], f[name], Exchanges.GetValueOrDefault(f[exchange], f[exchange]), f[etf] == "Y", f[test] == "Y", f[status])); + } + + return list; + } +} + +/// +/// The public archives of data.binance.vision (SPEC 4.2, 6.6): monthly zips of klines with a SHA-256 checksum file. +/// Research only: Binance does not serve Italian residents since July 2026. +/// +public static class BinanceArchive +{ + public const string Host = "https://data.binance.vision"; + + public static Uri Monthly(string symbol, string interval, int year, int month) => + new($"{Host}/data/spot/monthly/klines/{symbol}/{interval}/{symbol}-{interval}-{year:D4}-{month:D2}.zip"); + + public static Uri Daily(string symbol, string interval, DateOnly day) => + new($"{Host}/data/spot/daily/klines/{symbol}/{interval}/{symbol}-{interval}-{day:yyyy-MM-dd}.zip"); + + public static Uri ChecksumOf(Uri zip) => new(zip + ".CHECKSUM"); + + ///Checks the zip against its CHECKSUM file: "<sha256 hex> <file name>". + public static bool Verify(byte[] zip, string checksumFile) + { + ArgumentNullException.ThrowIfNull(checksumFile); + var expected = checksumFile.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries)[0]; + return string.Equals(Convert.ToHexStringLower(SHA256.HashData(zip)), expected, StringComparison.OrdinalIgnoreCase); + } + + public static IReadOnlyListReadZip(byte[] zip) + { + using var archive = new ZipArchive(new MemoryStream(zip), ZipArchiveMode.Read); + var entry = archive.Entries.Single(e => e.Name.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)); + using var reader = new StreamReader(entry.Open()); + return ParseCsv(reader.ReadToEnd()); + } + + /// + /// Klines without header: open_time, open, high, low, close, volume, close_time, quote_volume, trades, … The + /// open time is in milliseconds up to 2024 and in microseconds from 2025; the last column is ignored. + /// + public static IReadOnlyListParseCsv(string csv) + { + ArgumentNullException.ThrowIfNull(csv); + var bars = new List (); + foreach (var line in csv.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var f = line.Split(','); + if (f.Length < 9 || !long.TryParse(f[0], NumberStyles.None, CultureInfo.InvariantCulture, out var time)) + { + continue; // A header line some archives carry. + } + + bars.Add(new ResearchBar(FromEpoch(time), Number(f[1]), Number(f[2]), Number(f[3]), Number(f[4]), Number(f[5])) + { + QuoteVolume = Number(f[7]), + Trades = long.Parse(f[8], NumberStyles.None, CultureInfo.InvariantCulture), + }); + } + + return bars; + } + + /// Microseconds when the number is too large to be milliseconds (after year 5138). + public static DateTimeOffset FromEpoch(long value) => + value >= 100_000_000_000_000 ? DateTimeOffset.UnixEpoch.AddTicks(value * 10) : DateTimeOffset.FromUnixTimeMilliseconds(value); + + private static decimal Number(string text) => decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture); +} + +///Time zones of the exchanges and central banks, from the system's database (both Windows and Linux know the IANA ids). +public static class Zones +{ + public static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + public static readonly TimeZoneInfo Frankfurt = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); + + public static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + + public static DateTimeOffset At(DateOnly day, TimeOnly time, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(zone); + var local = day.ToDateTime(time); + return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime(); + } +} diff --git a/src/Anubis/Data/Freshness.cs b/src/Anubis/Data/Freshness.cs new file mode 100644 index 0000000..8b122e7 --- /dev/null +++ b/src/Anubis/Data/Freshness.cs @@ -0,0 +1,103 @@ +using System.Collections.Concurrent; +using Anubis.Core; + +namespace Anubis.Data; + +///Published when an instrument's live data become stale or fresh again (SPEC 6.5). +public sealed record FreshnessChanged(Guid InstrumentId, string Symbol, bool Fresh, DateTimeOffset? LastDataAt, DateTimeOffset At); + +///+/// Watches the age of the last live datum of each followed instrument, not the state of the connection (trap 10): +/// a feed that stays connected but stops sending is stale after +public sealed class FreshnessMonitor(IClock clock, EventBus bus, TimeSpan? maxAge = null) +{ + ///, and risk blocks new entries +/// on that instrument (SPEC 6.5, 9.2). Exits and stops are never blocked by this. +/// Maximum age of live prices (SPEC 6.5). + public static readonly TimeSpan DefaultMaxAge = TimeSpan.FromSeconds(60); + + private readonly ConcurrentDictionary_entries = new(); + + // Touch runs on the feed, Check on a timer: updates go one at a time so neither overwrites a newer datum. + private readonly Lock _gate = new(); + + public TimeSpan MaxAge { get; } = maxAge ?? DefaultMaxAge; + + public sealed record Status(Guid InstrumentId, string Symbol, DateTimeOffset? LastDataAt, bool Fresh, TimeSpan? Age); + + private sealed record Entry(string Symbol, DateTimeOffset FollowedSince, DateTimeOffset? LastDataAt, bool Fresh); + + /// Starts watching an instrument. Until its first datum it counts as stale. + public void Follow(Guid instrumentId, string symbol) => + _entries.TryAdd(instrumentId, new Entry(symbol, clock.UtcNow, null, false)); + + public void Unfollow(Guid instrumentId) + { + lock (_gate) + { + _entries.TryRemove(instrumentId, out _); + } + } + + public IReadOnlyCollectionFollowed => _entries.Keys.ToList(); + + /// A datum arrived. + public void Touch(Guid instrumentId, DateTimeOffset dataAt) + { + var now = clock.UtcNow; + var seen = dataAt > now ? now : dataAt; + Entry entry, updated; + lock (_gate) + { + if (!_entries.TryGetValue(instrumentId, out entry!)) + { + return; + } + + updated = entry with { LastDataAt = entry.LastDataAt is { } last && last > seen ? last : seen }; + updated = updated with { Fresh = IsFresh(updated, now) }; + _entries[instrumentId] = updated; + } + + if (updated.Fresh && !entry.Fresh) + { + bus.Publish(new FreshnessChanged(instrumentId, entry.Symbol, true, updated.LastDataAt, now)); + } + } + + ///is the venue's time; the age counts from when it arrived here if that is earlier. Re-evaluates every instrument and publishes the changes. Called every few seconds by the collector. + public void Check() + { + var now = clock.UtcNow; + var changes = new List(); + lock (_gate) + { + foreach (var (id, entry) in _entries) + { + var fresh = IsFresh(entry, now); + if (fresh != entry.Fresh) + { + _entries[id] = entry with { Fresh = fresh }; + changes.Add(new FreshnessChanged(id, entry.Symbol, fresh, entry.LastDataAt, now)); + } + } + } + + foreach (var change in changes) + { + bus.Publish(change); + } + } + + /// Whether new entries may use this instrument's live prices now. + public bool IsFresh(Guid instrumentId) => _entries.TryGetValue(instrumentId, out var entry) && IsFresh(entry, clock.UtcNow); + + public IReadOnlyListSnapshot() + { + var now = clock.UtcNow; + return _entries.Select(e => new Status(e.Key, e.Value.Symbol, e.Value.LastDataAt, IsFresh(e.Value, now), now - e.Value.LastDataAt)) + .OrderBy(s => s.Symbol, StringComparer.Ordinal).ToList(); + } + + private bool IsFresh(Entry entry, DateTimeOffset now) => entry.LastDataAt is { } last && now - last <= MaxAge; +} diff --git a/src/Anubis/Data/Importers.cs b/src/Anubis/Data/Importers.cs new file mode 100644 index 0000000..3f5ea09 --- /dev/null +++ b/src/Anubis/Data/Importers.cs @@ -0,0 +1,246 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Anubis.Brokers; +using Anubis.Core; + +namespace Anubis.Data; + +/// What an import did, for the log and the interface. +public sealed record ImportResult(string Venue, string Symbol, string Timeframe, int Bars, DateTimeOffset? First, DateTimeOffset? Last, IReadOnlyListNotes); + +/// +/// Downloads the monthly kline archives of data.binance.vision into the research history (issue #21). Every zip +/// is checked against its SHA-256 file before use; a month not published yet (404) ends the run without error. +/// Years already complete on disk are skipped. +/// +public sealed class BinanceImporter(ApiHttp http, ResearchStore store, IClock clock) +{ + ///The archive serves files from S3: a few requests a second is far below any limit. + private readonly RateLimiter _limiter = new(clock, 5, TimeSpan.FromSeconds(1)); + + public async TaskImportAsync(string symbol, string interval, int fromYear, int fromMonth, CancellationToken cancellationToken) + { + var timeframe = interval == "1m" ? Timeframes.Minute : interval == "1d" ? Timeframes.Day : interval; + var notes = new List (); + var total = 0; + DateTimeOffset? first = null, last = null; + var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + var have = store.Years(Venues.Binance, symbol, timeframe).ToHashSet(); + for (var month = new DateOnly(fromYear, fromMonth, 1); month <= today; month = month.AddMonths(1)) + { + // Months go in order, so a year is complete once the next one has a file. A year interrupted halfway is + // read again: writing merges with what is on disk. + if (have.Contains(month.Year) && have.Contains(month.Year + 1)) + { + continue; + } + + var url = BinanceArchive.Monthly(symbol, interval, month.Year, month.Month); + var zip = await http.GetBytesAsync(url, _limiter, null, cancellationToken).ConfigureAwait(false); + if (zip is null) + { + if (total > 0 || month >= new DateOnly(today.Year, today.Month, 1).AddMonths(-1)) + { + notes.Add($"{month:yyyy-MM}: archivio non ancora pubblicato"); + break; + } + + continue; // Before the pair was listed. + } + + var checksum = await http.GetStringAsync(BinanceArchive.ChecksumOf(url), _limiter, null, cancellationToken).ConfigureAwait(false); + if (!BinanceArchive.Verify(zip, checksum)) + { + throw new MarketDataException($"Binance: l'archivio {month:yyyy-MM} di {symbol} non corrisponde alla sua impronta SHA-256.", retryable: true); + } + + var bars = BinanceArchive.ReadZip(zip); + if (bars.Count == 0) + { + continue; + } + + await store.WriteAsync(Venues.Binance, symbol, timeframe, bars, cancellationToken).ConfigureAwait(false); + total += bars.Count; + first ??= bars[0].OpensAt; + last = bars[^1].OpensAt; + } + + return new ImportResult(Venues.Binance, symbol, timeframe, total, first, last, notes); + } +} + +/// +/// Column mapping of a user CSV in +public sealed record CsvMapping +{ + ////data/import (SPEC 6.6): a JSON file next to the CSV with the same name and +///.mapping.json , ormapping.json for the whole folder. Columns are named by header or by 0-based number. +///Symbol of the series, e.g. BTCEUR; when empty, the part of the file name before the first '-' or '_'. + public string? Symbol { get; init; } + + public string Venue { get; init; } = "import"; + + public string Timeframe { get; init; } = Timeframes.Minute; + + public string Delimiter { get; init; } = ","; + + public bool HasHeader { get; init; } = true; + + public string Time { get; init; } = "0"; + + ///+ public string TimeFormat { get; init; } = "auto"; + + /// unix_ms ,unix_s ,unix_us ,auto (milliseconds or microseconds by size), or a .NET date format such asyyyy-MM-dd HH:mm:ss .Time zone of text times (IANA id); unix times are always UTC. + public string TimeZone { get; init; } = "UTC"; + + public string Open { get; init; } = "1"; + + public string High { get; init; } = "2"; + + public string Low { get; init; } = "3"; + + public string Close { get; init; } = "4"; + + public string Volume { get; init; } = "5"; + + public string? QuoteVolume { get; init; } + + ///Decimal separator of the numbers: "." or ","; with "," a "." is read as the thousands separator. + public string DecimalSeparator { get; init; } = "."; + + ///True for a market that never closes (crypto): every missing minute or day is reported as a gap. + public bool Continuous { get; init; } = true; + + public static readonly JsonSerializerOptions Json = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; +} + +///+/// The generic importer of user CSV files with one-minute or daily bars into the research history (issue #21). +/// Lines that cannot be read are counted and reported, never silently fixed. +/// +public sealed class CsvImporter(ResearchStore store) +{ + public const int MaxReportedErrors = 5; + + public static CsvMapping MappingFor(string csvPath) + { + ArgumentNullException.ThrowIfNull(csvPath); + var own = Path.ChangeExtension(csvPath, ".mapping.json"); + var shared = Path.Combine(Path.GetDirectoryName(csvPath) ?? ".", "mapping.json"); + var path = File.Exists(own) ? own : File.Exists(shared) ? shared : null; + return path is null ? new CsvMapping() : JsonSerializer.Deserialize(File.ReadAllText(path), CsvMapping.Json) ?? new CsvMapping(); + } + + public async Task ImportAsync(string csvPath, CsvMapping mapping, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(mapping); + var symbol = string.IsNullOrWhiteSpace(mapping.Symbol) + ? Path.GetFileNameWithoutExtension(csvPath).Split('-', '_')[0].ToUpperInvariant() + : mapping.Symbol; + var zone = TimeZoneInfo.FindSystemTimeZoneById(mapping.TimeZone); + var numbers = new NumberFormatInfo { NumberDecimalSeparator = mapping.DecimalSeparator, NumberGroupSeparator = mapping.DecimalSeparator == "," ? "." : "," }; + var style = mapping.DecimalSeparator == "," ? NumberStyles.Float | NumberStyles.AllowThousands : NumberStyles.Float; + var bars = new List (); + var notes = new List (); + var errors = 0; + string[]? header = null; + var lineNumber = 0; + foreach (var line in await File.ReadAllLinesAsync(csvPath, cancellationToken).ConfigureAwait(false)) + { + lineNumber++; + if (line.Length == 0) + { + continue; + } + + var fields = line.Split(mapping.Delimiter); + if (header is null && mapping.HasHeader) + { + header = fields.Select(f => f.Trim().Trim('"')).ToArray(); + continue; + } + + try + { + string Field(string column) => fields[Index(column, header)].Trim().Trim('"'); + decimal Number(string column) => decimal.Parse(Field(column), style, numbers); + bars.Add(new ResearchBar(ParseTime(Field(mapping.Time), mapping.TimeFormat, zone), Number(mapping.Open), Number(mapping.High), + Number(mapping.Low), Number(mapping.Close), Number(mapping.Volume)) + { + QuoteVolume = mapping.QuoteVolume is { Length: > 0 } q ? Number(q) : null, + }); + } + catch (Exception ex) when (ex is FormatException or IndexOutOfRangeException or OverflowException or ArgumentException) + { + if (++errors <= MaxReportedErrors) + { + notes.Add($"riga {lineNumber}: {ex.Message}"); + } + } + } + + if (errors > 0) + { + notes.Add($"{errors} righe non lette su {lineNumber}"); + } + + var ordered = bars.OrderBy(b => b.OpensAt).ToList(); + IReadOnlyList issues = []; + if (ordered.Count > 0 && mapping.Timeframe == Timeframes.Minute) + { + issues = QualityChecks.CheckMinutes(ordered.Select(b => b.ToBar()).ToList(), + mapping.Continuous ? QualityChecks.EveryMinute(ordered[0].OpensAt, ordered[^1].OpensAt.AddMinutes(1)) : null); + } + else if (ordered.Count > 0) + { + var days = ordered.Select(b => new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, + (double)b.Close, (double)b.Volume)).ToList(); + issues = QualityChecks.CheckDaily(days, mapping.Continuous ? QualityChecks.EveryDay(days[0].Day, days[^1].Day) : null); + } + + notes.AddRange(issues.Take(MaxReportedErrors).Select(i => $"{i.Kind} {i.StartsAt:yyyy-MM-dd HH:mm}: {i.Detail}")); + + await store.WriteAsync(mapping.Venue, symbol, mapping.Timeframe, bars, cancellationToken).ConfigureAwait(false); + return new ImportResult(mapping.Venue, symbol, mapping.Timeframe, bars.Count, ordered.FirstOrDefault()?.OpensAt, ordered.LastOrDefault()?.OpensAt, notes); + } + + private static int Index(string column, string[]? header) + { + if (int.TryParse(column, NumberStyles.None, CultureInfo.InvariantCulture, out var index)) + { + return index; + } + + var found = header is null ? -1 : Array.FindIndex(header, h => string.Equals(h, column, StringComparison.OrdinalIgnoreCase)); + return found >= 0 ? found : throw new ArgumentException($"colonna «{column}» assente"); + } + + private static DateTimeOffset ParseTime(string text, string format, TimeZoneInfo zone) + { + switch (format) + { + case "unix_s": + return DateTimeOffset.FromUnixTimeSeconds(long.Parse(text, CultureInfo.InvariantCulture)); + case "unix_ms": + return DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(text, CultureInfo.InvariantCulture)); + case "unix_us": + return DateTimeOffset.UnixEpoch.AddTicks(long.Parse(text, CultureInfo.InvariantCulture) * 10); + case "auto" when long.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var number): + return number < 100_000_000_000 ? DateTimeOffset.FromUnixTimeSeconds(number) : BinanceArchive.FromEpoch(number); + case "auto": + return DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + default: + var local = DateTime.ParseExact(text, format, CultureInfo.InvariantCulture, DateTimeStyles.None); + return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime(); + } + } +} diff --git a/src/Anubis/Data/InstrumentCatalog.cs b/src/Anubis/Data/InstrumentCatalog.cs new file mode 100644 index 0000000..df21905 --- /dev/null +++ b/src/Anubis/Data/InstrumentCatalog.cs @@ -0,0 +1,126 @@ +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +/// +/// The single instrument catalogue (SPEC 6.1): internal id, venue, venue symbol, class, currency, tick, lot, minimum +/// and status, refreshed every day from the venues. An instrument the venue stops listing is kept, marked +/// +public sealed class InstrumentCatalog(Database db, IClock clock) +{ + public const string Delisted = "delisted"; + + private const string Columns = + "id, venue, symbol, name, asset_class, quote_currency, base_currency, exchange, tick_size, lot_size, min_size, min_notional, " + + "status, fractionable, is_fund, listed_at, updated_at"; + + public sealed record SyncResult(int Added, int Updated, int Delisted); + + ///delisted : its history and the orders that used it still point to it. +///+ /// Writes what the venue listed today. With + public async Taskthe list is the venue's whole catalogue + /// and instruments missing from it become delisted. + /// SyncAsync(string venue, IReadOnlyCollection specs, bool complete, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(specs); + if (specs.Any(s => s.Venue != venue)) + { + throw new ArgumentException("Every instrument must belong to " + venue, nameof(specs)); + } + + var now = clock.UtcNow; + return await db.WriteAsync(async s => + { + var existing = (await s.QueryAsync($"SELECT {Columns} FROM instruments WHERE venue = @v", Read, ("v", venue)).ConfigureAwait(false)) + .ToDictionary(i => i.Symbol, StringComparer.Ordinal); + int added = 0, updated = 0, delisted = 0; + foreach (var spec in specs.DistinctBy(x => x.Symbol)) + { + if (existing.Remove(spec.Symbol, out var known)) + { + if (known.Spec != spec) + { + await s.ExecuteAsync( + "UPDATE instruments SET name = @name, asset_class = @class, quote_currency = @quote, base_currency = @base, exchange = @exchange, " + + "tick_size = @tick, lot_size = @lot, min_size = @min, min_notional = @notional, status = @status, fractionable = @fractionable, " + + "is_fund = @fund, listed_at = @listed, updated_at = @now WHERE id = @id", + cancellationToken, [.. Parameters(spec), ("now", now), ("id", known.Id)]).ConfigureAwait(false); + updated++; + } + } + else + { + await s.ExecuteAsync( + $"INSERT INTO instruments ({Columns}, created_at) VALUES (@id, @venue, @symbol, @name, @class, @quote, @base, @exchange, @tick, @lot, @min, @notional, " + + "@status, @fractionable, @fund, @listed, @now, @now)", + cancellationToken, [.. Parameters(spec), ("id", Ids.NewId(clock)), ("venue", venue), ("symbol", spec.Symbol), ("now", now)]).ConfigureAwait(false); + added++; + } + } + + if (complete) + { + foreach (var missing in existing.Values.Where(i => i.Spec.Status != Delisted)) + { + await s.ExecuteAsync("UPDATE instruments SET status = @status, updated_at = @now WHERE id = @id", cancellationToken, + ("status", Delisted), ("now", now), ("id", missing.Id)).ConfigureAwait(false); + delisted++; + } + } + + return new SyncResult(added, updated, delisted); + }, cancellationToken).ConfigureAwait(false); + } + + public Task FindAsync(string venue, string symbol, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM instruments WHERE venue = @v AND symbol = @s", Read, ("v", venue), ("s", symbol)), + cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM instruments WHERE id = @id", Read, ("id", id)), cancellationToken); + + public async Task > ListAsync(string? venue, CancellationToken cancellationToken) => + await db.ReadAsync(s => venue is null + ? s.QueryAsync($"SELECT {Columns} FROM instruments ORDER BY venue, symbol", Read) + : s.QueryAsync($"SELECT {Columns} FROM instruments WHERE venue = @v ORDER BY symbol", Read, ("v", venue)), + cancellationToken).ConfigureAwait(false); + + /// Finds or creates an instrument known only by name, for the research importers and tests. + public async TaskEnsureAsync(InstrumentSpec spec, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(spec); + if (await FindAsync(spec.Venue, spec.Symbol, cancellationToken).ConfigureAwait(false) is { } known) + { + return known; + } + + await SyncAsync(spec.Venue, [spec], complete: false, cancellationToken).ConfigureAwait(false); + return (await FindAsync(spec.Venue, spec.Symbol, cancellationToken).ConfigureAwait(false))!; + } + + private static (string, object?)[] Parameters(InstrumentSpec spec) => + [ + ("name", spec.Name), ("class", spec.AssetClass), ("quote", spec.QuoteCurrency), ("base", spec.BaseCurrency), ("exchange", spec.Exchange), + ("tick", spec.TickSize), ("lot", spec.LotSize), ("min", spec.MinSize), ("notional", spec.MinNotional), ("status", spec.Status), + ("fractionable", spec.Fractionable), ("fund", spec.IsFund), ("listed", spec.ListedAt), + ]; + + private static Instrument Read(DbRow r) => new( + r.Id("id"), + new InstrumentSpec(r.Text("venue"), r.Text("symbol"), r.Text("name"), r.Text("asset_class"), r.Text("quote_currency")) + { + BaseCurrency = r.TextOrNull("base_currency"), + Exchange = r.TextOrNull("exchange"), + TickSize = r.MoneyOrNull("tick_size"), + LotSize = r.MoneyOrNull("lot_size"), + MinSize = r.MoneyOrNull("min_size"), + MinNotional = r.MoneyOrNull("min_notional"), + Status = r.TextOrNull("status"), + Fractionable = r.IsNull("fractionable") ? null : r.Bool("fractionable"), + IsFund = r.IsNull("is_fund") ? null : r.Bool("is_fund"), + ListedAt = r.MomentOrNull("listed_at"), + }, + r.MomentOrNull("updated_at")); +} diff --git a/src/Anubis/Data/Market.cs b/src/Anubis/Data/Market.cs new file mode 100644 index 0000000..2c0cc69 --- /dev/null +++ b/src/Anubis/Data/Market.cs @@ -0,0 +1,163 @@ +namespace Anubis.Data; + +/// Where data and orders come from. The value is stored in +public static class Venues +{ + public const string Okx = "okx"; + public const string Alpaca = "alpaca"; + + ///instruments.venue .Research archives only (data.binance.vision): never a venue for orders (SPEC 4.2). + public const string Binance = "binance"; +} + +public static class AssetClasses +{ + public const string Crypto = "crypto"; + public const string Equity = "equity"; +} + +///Quality of a stored bar (SPEC 6.4). +public static class BarQuality +{ + ///Passed every check. + public const string Ok = "ok"; + + ///Failed a check and waits for a second reading: no entries on the instrument meanwhile. + public const string Suspect = "suspect"; + + ///Failed a check, but a second reading gave the same values: a real move, usable. + public const string Confirmed = "confirmed"; +} + +///+/// An instrument as the venue describes it (SPEC 6.1): trading rules come from the API every day, never from code. +/// +public sealed record InstrumentSpec( + string Venue, + string Symbol, + string Name, + string AssetClass, + string QuoteCurrency) +{ + public string? BaseCurrency { get; init; } + + ///is the venue's own identifier: BTC-EUR on OKX,AAPL on Alpaca. +///Listing exchange for stocks (NYSE, NASDAQ, ARCA…); null for crypto. + public string? Exchange { get; init; } + + public decimal? TickSize { get; init; } + + public decimal? LotSize { get; init; } + + public decimal? MinSize { get; init; } + + public decimal? MinNotional { get; init; } + + ///The venue's own word: + public string? Status { get; init; } + + public bool? Fractionable { get; init; } + + ///live ,suspend ,active ,inactive …ETF, ETN or fund: never bought, at most used as an indicator (SPEC 4.6). + public bool? IsFund { get; init; } + + public DateTimeOffset? ListedAt { get; init; } +} + +///An instrument of the catalogue: the internal id and what the venue said the last time it was read. +public sealed record Instrument(Guid Id, InstrumentSpec Spec, DateTimeOffset? UpdatedAt) +{ + public string Venue => Spec.Venue; + + public string Symbol => Spec.Symbol; + + public string AssetClass => Spec.AssetClass; + + public bool IsCrypto => Spec.AssetClass == AssetClasses.Crypto; + + ///The instrument is tradable today, as far as the venue says. + public bool IsLive => Spec.Status is null or "live" or "active"; +} + +///+/// A bar of a given length that opens at +public sealed record Bar(DateTimeOffset OpensAt, double Open, double High, double Low, double Close, double Volume) +{ + ///(UTC). Bars are analysis data and stay +/// floating point (SPEC 5.4). +/// Traded value in the quote currency, when the source gives it (OKX + public double? QuoteVolume { get; init; } +} + +///volCcyQuote ).+/// A daily bar. +public sealed record DailyBar(DateOnly Day, double Open, double High, double Low, double Close, double Volume) +{ + public double? QuoteVolume { get; init; } + + ///is the exchange date for stocks and the UTC date for crypto: a crypto day +/// opens at 00:00 UTC and closes at the next 00:00 UTC (trap 23). +/// Prices adjusted for splits and dividends as the source gave them (stocks only). + public Ohlc? Adjusted { get; init; } + + public string Quality { get; init; } = BarQuality.Ok; + + public Ohlc Prices => new(Open, High, Low, Close); +} + +public readonly record struct Ohlc(double Open, double High, double Low, double Close) +{ + public Ohlc Scale(double factor) => new(Open * factor, High * factor, Low * factor, Close * factor); +} + +///Best bid and ask: prices orders may use, so they are exact. +public sealed record Quote(string Symbol, decimal Bid, decimal Ask, DateTimeOffset At) +{ + public decimal? BidSize { get; init; } + + public decimal? AskSize { get; init; } + + public decimal Mid => (Bid + Ask) / 2m; + + ///Spread in basis points of the mid price; null when the book is empty or crossed. + public double? SpreadBp => Bid > 0 && Ask >= Bid ? (double)((Ask - Bid) / Mid * 10_000m) : null; +} + +///Something a live feed delivered. +public abstract record MarketEvent(string Symbol, DateTimeOffset At); + +public sealed record TradeEvent(string Symbol, DateTimeOffset At, decimal Price, decimal Size) : MarketEvent(Symbol, At); + +public sealed record QuoteEvent(Quote Quote) : MarketEvent(Quote.Symbol, Quote.At); + +///is the moment the venue gives, in UTC. A one-minute bar. +public sealed record BarEvent(string Symbol, Bar Bar, bool Closed) : MarketEvent(Symbol, Bar.OpensAt); + +///is false while the minute is still running. Kinds of corporate action (SPEC 6.10). +public static class CorporateActionKinds +{ + ///Forward or reverse split: + public const string Split = "split"; + + public const string CashDividend = "cash_dividend"; + + ///ratio new shares for each old one (2 = 2-for-1, 0.1 = 1-for-10).Dividend paid in shares: treated like a split with its ratio. + public const string StockDividend = "stock_dividend"; + + public const string SymbolChange = "symbol_change"; +} + +///A corporate action. +public sealed record CorporateAction(string Symbol, string Kind, DateOnly ExDate, string Source, string SourceKey) +{ + public decimal? Ratio { get; init; } + + public decimal? CashAmount { get; init; } + + public string? Currency { get; init; } + + public string? NewSymbol { get; init; } + + ///identifies it at the source, so a second reading does not add it twice. A split, reverse split or stock dividend: quantities and per-share levels change. + public bool ChangesShares => Kind is CorporateActionKinds.Split or CorporateActionKinds.StockDividend && Ratio is > 0m; +} diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs new file mode 100644 index 0000000..cace228 --- /dev/null +++ b/src/Anubis/Data/MarketDataService.cs @@ -0,0 +1,529 @@ +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Data; + +///+/// Everything Phase 2 collects, wired together (SPEC 6): catalogue, history, live crypto feed, reference sources, +/// universes and corporate actions. Short jobs run on the scheduler; long downloads (the first history, thousands of +/// stocks) run on a background worker the jobs only wake, so they never delay the other jobs. Alpaca uses only the +/// keys of the paper account ( +public sealed partial class MarketDataService : IDisposable +{ + ///_DEMO ): without them the stock part is off and the sources list says so. +///Start of the daily history asked for (SPEC Phase 2): OKX EUR pairs answer from November 2023. + public static readonly DateOnly HistoryFrom = new(2016, 1, 1); + + ///The three EUR pairs with the best liquidity (SPEC 4.2), followed live until the first universe exists. + public static readonly IReadOnlyListCoreCrypto = ["BTC-EUR", "ETH-EUR", "SOL-EUR"]; + + /// + /// Coins whose Binance USDT archives are kept for the research history before the EUR pairs existed (SPEC 8.1): + /// the largest non-stable coins by volume over 2017–2025. + /// + public static readonly IReadOnlyListBinanceCoins = + [ + "BTC", "ETH", "BNB", "SOL", "XRP", "ADA", "DOGE", "TRX", "DOT", "LINK", "LTC", "BCH", "AVAX", "XLM", "ATOM", "ETC", "UNI", "FIL", "NEAR", + "ICP", "APT", "ARB", "OP", "SHIB", "EOS", + ]; + + public const string AlpacaSource = "alpaca"; + public const string OkxSource = "okx"; + public const string HistorySource = "storico"; + public const string BinanceSource = "binance"; + + private readonly Database _db; + private readonly IClock _clock; + private readonly SecretStore _secrets; + private readonly DataDirectory? _data; + private readonly HttpClient _http; + private readonly Func ? _sockets; + private readonly ILogger _logger; + private readonly MarketCollector _okxCollector; + private readonly InstrumentCatalog _catalog; + private readonly UniverseStore _universes; + private readonly UniverseBuilder _builder; + private readonly SourceStateStore _states; + private readonly EventBus _bus; + private readonly SemaphoreSlim _work = new(0); + private readonly Lock _gate = new(); + private (string Key, string Secret, AlpacaClient Client)? _alpaca; + + public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data, + HttpMessageHandler? handler = null, Func ? sockets = null, ILogger? logger = null) + { + _db = db; + _clock = clock; + _bus = bus; + _secrets = secrets; + _data = data; + _sockets = sockets; + _logger = logger ?? NullLogger.Instance; + _http = handler is null + ? new HttpClient(new SocketsHttpHandler + { + PooledConnectionLifetime = TimeSpan.FromMinutes(10), + AutomaticDecompression = System.Net.DecompressionMethods.All, + }) + : new HttpClient(handler, disposeHandler: false); + _http.Timeout = TimeSpan.FromSeconds(60); + _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + + Okx = new OkxClient(_http, clock, null, sockets); + Freshness = new FreshnessMonitor(clock, bus); + References = new ReferenceSources(new ApiHttp(_http, clock, "reference"), db, clock, settings, secrets.RevealAsync, Okx); + UsCalendar = new StoredMarketCalendar(db, clock, "us_equity"); + _okxCollector = new MarketCollector(Okx, db, clock, bus, Freshness, logger: _logger); + _catalog = new InstrumentCatalog(db, clock); + _universes = new UniverseStore(db, clock); + _builder = new UniverseBuilder(db, clock); + _states = new SourceStateStore(db, clock); + } + + public OkxClient Okx { get; } + + public FreshnessMonitor Freshness { get; } + + public ReferenceSources References { get; } + + public StoredMarketCalendar UsCalendar { get; } + + /// True while the live crypto feed is connected. + public bool LiveConnected => _okxCollector.Connected; + + ///When the background worker last finished a round, for the interface. + public DateTimeOffset? LastHistoryRun { get; private set; } + + ///The scheduled jobs (SPEC 5.5, 6). Times of the stock market come from the broker's calendar. + public IReadOnlyListJobs() => + [ + new("dati-storico", "Storico giornaliero, catalogo e universi", Schedule.Daily(new TimeOnly(0, 20), TimeZoneInfo.Utc), _ => WakeWorker()) + { MaxLateness = TimeSpan.FromHours(6) }, + new("dati-azioni-chiusura", "Barre giornaliere delle azioni dopo la chiusura", Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(30), UsCalendar), + _ => WakeWorker()) { MaxLateness = TimeSpan.FromHours(6) }, + new("dati-cambi-mattina", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(8, 0), Zones.Rome), References.RefreshFxAsync) + { MaxLateness = TimeSpan.FromHours(4) }, + new("dati-cambi-pomeriggio", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(16, 30), Zones.Rome), References.RefreshFxAsync) + { MaxLateness = TimeSpan.FromHours(4) }, + new("dati-calendario", "Calendario economico, riunioni e trimestrali", Schedule.Every(TimeSpan.FromHours(1)), RefreshCalendarAsync) + { MaxLateness = TimeSpan.FromMinutes(50) }, + new("dati-umore", "Umore del mercato", Schedule.Every(TimeSpan.FromHours(1)), References.RefreshMoodAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, + new("dati-spread", "Campione orario degli spread delle crypto", Schedule.Every(TimeSpan.FromHours(1)), SampleSpreadsAsync) + { MaxLateness = TimeSpan.FromMinutes(50) }, + new("dati-calendario-borsa", "Calendario di borsa di Alpaca", Schedule.Daily(new TimeOnly(4, 0), Zones.Rome), RefreshUsCalendarAsync) + { MaxLateness = TimeSpan.FromHours(12) }, + new("dati-azioni-societarie", "Frazionamenti e dividendi prima dell'apertura", Schedule.Market(MarketAnchor.Open, TimeSpan.FromHours(-1), UsCalendar), + RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, + new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync) + { MaxLateness = TimeSpan.FromHours(12) }, + ]; + + /// + /// Runs until cancelled: the background worker (woken at start and by the jobs), the live crypto feed, and the + /// freshness check every five seconds. + /// + public async Task RunAsync(CancellationToken cancellationToken) + { + await UsCalendar.LoadAsync(cancellationToken).ConfigureAwait(false); + _work.Release(); + await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), FreshnessAsync(cancellationToken)).ConfigureAwait(false); + } + + public Task WakeWorker() + { + if (_work.CurrentCount == 0) + { + _work.Release(); + } + + return Task.CompletedTask; + } + + public void Dispose() + { + _work.Dispose(); + _http.Dispose(); + } + + ///The Alpaca client with the paper account keys, or null when they are missing. + public async TaskAlpacaAsync(CancellationToken cancellationToken) + { + var key = await _secrets.RevealAsync("ALPACA_API_KEY_DEMO", cancellationToken).ConfigureAwait(false); + var secret = await _secrets.RevealAsync("ALPACA_API_SECRET_DEMO", cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(secret)) + { + await _states.RecordAsync(AlpacaSource, enabled: false, success: false, null, + "Spento: mancano le chiavi del conto di prova Alpaca (ALPACA_API_KEY_DEMO e ALPACA_API_SECRET_DEMO). La parte azionaria aspetta.", + cancellationToken).ConfigureAwait(false); + return null; + } + + lock (_gate) + { + if (_alpaca is { } cached && cached.Key == key && cached.Secret == secret) + { + return cached.Client; + } + + var client = new AlpacaClient(_http, _clock, new AlpacaCredentials(key, secret), null, _sockets); + _alpaca = (key, secret, client); + return client; + } + } + + /// One round of the long work, in order; each step records its outcome and never stops the next. + public async Task HistoryRoundAsync(CancellationToken cancellationToken) + { + var alpaca = await AlpacaAsync(cancellationToken).ConfigureAwait(false); + await StepAsync(OkxSource, () => SyncOkxCatalogAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + if (alpaca is not null) + { + await StepAsync(AlpacaSource, () => SyncAlpacaCatalogAsync(alpaca, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + await StepAsync(HistorySource, () => CryptoHistoryAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + if (alpaca is not null) + { + await StepAsync(HistorySource + "_azioni", () => EquityHistoryAsync(alpaca, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + if (_data is not null) + { + await StepAsync(BinanceSource, () => BinanceArchivesAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + } + + LastHistoryRun = _clock.UtcNow; + } + + private async Task WorkerAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + await _work.WaitAsync(cancellationToken).ConfigureAwait(false); + await HistoryRoundAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // A failure outside the single steps (the database during a restart, a secret that cannot be read) ends + // this round only: the worker waits and is ready for the next wake-up. + LogStepFailed(_logger, ex, "history round"); + try + { + await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + } + } + } + + private async Task StepAsync(string source, Func> step, CancellationToken cancellationToken) + { + try + { + var note = await step().ConfigureAwait(false); + await _states.RecordAsync(source, enabled: true, success: true, null, note, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var reason = Redactor.Redact(ex.Message); + LogStepFailed(_logger, ex, source); + await _states.RecordAsync(source, enabled: true, success: false, reason, null, cancellationToken).ConfigureAwait(false); + } + } + + private async Task SyncOkxCatalogAsync(CancellationToken cancellationToken) + { + var result = await _catalog.SyncAsync(Venues.Okx, await Okx.ListInstrumentsAsync(cancellationToken).ConfigureAwait(false), complete: true, cancellationToken) + .ConfigureAwait(false); + return $"catalogo: {result.Added} nuovi, {result.Updated} cambiati, {result.Delisted} tolti"; + } + + private async Task SyncAlpacaCatalogAsync(AlpacaClient alpaca, CancellationToken cancellationToken) + { + var assets = await alpaca.ListInstrumentsAsync(cancellationToken).ConfigureAwait(false); + var listed = NasdaqTraded.Parse(await new ApiHttp(_http, _clock, NasdaqTraded.Source).GetStringAsync(NasdaqTraded.File, null, null, cancellationToken) + .ConfigureAwait(false)); + var result = await _catalog.SyncAsync(Venues.Alpaca, NasdaqTraded.MarkFunds(assets, listed), complete: true, cancellationToken).ConfigureAwait(false); + return $"catalogo: {result.Added} nuovi, {result.Updated} cambiati, {result.Delisted} tolti"; + } + + private async Task > CryptoCandidatesAsync(CancellationToken cancellationToken) => + (await _catalog.ListAsync(Venues.Okx, cancellationToken).ConfigureAwait(false)) + .Where(i => i.IsLive && i.IsCrypto && i.Spec.QuoteCurrency == "EUR" && !CryptoUniverse.Excluded(i.Spec.BaseCurrency ?? "")) + .ToList(); + + private async Task CryptoHistoryAsync(CancellationToken cancellationToken) + { + var total = CollectionResult.None; + var failed = new List (); + foreach (var instrument in await CryptoCandidatesAsync(cancellationToken).ConfigureAwait(false)) + { + try + { + total = total.Add(await _okxCollector.BackfillDailyAsync(instrument, HistoryFrom, cancellationToken).ConfigureAwait(false)); + } + catch (Exception ex) when (ex is MarketDataException or HttpRequestException or TaskCanceledException && !cancellationToken.IsCancellationRequested) + { + failed.Add(instrument.Symbol); + LogInstrumentFailed(_logger, ex, instrument.Symbol); + } + } + + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var monthStart = new DateOnly(today.Year, today.Month, 1); + var current = await _universes.AsOfAsync(Universes.Crypto, today, cancellationToken).ConfigureAwait(false); + var computedThisMonth = await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM universe_members WHERE universe = @u AND as_of >= @d", + ("u", Universes.Crypto), ("d", BarStore.DayText(monthStart))), cancellationToken).ConfigureAwait(false) > 0; + var note = ""; + if (current.Count == 0 || !computedThisMonth) + { + var members = await _builder.CryptoAsync(today, async i => + { + try + { + return (await Okx.FetchQuoteAsync(i.Symbol, cancellationToken).ConfigureAwait(false)).SpreadBp; + } + catch (MarketDataException) + { + return null; + } + }, cancellationToken).ConfigureAwait(false); + note = $"; universo crypto: {string.Join(", ", members.Select(m => m.Symbol))}"; + } + + return $"crypto: {total.Stored} barre, {total.Gaps} buchi, {total.Suspect} anomalie" + + (failed.Count > 0 ? $"; non riuscite: {string.Join(", ", failed.Take(10))}" : "") + note; + } + + private async Task EquityHistoryAsync(AlpacaClient alpaca, CancellationToken cancellationToken) + { + // Trading days come from the broker's calendar; days it does not cover are not checked for gaps. + var collector = new MarketCollector(alpaca, _db, _clock, _bus, Freshness, + expectedDays: (_, from, to) => UsCalendar.Sessions(from, to) is { Count: > 0 } sessions ? sessions.Select(x => x.Date) : null, logger: _logger); + var bars = new BarStore(_db, _clock); + var eligible = (await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false)).Where(i => EquityUniverse.Eligible(i.Spec)).ToList(); + // The last New York session whose consolidated bar is final (16 minutes after the close), so the run after the + // close already collects that day. Without the calendar, yesterday. + var now = _clock.UtcNow; + var today = DateOnly.FromDateTime(now.UtcDateTime); + var closed = UsCalendar.Sessions(today.AddDays(-10), today.AddDays(1)).Where(s => s.CloseUtc + TimeSpan.FromMinutes(16) <= now).ToList(); + var yesterday = closed.Count > 0 ? closed[^1].Date : today.AddDays(-1); + var total = CollectionResult.None; + + // Grouped by the first missing day, so one request serves up to a hundred symbols. + var starts = new List<(Instrument Instrument, DateOnly First)>(); + foreach (var instrument in eligible) + { + var last = await bars.LastDayAsync(instrument.Id, cancellationToken).ConfigureAwait(false); + if (!instrument.IsLive && last is not null) + { + continue; // Delisted with its history already here: nothing new will come, and each would cost requests of its own. + } + + starts.Add((instrument, last?.AddDays(1) ?? HistoryFrom)); + } + + foreach (var group in starts.Where(s => s.First <= yesterday).GroupBy(s => s.First)) + { + foreach (var chunk in group.Chunk(100)) + { + // From the day before the group's first missing day: for symbols with history that is the last day held, + // which the collector compares to find new splits and dividends. + var from = group.Key == HistoryFrom ? group.Key : group.Key.AddDays(-1); + var fetched = await alpaca.FetchDailyBarsAsync(chunk.Select(c => c.Instrument.Symbol).ToList(), from, yesterday, cancellationToken) + .ConfigureAwait(false); + foreach (var (instrument, first) in chunk) + { + var list = fetched.TryGetValue(instrument.Symbol, out var b) ? b : []; + total = total.Add(await collector.BackfillDailyAsync(instrument, first, cancellationToken, list, yesterday).ConfigureAwait(false)); + } + } + } + + var recent = UsCalendar.Sessions(yesterday.AddDays(-10), yesterday); + var session = recent.Count > 0 ? recent[^1].Date : yesterday; + var members = await _builder.EquityAsync(session, cancellationToken).ConfigureAwait(false); + return $"azioni: {eligible.Count} titoli, {total.Stored} barre, {total.Suspect} anomalie; universo del {session:dd/MM/yyyy}: {members.Count} titoli"; + } + + private async Task BinanceArchivesAsync(CancellationToken cancellationToken) + { + // Once a month is enough: the archive publishes a month when it ends. + var states = await _states.ListAsync(cancellationToken).ConfigureAwait(false); + if (states.FirstOrDefault(s => s.Source == BinanceSource)?.LastSuccessAt is { } last && _clock.UtcNow - last < TimeSpan.FromDays(25)) + { + return states.First(s => s.Source == BinanceSource).Note ?? ""; + } + + var importer = new BinanceImporter(new ApiHttp(_http, _clock, BinanceSource), new ResearchStore(_data!.Research), _clock); + var bars = 0; + foreach (var coin in BinanceCoins) + { + var result = await importer.ImportAsync(coin + "USDT", "1d", 2017, 8, cancellationToken).ConfigureAwait(false); + bars += result.Bars; + } + + return $"archivi Binance: {BinanceCoins.Count} monete, {bars} barre giornaliere lette"; + } + + private async Task RefreshCalendarAsync(CancellationToken cancellationToken) + { + await References.RefreshCalendarAsync(cancellationToken).ConfigureAwait(false); + await References.RefreshFredAsync(cancellationToken).ConfigureAwait(false); + var universe = await _universes.AsOfAsync(Universes.Equity, DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime), cancellationToken).ConfigureAwait(false); + await References.RefreshEarningsAsync(universe.Count == 0 ? null : universe.Select(m => m.Symbol).ToHashSet(StringComparer.Ordinal), cancellationToken) + .ConfigureAwait(false); + } + + private async Task SampleSpreadsAsync(CancellationToken cancellationToken) + { + var hour = new DateTimeOffset(_clock.UtcNow.UtcTicks - (_clock.UtcNow.UtcTicks % TimeSpan.TicksPerHour), TimeSpan.Zero); + foreach (var instrument in await CryptoCandidatesAsync(cancellationToken).ConfigureAwait(false)) + { + try + { + if ((await Okx.FetchQuoteAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false)).SpreadBp is { } bp) + { + await _universes.AddSpreadAsync(instrument.Id, hour, bp, cancellationToken).ConfigureAwait(false); + } + } + catch (MarketDataException ex) + { + LogInstrumentFailed(_logger, ex, instrument.Symbol); + } + } + } + + private async Task RefreshUsCalendarAsync(CancellationToken cancellationToken) + { + if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca) + { + return; + } + + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var sessions = await alpaca.FetchCalendarAsync(today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false); + await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false); + } + + private async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) + { + if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca) + { + return; + } + + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var universe = await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false); + if (universe.Count == 0) + { + return; + } + + var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), today.AddDays(-7), today.AddDays(30), cancellationToken) + .ConfigureAwait(false); + await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false); + } + + private async Task PruneAsync(CancellationToken cancellationToken) + { + await new BarStore(_db, _clock).PruneMinutesAsync(cancellationToken).ConfigureAwait(false); + await _universes.PruneSpreadsAsync(cancellationToken).ConfigureAwait(false); + } + + /// The live feed follows the crypto universe (or the three main pairs until one exists) and restarts when it changes. + private async Task LiveAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + var instruments = await LiveInstrumentsAsync(cancellationToken).ConfigureAwait(false); + if (instruments.Count == 0) + { + await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false); + continue; + } + + using var round = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var run = _okxCollector.RunLiveAsync(instruments, round.Token); + var ids = instruments.Select(i => i.Id).ToHashSet(); + while (!run.IsCompleted) + { + using var nap = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var wait = _clock.WaitUntilAsync(_clock.UtcNow.AddHours(1), nap.Token); + await Task.WhenAny(run, wait).ConfigureAwait(false); + await nap.CancelAsync().ConfigureAwait(false); + if (!run.IsCompleted && !(await LiveInstrumentsAsync(cancellationToken).ConfigureAwait(false)).Select(i => i.Id).ToHashSet().SetEquals(ids)) + { + await round.CancelAsync().ConfigureAwait(false); + } + } + + await run.ConfigureAwait(false); + foreach (var id in ids) + { + Freshness.Unfollow(id); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogStepFailed(_logger, ex, "live"); + await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false); + } + } + } + + private async Task> LiveInstrumentsAsync(CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var members = await _universes.AsOfAsync(Universes.Crypto, today, cancellationToken).ConfigureAwait(false); + var symbols = members.Count > 0 ? members.Select(m => m.Symbol).ToList() : CoreCrypto; + var all = (await _catalog.ListAsync(Venues.Okx, cancellationToken).ConfigureAwait(false)).ToDictionary(i => i.Symbol, StringComparer.Ordinal); + return symbols.Select(s => all.GetValueOrDefault(s)).OfType ().Where(i => i.IsLive).ToList(); + } + + private async Task FreshnessAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + await _clock.WaitUntilAsync(_clock.UtcNow.AddSeconds(5), cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + + Freshness.Check(); + } + } + + /// The quality report of the last + public Taskdays. ReportAsync(int days, CancellationToken cancellationToken) => + QualityReport.BuildAsync(_db, _clock, TimeSpan.FromDays(days), cancellationToken); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Market data step {Step} failed")] + private static partial void LogStepFailed(ILogger logger, Exception exception, string step); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Market data for {Symbol} failed")] + private static partial void LogInstrumentFailed(ILogger logger, Exception exception, string symbol); +} diff --git a/src/Anubis/Data/Quality.cs b/src/Anubis/Data/Quality.cs new file mode 100644 index 0000000..7b34a3c --- /dev/null +++ b/src/Anubis/Data/Quality.cs @@ -0,0 +1,301 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +/// What the data checks look for (SPEC 6.3, 6.4). +public static class IssueKinds +{ + public const string Duplicate = "duplicate"; + public const string Gap = "gap"; + public const string NonPositive = "non_positive"; + public const string HighBelowLow = "high_below_low"; + public const string Jump = "jump"; + public const string Stale = "stale"; + + ///Kinds that make a bar suspect: no entries until a second reading (SPEC 6.4). + public static bool MakesSuspect(string kind) => kind is NonPositive or HighBelowLow or Jump or Duplicate; +} + +public static class IssueStatus +{ + public const string Open = "open"; + + ///A gap filled by a later download. + public const string Recovered = "recovered"; + + ///A gap the source cannot fill, or an impossible bar confirmed by the source: recorded and left out. + public const string Unrecoverable = "unrecoverable"; + + ///A second reading gave the same values: a real move. + public const string Confirmed = "confirmed"; + + ///A second reading gave different values, which replaced the first ones. + public const string Corrected = "corrected"; +} + +public static class Timeframes +{ + public const string Day = "1d"; + public const string Minute = "1m"; +} + +///A problem found in a series. Moments are UTC; for daily bars they are the day at 00:00 UTC. +public sealed record QualityFinding(string Kind, DateTimeOffset StartsAt, DateTimeOffset EndsAt, string Detail); + +///+/// The automatic checks of SPEC 6.4, as pure functions over a series: duplicates, gaps against the expected +/// moments, null or negative prices, high below low, and jumps over 8 standard deviations of the previous returns. +/// +public static class QualityChecks +{ + public const double JumpSigmas = 8; + + ///Returns before the bar that give the standard deviation of the jump check. + public const int JumpWindow = 60; + + ///Fewer returns than this and the jump check is skipped: the deviation would mean little. + public const int JumpMinimum = 20; + + public static IReadOnlyListCheckDaily(IReadOnlyList bars, IEnumerable ? expectedDays = null) + { + ArgumentNullException.ThrowIfNull(bars); + var findings = new List (); + foreach (var group in bars.GroupBy(b => b.Day).Where(g => g.Count() > 1)) + { + var at = Midnight(group.Key); + var distinct = group.Select(b => b.Prices).Distinct().Count(); + findings.Add(new QualityFinding(IssueKinds.Duplicate, at, at, + $"{group.Count()} barre per lo stesso giorno" + (distinct > 1 ? ", con valori diversi" : ", identiche"))); + } + + var unique = bars.DistinctBy(b => b.Day).OrderBy(b => b.Day).ToList(); + foreach (var bar in unique) + { + CheckPrices(Midnight(bar.Day), bar.Open, bar.High, bar.Low, bar.Close, findings); + } + + // Splits and dividends would look like jumps on real prices: stocks are checked on their adjusted closes. + var closes = unique.Select(b => b.Adjusted?.Close ?? b.Close).ToList(); + foreach (var (index, detail) in Jumps(closes)) + { + var at = Midnight(unique[index].Day); + findings.Add(new QualityFinding(IssueKinds.Jump, at, at, detail)); + } + + if (expectedDays is not null && unique.Count > 0) + { + var have = unique.Select(b => Midnight(b.Day)).ToHashSet(); + foreach (var run in MissingRuns(expectedDays.Select(Midnight), have, Midnight(unique[0].Day), Midnight(unique[^1].Day))) + { + findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last, + run.Count == 1 ? "Manca la barra di un giorno" : $"Mancano le barre di {run.Count} giorni")); + } + } + + return findings; + } + + /// + /// Checks one-minute bars. + public static IReadOnlyListlists the minutes that should exist (every minute for + /// crypto, the session minutes for stocks); without it gaps are not looked for. + /// CheckMinutes(IReadOnlyList bars, IEnumerable ? expected = null) + { + ArgumentNullException.ThrowIfNull(bars); + var findings = new List (); + foreach (var group in bars.GroupBy(b => b.OpensAt).Where(g => g.Count() > 1)) + { + findings.Add(new QualityFinding(IssueKinds.Duplicate, group.Key, group.Key, $"{group.Count()} barre per lo stesso minuto")); + } + + var unique = bars.DistinctBy(b => b.OpensAt).OrderBy(b => b.OpensAt).ToList(); + foreach (var bar in unique) + { + CheckPrices(bar.OpensAt, bar.Open, bar.High, bar.Low, bar.Close, findings); + } + + foreach (var (index, detail) in Jumps(unique.Select(b => b.Close).ToList())) + { + findings.Add(new QualityFinding(IssueKinds.Jump, unique[index].OpensAt, unique[index].OpensAt, detail)); + } + + if (expected is not null && unique.Count > 0) + { + var have = unique.Select(b => b.OpensAt).ToHashSet(); + foreach (var run in MissingRuns(expected, have, unique[0].OpensAt, unique[^1].OpensAt)) + { + findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last, + run.Count == 1 ? "Manca la barra di un minuto" : $"Mancano {run.Count} minuti")); + } + } + + return findings; + } + + /// Every minute in [from, to): the expected moments of a market that never closes. + public static IEnumerableEveryMinute(DateTimeOffset from, DateTimeOffset to) + { + for (var t = from; t < to; t = t.AddMinutes(1)) + { + yield return t; + } + } + + public static IEnumerable EveryDay(DateOnly from, DateOnly to) + { + for (var d = from; d <= to; d = d.AddDays(1)) + { + yield return d; + } + } + + public static DateTimeOffset Midnight(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + + private static void CheckPrices(DateTimeOffset at, double open, double high, double low, double close, List findings) + { + if (open <= 0 || high <= 0 || low <= 0 || close <= 0 || !double.IsFinite(open + high + low + close)) + { + findings.Add(new QualityFinding(IssueKinds.NonPositive, at, at, "Prezzo nullo, negativo o non valido")); + } + else if (high < low || high < Math.Max(open, close) || low > Math.Min(open, close)) + { + findings.Add(new QualityFinding(IssueKinds.HighBelowLow, at, at, + string.Create(CultureInfo.InvariantCulture, $"Massimo {high} e minimo {low} incoerenti con apertura {open} e chiusura {close}"))); + } + } + + /// Log returns further than 8 deviations from the mean of the previous 60. + private static IEnumerable<(int Index, string Detail)> Jumps(Listcloses) + { + var returns = new double[closes.Count]; + for (var i = 1; i < closes.Count; i++) + { + returns[i] = closes[i] > 0 && closes[i - 1] > 0 ? Math.Log(closes[i] / closes[i - 1]) : double.NaN; + } + + for (var i = JumpMinimum + 1; i < closes.Count; i++) + { + var window = returns.Skip(Math.Max(1, i - JumpWindow)).Take(i - Math.Max(1, i - JumpWindow)).Where(double.IsFinite).ToList(); + if (window.Count < JumpMinimum || !double.IsFinite(returns[i])) + { + continue; + } + + var mean = window.Average(); + var sigma = Math.Sqrt(window.Sum(r => (r - mean) * (r - mean)) / (window.Count - 1)); + if (sigma > 0 && Math.Abs(returns[i] - mean) > JumpSigmas * sigma) + { + yield return (i, string.Create(CultureInfo.InvariantCulture, + $"Variazione del {(Math.Exp(returns[i]) - 1) * 100:0.##}% pari a {Math.Abs(returns[i] - mean) / sigma:0.#} deviazioni standard")); + } + } + } + + /// + /// Expected moments between + private static List<(DateTimeOffset First, DateTimeOffset Last, int Count)> MissingRuns( + IEnumerableand with no bar, grouped in runs of + /// consecutive expected moments: a weekend between two missing sessions does not split the gap. + /// expected, HashSet have, DateTimeOffset first, DateTimeOffset last) + { + var runs = new List<(DateTimeOffset, DateTimeOffset, int)>(); + (DateTimeOffset First, DateTimeOffset Last, int Count)? current = null; + foreach (var moment in expected.Where(t => t >= first && t <= last).Distinct().Order()) + { + if (have.Contains(moment)) + { + if (current is { } done) + { + runs.Add(done); + current = null; + } + } + else + { + current = current is { } run ? (run.First, moment, run.Count + 1) : (moment, moment, 1); + } + } + + if (current is { } tail) + { + runs.Add(tail); + } + + return runs; + } +} + +/// A row of +public sealed record DataIssue( + Guid Id, Guid? InstrumentId, string Timeframe, string Kind, DateTimeOffset StartsAt, DateTimeOffset EndsAt, + string Status, int Attempts, string Detail, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt); + +///data_issues .+/// The register of what the checks found (SPEC 6.3, 6.4). Nothing is corrected in silence: every gap, suspect +/// bar and second reading leaves a row here, and the quality report reads it. +/// +public sealed class DataIssueStore(Database db, IClock clock) +{ + private const string Columns = "id, instrument_id, timeframe, kind, starts_at, ends_at, status, attempts, detail, created_at, updated_at"; + + ///Records a finding unless the same one (instrument, timeframe, kind, start) is already open. Returns its id. + public async TaskRecordAsync(Guid? instrumentId, string timeframe, QualityFinding finding, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(finding); + var now = clock.UtcNow; + return await db.WriteAsync(async s => + { + (string, object?)[] args = [("tf", timeframe), ("k", finding.Kind), ("s", finding.StartsAt), ("open", IssueStatus.Open)]; + var existing = await s.FirstOrDefaultAsync( + "SELECT id FROM data_issues WHERE " + (instrumentId is null ? "instrument_id IS NULL" : "instrument_id = @i") + + " AND timeframe = @tf AND kind = @k AND starts_at = @s AND status = @open", + r => (Guid?)r.Id("id"), instrumentId is null ? args : [.. args, ("i", instrumentId)]).ConfigureAwait(false); + if (existing is { } id) + { + return id; + } + + id = Ids.NewId(clock); + await s.ExecuteAsync( + $"INSERT INTO data_issues ({Columns}) VALUES (@id, @i, @tf, @k, @s, @e, @open, 0, @d, @now, @now)", cancellationToken, + ("id", id), ("i", instrumentId), ("tf", timeframe), ("k", finding.Kind), ("s", finding.StartsAt), ("e", finding.EndsAt), + ("open", IssueStatus.Open), ("d", finding.Detail), ("now", now)).ConfigureAwait(false); + return id; + }, cancellationToken).ConfigureAwait(false); + } + + /// Counts one more attempt at fixing an open issue (a download, a second reading). + public Task AttemptAsync(Guid id, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE data_issues SET attempts = attempts + 1, updated_at = @now WHERE id = @id", cancellationToken, + ("now", clock.UtcNow), ("id", id)), cancellationToken); + + public Task ResolveAsync(Guid id, string status, string? detail, CancellationToken cancellationToken) => + db.WriteAsync(s => detail is null + ? s.ExecuteAsync("UPDATE data_issues SET status = @st, updated_at = @now WHERE id = @id", cancellationToken, + ("st", status), ("now", clock.UtcNow), ("id", id)) + : s.ExecuteAsync("UPDATE data_issues SET status = @st, detail = @d, updated_at = @now WHERE id = @id", cancellationToken, + ("st", status), ("d", detail), ("now", clock.UtcNow), ("id", id)), cancellationToken); + + public async Task> OpenAsync(Guid? instrumentId, CancellationToken cancellationToken) => + await db.ReadAsync(s => instrumentId is null + ? s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE status = @open ORDER BY starts_at", Read, ("open", IssueStatus.Open)) + : s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE status = @open AND instrument_id = @i ORDER BY starts_at", Read, + ("open", IssueStatus.Open), ("i", instrumentId)), cancellationToken).ConfigureAwait(false); + + public async Task > SinceAsync(DateTimeOffset since, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE updated_at >= @t ORDER BY created_at", Read, ("t", since)), + cancellationToken).ConfigureAwait(false); + + /// Instruments with a suspect bar still waiting for its second reading: no entries on them (SPEC 6.4). + public async Task> BlockedInstrumentsAsync(CancellationToken cancellationToken) + { + var open = await OpenAsync(null, cancellationToken).ConfigureAwait(false); + return open.Where(i => i.InstrumentId is not null && IssueKinds.MakesSuspect(i.Kind)).Select(i => i.InstrumentId!.Value).ToHashSet(); + } + + private static DataIssue Read(DbRow r) => new( + r.Id("id"), r.IdOrNull("instrument_id"), r.Text("timeframe"), r.Text("kind"), r.Moment("starts_at"), r.Moment("ends_at"), + r.Text("status"), (int)r.Number("attempts"), r.Text("detail"), r.Moment("created_at"), r.Moment("updated_at")); +} diff --git a/src/Anubis/Data/QualityReport.cs b/src/Anubis/Data/QualityReport.cs new file mode 100644 index 0000000..ccd170c --- /dev/null +++ b/src/Anubis/Data/QualityReport.cs @@ -0,0 +1,106 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +/// History and problems of one instrument in the report. +public sealed record InstrumentQuality( + string Venue, string Symbol, long DailyBars, DateOnly? FirstDay, DateOnly? LastDay, long MinuteBars, + int Gaps, int Recovered, int Unrecoverable, int Suspect, int Confirmed, int Corrected, int Open); + +///+/// The data quality report of Phase 2 (SPEC 6.4): for each instrument how much history there is, what the checks +/// found in the period and how it ended, which problems are still open, and the state of every external source. +/// +public sealed record QualityReport( + DateTimeOffset From, DateTimeOffset To, IReadOnlyListInstruments, IReadOnlyList OpenIssues, IReadOnlyList Sources) +{ + public static async Task BuildAsync(Database db, IClock clock, TimeSpan period, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(clock); + var to = clock.UtcNow; + var from = to - period; + var issues = new DataIssueStore(db, clock); + var recent = await issues.SinceAsync(from, cancellationToken).ConfigureAwait(false); + var open = await issues.OpenAsync(null, cancellationToken).ConfigureAwait(false); + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT i.id, i.venue, i.symbol, (SELECT COUNT(*) FROM bars_1d b WHERE b.instrument_id = i.id) AS days, " + + "(SELECT MIN(day) FROM bars_1d b WHERE b.instrument_id = i.id) AS first_day, (SELECT MAX(day) FROM bars_1d b WHERE b.instrument_id = i.id) AS last_day, " + + "(SELECT COUNT(*) FROM bars_1m m WHERE m.instrument_id = i.id) AS minutes FROM instruments i ORDER BY i.venue, i.symbol", + r => (Id: r.Id("id"), Venue: r.Text("venue"), Symbol: r.Text("symbol"), Days: r.Number("days"), First: r.TextOrNull("first_day"), + Last: r.TextOrNull("last_day"), Minutes: r.Number("minutes"))), cancellationToken).ConfigureAwait(false); + + var instruments = new List (); + foreach (var row in rows) + { + var mine = recent.Where(i => i.InstrumentId == row.Id).ToList(); + if (row.Days == 0 && row.Minutes == 0 && mine.Count == 0) + { + continue; // In the catalogue but never collected: not part of the report. + } + + int Count(Func match) => mine.Count(match); + instruments.Add(new InstrumentQuality(row.Venue, row.Symbol, row.Days, row.First is null ? null : BarStore.ParseDay(row.First), + row.Last is null ? null : BarStore.ParseDay(row.Last), row.Minutes, + Count(i => i.Kind == IssueKinds.Gap), Count(i => i.Status == IssueStatus.Recovered), Count(i => i.Status == IssueStatus.Unrecoverable), + Count(i => IssueKinds.MakesSuspect(i.Kind)), Count(i => i.Status == IssueStatus.Confirmed), Count(i => i.Status == IssueStatus.Corrected), + open.Count(i => i.InstrumentId == row.Id))); + } + + var sources = await new SourceStateStore(db, clock).ListAsync(cancellationToken).ConfigureAwait(false); + return new QualityReport(from, to, instruments, open, sources); + } + + /// The report as Markdown, in the words the user reads (Italian). + public string ToMarkdown() + { + var it = CultureInfo.GetCultureInfo("it-IT"); + var text = new StringBuilder(); + text.AppendLine(it, $"# Qualità dei dati"); + text.AppendLine(); + text.AppendLine(it, $"Periodo: dal {From:dd/MM/yyyy HH:mm} al {To:dd/MM/yyyy HH:mm} (UTC)."); + text.AppendLine(); + var totals = (Gaps: Instruments.Sum(i => i.Gaps), Recovered: Instruments.Sum(i => i.Recovered), Lost: Instruments.Sum(i => i.Unrecoverable), + Suspect: Instruments.Sum(i => i.Suspect), Confirmed: Instruments.Sum(i => i.Confirmed), Corrected: Instruments.Sum(i => i.Corrected)); + text.AppendLine(it, $"In sintesi: {Instruments.Count} strumenti con dati, {totals.Gaps} buchi ({totals.Recovered} recuperati, {totals.Lost} non recuperabili), " + + $"{totals.Suspect} dati anomali ({totals.Confirmed} confermati, {totals.Corrected} corretti dalla seconda lettura), {OpenIssues.Count} problemi ancora aperti."); + text.AppendLine(); + text.AppendLine("## Strumenti"); + text.AppendLine(); + text.AppendLine("| Mercato | Strumento | Giorni | Dal | Al | Minuti | Buchi | Recuperati | Persi | Anomali | Confermati | Corretti | Aperti |"); + text.AppendLine("|---|---|---:|---|---|---:|---:|---:|---:|---:|---:|---:|---:|"); + foreach (var i in Instruments) + { + text.AppendLine(it, $"| {i.Venue} | {i.Symbol} | {i.DailyBars:N0} | {i.FirstDay:dd/MM/yyyy} | {i.LastDay:dd/MM/yyyy} | {i.MinuteBars:N0} | {i.Gaps} | " + + $"{i.Recovered} | {i.Unrecoverable} | {i.Suspect} | {i.Confirmed} | {i.Corrected} | {i.Open} |"); + } + + text.AppendLine(); + text.AppendLine("## Problemi aperti"); + text.AppendLine(); + if (OpenIssues.Count == 0) + { + text.AppendLine("Nessuno."); + } + + foreach (var issue in OpenIssues.Take(50)) + { + text.AppendLine(it, $"- {issue.StartsAt:dd/MM/yyyy HH:mm} {issue.Timeframe} {issue.Kind}: {issue.Detail}"); + } + + text.AppendLine(); + text.AppendLine("## Fonti"); + text.AppendLine(); + text.AppendLine("| Fonte | Attiva | Ultima risposta | Ultimo errore | Nota |"); + text.AppendLine("|---|---|---|---|---|"); + foreach (var s in Sources) + { + text.AppendLine(it, $"| {s.Source} | {(s.Enabled ? "sì" : "no")} | {s.LastSuccessAt:dd/MM/yyyy HH:mm} | {s.LastError} | {s.Note} |"); + } + + return text.ToString(); + } +} diff --git a/src/Anubis/Data/ReferenceData.cs b/src/Anubis/Data/ReferenceData.cs new file mode 100644 index 0000000..477176d --- /dev/null +++ b/src/Anubis/Data/ReferenceData.cs @@ -0,0 +1,280 @@ +using System.Collections.Concurrent; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +///A reference exchange rate: +public sealed record FxRate(string Base, string Quote, DateOnly Date, decimal Rate, string Source); + +///units of for one , as published for . +/// Reference exchange rates (SPEC 6.8): one per day as the ECB publishes them. A day without a rate uses the last +/// one before it, as the tax export requires (SPEC 4.6). +/// +public sealed class FxStore(Database db, IClock clock) +{ + public async TaskUpsertAsync(IEnumerable rates, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(rates); + var list = rates.ToList(); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + foreach (var rate in list) + { + await s.ExecuteAsync( + "INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, @b, @q, @d, @r, @s, @now) " + + "ON CONFLICT (base, quote, rate_date) DO UPDATE SET rate = excluded.rate, source = excluded.source", + cancellationToken, ("id", Ids.NewId(clock)), ("b", rate.Base), ("q", rate.Quote), ("d", BarStore.DayText(rate.Date)), + ("r", rate.Rate), ("s", rate.Source), ("now", now)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return list.Count; + } + + /// The rate published for + public Task, or the last one before it; null if none is known. RateOnAsync(string baseCurrency, string quote, DateOnly day, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT base, quote, rate_date, rate, source FROM fx_rates WHERE base = @b AND quote = @q AND rate_date <= @d ORDER BY rate_date DESC", + Read, ("b", baseCurrency), ("q", quote), ("d", BarStore.DayText(day))), cancellationToken); + + public Task LatestAsync(string baseCurrency, string quote, CancellationToken cancellationToken) => + RateOnAsync(baseCurrency, quote, DateOnly.MaxValue, cancellationToken); + + private static FxRate Read(DbRow r) => + new(r.Text("base"), r.Text("quote"), BarStore.ParseDay(r.Text("rate_date")), r.Money("rate"), r.Text("source")); +} + +public static class CalendarEventKinds +{ + public const string Economic = "economic"; + public const string CentralBank = "central_bank"; + public const string Earnings = "earnings"; + public const string Holiday = "holiday"; +} + +/// +/// An event of the calendar (SPEC 10.4). +public sealed record CalendarEvent(string Kind, string Title, DateTimeOffset OccursAt, bool TimeKnown, string Source, string SourceKey) +{ + public string? Currency { get; init; } + + public string? Symbol { get; init; } + + ///is false when the source gives only the day +/// (earnings without an hour, holidays): is then midnight of that day in the exchange's zone. +/// For earnings: + public string? TimeHint { get; init; } + + ///bmo before the open,amc after the close,dmh during market hours.Low, Medium or High. + public string? Impact { get; init; } + + public string? Forecast { get; init; } + + public string? Previous { get; init; } +} + +public sealed class CalendarEventStore(Database db, IClock clock) +{ + private const string Columns = "kind, title, currency, symbol, occurs_at, time_known, time_hint, impact, forecast, previous, source, source_key"; + + ///Adds new events and updates known ones (a moved date, a new forecast). Returns how many arrived. + public async TaskUpsertAsync(IEnumerable events, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(events); + var list = events.DistinctBy(e => e.SourceKey).ToList(); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + foreach (var e in list) + { + await s.ExecuteAsync( + $"INSERT INTO calendar_events (id, {Columns}, created_at, updated_at) VALUES (@id, @kind, @title, @ccy, @sym, @at, @known, @hint, @impact, " + + "@forecast, @previous, @source, @key, @now, @now) ON CONFLICT (source_key) DO UPDATE SET kind = excluded.kind, title = excluded.title, " + + "currency = excluded.currency, symbol = excluded.symbol, occurs_at = excluded.occurs_at, time_known = excluded.time_known, " + + "time_hint = excluded.time_hint, impact = excluded.impact, forecast = excluded.forecast, previous = excluded.previous, updated_at = excluded.updated_at", + cancellationToken, ("id", Ids.NewId(clock)), ("kind", e.Kind), ("title", e.Title), ("ccy", e.Currency), ("sym", e.Symbol), ("at", e.OccursAt), + ("known", e.TimeKnown), ("hint", e.TimeHint), ("impact", e.Impact), ("forecast", e.Forecast), ("previous", e.Previous), ("source", e.Source), + ("key", e.SourceKey), ("now", now)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return list.Count; + } + + public async Task > BetweenAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM calendar_events WHERE occurs_at >= @f AND occurs_at < @t ORDER BY occurs_at, title", + r => new CalendarEvent(r.Text("kind"), r.Text("title"), r.Moment("occurs_at"), r.Bool("time_known"), r.Text("source"), r.Text("source_key")) + { + Currency = r.TextOrNull("currency"), + Symbol = r.TextOrNull("symbol"), + TimeHint = r.TextOrNull("time_hint"), + Impact = r.TextOrNull("impact"), + Forecast = r.TextOrNull("forecast"), + Previous = r.TextOrNull("previous"), + }, ("f", from), ("t", to)), cancellationToken).ConfigureAwait(false); +} + +public static class MoodIndicators +{ + public const string FearGreed = "fear_greed"; + public const string Vix = "vix"; + public const string BtcFunding = "btc_funding"; + public const string BtcOpenInterest = "btc_open_interest"; +} + +public sealed record MoodReading(string Indicator, DateTimeOffset AsOf, double Value, string? Label, string Source); + +/// The labels of SPEC 10.4, in the words the interface shows. +public static class MoodLabels +{ + public static string FearGreed(double value) => value switch + { + <= 24 => "paura estrema", + <= 44 => "paura", + <= 55 => "neutro", + <= 75 => "avidità", + _ => "avidità estrema", + }; + + public static string Vix(double value) => value switch + { + < 20 => "calmo", + <= 30 => "nervoso", + _ => "panico", + }; + + ///+ public static string Funding(double rate, TimeSpan interval) + { + var perEightHours = interval > TimeSpan.Zero ? rate * (TimeSpan.FromHours(8) / interval) : rate; + return perEightHours switch + { + > 0.0002 => "troppi al rialzo", + < -0.0002 => "troppi al ribasso", + _ => "nella norma", + }; + } +} + +public sealed class MoodStore(Database db, IClock clock) +{ + public async Task is the funding of one period; its length (usually 8 hours). UpsertAsync(IEnumerable readings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(readings); + // An empty field from the source reads as NaN: SQLite would store it as NULL and PostgreSQL as NaN, so it is + // left out on both engines. + var list = readings.Where(r => double.IsFinite(r.Value)).ToList(); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + foreach (var m in list) + { + await s.ExecuteAsync( + "INSERT INTO market_mood (id, indicator, as_of, value, label, source, created_at) VALUES (@id, @i, @a, @v, @l, @s, @now) " + + "ON CONFLICT (indicator, as_of) DO UPDATE SET value = excluded.value, label = excluded.label, source = excluded.source", + cancellationToken, ("id", Ids.NewId(clock)), ("i", m.Indicator), ("a", m.AsOf), ("v", m.Value), ("l", m.Label), ("s", m.Source), ("now", now)) + .ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return list.Count; + } + + public Task LatestAsync(string indicator, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT indicator, as_of, value, label, source FROM market_mood WHERE indicator = @i ORDER BY as_of DESC", + r => new MoodReading(r.Text("indicator"), r.Moment("as_of"), r.Measure("value"), r.TextOrNull("label"), r.Text("source")), ("i", indicator)), + cancellationToken); +} + +/// +/// The exchange calendar as the broker gives it, saved day by day so the scheduler can read it without network +/// (SPEC 5.5: market times come from the broker's calendar, never from Italian time). +/// +public sealed class StoredMarketCalendar(Database db, IClock clock, string market) : IMarketCalendar +{ + private readonly ConcurrentDictionary_days = new(); + + public string Market { get; } = market; + + /// First and last day the stored calendar covers; null when it is empty. + public (DateOnly First, DateOnly Last)? Coverage => _days.IsEmpty ? null : (_days.Keys.Min(), _days.Keys.Max()); + + ///The session of + public MarketSession? SessionOn(DateOnly day) => _days.TryGetValue(day, out var session) ? session : null; + + public bool Covers(DateOnly day) => _days.ContainsKey(day); + + ///; null when the market is closed or the day is not covered yet. Saves the sessions of [first, last]; days without a session are saved as closed. + public async Task SaveAsync(IReadOnlyCollectionsessions, DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(sessions); + var byDay = sessions.Where(x => x.Date >= first && x.Date <= last).ToDictionary(x => x.Date); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + for (var day = first; day <= last; day = day.AddDays(1)) + { + var session = byDay.GetValueOrDefault(day); + await s.ExecuteAsync( + "INSERT INTO market_calendar (id, market, session_date, is_open, open_at, close_at, created_at) VALUES (@id, @m, @d, @o, @oa, @ca, @now) " + + "ON CONFLICT (market, session_date) DO UPDATE SET is_open = excluded.is_open, open_at = excluded.open_at, close_at = excluded.close_at", + cancellationToken, ("id", Ids.NewId(clock)), ("m", Market), ("d", BarStore.DayText(day)), ("o", session is not null), + ("oa", session?.OpenUtc), ("ca", session?.CloseUtc), ("now", now)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + + for (var day = first; day <= last; day = day.AddDays(1)) + { + _days[day] = byDay.GetValueOrDefault(day); + } + } + + public async Task LoadAsync(CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync("SELECT session_date, is_open, open_at, close_at FROM market_calendar WHERE market = @m", + r => + { + var day = BarStore.ParseDay(r.Text("session_date")); + return (Day: day, Session: r.Bool("is_open") ? new MarketSession(day, r.Moment("open_at"), r.Moment("close_at")) : null); + }, ("m", Market)), cancellationToken).ConfigureAwait(false); + foreach (var (day, session) in rows) + { + _days[day] = session; + } + } + + /// Sessions in [first, last], oldest first. + public IReadOnlyListSessions(DateOnly first, DateOnly last) => + _days.Where(d => d.Key >= first && d.Key <= last && d.Value is not null).Select(d => d.Value!).OrderBy(x => x.Date).ToList(); +} + +/// State of an external source: when it was last asked, last answered, and why it is off (SPEC 4.4). +public sealed record SourceState(string Source, bool Enabled, DateTimeOffset? LastRequestAt, DateTimeOffset? LastSuccessAt, string? LastError, string? Note); + +public sealed class SourceStateStore(Database db, IClock clock) +{ + public Task RecordAsync(string source, bool enabled, bool success, string? error, string? note, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + return db.WriteAsync(async s => + { + var exists = await s.CountAsync("SELECT COUNT(*) FROM source_state WHERE source = @s", ("s", source)).ConfigureAwait(false) > 0; + if (!exists) + { + await s.ExecuteAsync("INSERT INTO source_state (id, source, enabled, created_at, updated_at) VALUES (@id, @s, @e, @now, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("s", source), ("e", enabled), ("now", now)).ConfigureAwait(false); + } + + await s.ExecuteAsync(success + ? "UPDATE source_state SET enabled = @e, last_request_at = @now, last_success_at = @now, last_error = NULL, note = @n, updated_at = @now WHERE source = @s" + : "UPDATE source_state SET enabled = @e, last_request_at = @now, last_error = @err, note = @n, updated_at = @now WHERE source = @s", + cancellationToken, success + ? [("e", enabled), ("now", now), ("n", note), ("s", source)] + : [("e", enabled), ("now", now), ("err", error), ("n", note), ("s", source)]).ConfigureAwait(false); + }, cancellationToken); + } + + public async Task> ListAsync(CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync("SELECT source, enabled, last_request_at, last_success_at, last_error, note FROM source_state ORDER BY source", + r => new SourceState(r.Text("source"), r.Bool("enabled"), r.MomentOrNull("last_request_at"), r.MomentOrNull("last_success_at"), + r.TextOrNull("last_error"), r.TextOrNull("note"))), cancellationToken).ConfigureAwait(false); +} diff --git a/src/Anubis/Data/ReferenceSources.cs b/src/Anubis/Data/ReferenceSources.cs new file mode 100644 index 0000000..3f8c60d --- /dev/null +++ b/src/Anubis/Data/ReferenceSources.cs @@ -0,0 +1,221 @@ +using System.Globalization; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +/// +/// Downloads the free sources of SPEC 4.4 within their limits and records each attempt in +public sealed class ReferenceSources( + ApiHttp http, + Database db, + IClock clock, + SettingsStore settings, + Funcsource_state , so +/// limits hold across restarts and the interface can say what is off and why. A source that fails is retried at +/// its next turn; it never stops the others. +///> secret, + OkxClient? okx = null) +{ + /// Currencies kept from the ECB: the dollar for display and the tax export (SPEC 6.8). + public static readonly IReadOnlyListCurrencies = ["USD"]; + + public const string OkxDerivatives = "okx_derivatives"; + + /// + /// Shortest time between two requests to the same source. Forex Factory asks for no more than two requests every + /// five minutes; the others publish once a day or less. + /// + public static readonly IReadOnlyDictionaryMinInterval = new Dictionary + { + [Ecb.Source] = TimeSpan.FromMinutes(30), + [ForexFactory.Source] = TimeSpan.FromMinutes(55), + [Fred.Source] = TimeSpan.FromHours(12), + [Finnhub.Source] = TimeSpan.FromHours(12), + [FearGreed.Source] = TimeSpan.FromMinutes(55), + [VixHistory.Source] = TimeSpan.FromHours(6), + [OkxDerivatives] = TimeSpan.FromMinutes(55), + [CentralBanks.Source] = TimeSpan.Zero, + }; + + private readonly SourceStateStore _states = new(db, clock); + + private readonly FxStore _fx = new(db, clock); + + private readonly CalendarEventStore _calendar = new(db, clock); + + private readonly MoodStore _mood = new(db, clock); + + /// Reference rates: the whole history the first time, the last 90 days after a pause, otherwise the day's file. + public TaskRefreshFxAsync(CancellationToken cancellationToken) => RunAsync(Ecb.Source, async () => + { + var latest = await _fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + IReadOnlyList rates; + if (latest is null) + { + var zip = await http.GetBytesAsync(Ecb.History, null, null, cancellationToken).ConfigureAwait(false) + ?? throw new MarketDataException("BCE: archivio storico dei cambi non trovato.", retryable: true); + rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(zip), Currencies); + } + else + { + var url = latest.Date < today.AddDays(-4) ? Ecb.Last90Days : Ecb.Daily; + rates = Ecb.ParseXml(await http.GetStringAsync(url, null, null, cancellationToken).ConfigureAwait(false), Currencies); + } + + await _fx.UpsertAsync(rates, cancellationToken).ConfigureAwait(false); + return $"{rates.Count} cambi"; + }, cancellationToken); + + /// The economic calendar of this week (Forex Factory), plus the central bank list of the settings. + public async TaskRefreshCalendarAsync(CancellationToken cancellationToken) + { + var banks = await RunAsync(CentralBanks.Source, async () => + { + var list = await settings.GetAsync(SettingsStore.CentralBankMeetings.Key, cancellationToken).ConfigureAwait(false); + var events = CentralBanks.Parse(list.Value); + await _calendar.UpsertAsync(events, cancellationToken).ConfigureAwait(false); + var last = events.Count == 0 ? (DateTimeOffset?)null : events.Max(e => e.OccursAt); + return last is { } l && l < clock.UtcNow.AddDays(60) + ? $"L'elenco delle riunioni finisce il {l:dd/MM/yyyy}: aggiungi le date del nuovo anno nelle impostazioni." + : $"{events.Count} riunioni"; + }, cancellationToken).ConfigureAwait(false); + + var week = await RunAsync(ForexFactory.Source, async () => + { + var events = ForexFactory.Parse(await http.GetStringAsync(ForexFactory.ThisWeek, null, null, cancellationToken).ConfigureAwait(false)); + await _calendar.UpsertAsync(events, cancellationToken).ConfigureAwait(false); + return $"{events.Count} eventi"; + }, cancellationToken).ConfigureAwait(false); + return banks && week; + } + + /// Release dates of the main US data from FRED; off without a key, and the interface says so. + public async TaskRefreshFredAsync(CancellationToken cancellationToken) + { + var key = await secret("FRED_API_KEY", cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(key)) + { + await _states.RecordAsync(Fred.Source, enabled: false, success: false, null, + "Spento: manca la chiave FRED_API_KEY. Il calendario usa solo Forex Factory.", cancellationToken).ConfigureAwait(false); + return false; + } + + return await RunAsync(Fred.Source, async () => + { + var from = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + var count = 0; + foreach (var (id, title) in Fred.Releases) + { + var events = Fred.Parse(await http.GetStringAsync(Fred.ReleaseDates(id, key, from), null, null, cancellationToken).ConfigureAwait(false), title, from); + count += await _calendar.UpsertAsync(events.Where(e => e.OccursAt < clock.UtcNow.AddDays(120)), cancellationToken).ConfigureAwait(false); + } + + return $"{count} date"; + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// Earnings dates for the next two weeks. Without a key the earnings filter is off (SPEC 4.4): the state says so + /// and the strategies read + public async Task. + /// RefreshEarningsAsync(IReadOnlySet ? symbols, CancellationToken cancellationToken) + { + var key = await secret("FINNHUB_API_KEY", cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(key)) + { + await _states.RecordAsync(Finnhub.Source, enabled: false, success: false, null, + "Spento: manca la chiave FINNHUB_API_KEY. Il filtro sulle trimestrali è disattivato.", cancellationToken).ConfigureAwait(false); + return false; + } + + return await RunAsync(Finnhub.Source, async () => + { + var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + var events = Finnhub.Parse(await http.GetStringAsync(Finnhub.Earnings(today, today.AddDays(14), key), null, null, cancellationToken).ConfigureAwait(false), + symbols); + await _calendar.UpsertAsync(events, cancellationToken).ConfigureAwait(false); + return $"{events.Count} trimestrali"; + }, cancellationToken).ConfigureAwait(false); + } + + /// True when earnings dates are known: the source is on and answered in the last two days. + public async TaskEarningsFilterActiveAsync(CancellationToken cancellationToken) + { + var state = (await _states.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(s => s.Source == Finnhub.Source); + return state is { Enabled: true, LastSuccessAt: { } at } && clock.UtcNow - at < TimeSpan.FromDays(2); + } + + /// Mood indicators: fear and greed, VIX, and Bitcoin funding and open interest from OKX public data. + public async TaskRefreshMoodAsync(CancellationToken cancellationToken) + { + var fng = await RunAsync(FearGreed.Source, async () => + { + var first = await _mood.LatestAsync(MoodIndicators.FearGreed, cancellationToken).ConfigureAwait(false) is null; + var readings = FearGreed.Parse(await http.GetStringAsync(FearGreed.Latest(first ? 400 : 2), null, null, cancellationToken).ConfigureAwait(false)); + await _mood.UpsertAsync(readings, cancellationToken).ConfigureAwait(false); + return FearGreed.Attribution; + }, cancellationToken).ConfigureAwait(false); + + var vix = await RunAsync(VixHistory.Source, async () => + { + var from = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime).AddDays(-400); + var readings = VixHistory.Parse(await http.GetStringAsync(VixHistory.Csv, null, null, cancellationToken).ConfigureAwait(false), from); + await _mood.UpsertAsync(readings, cancellationToken).ConfigureAwait(false); + return $"{readings.Count} chiusure"; + }, cancellationToken).ConfigureAwait(false); + + if (okx is null) + { + return fng && vix; + } + + var derivatives = await RunAsync(OkxDerivatives, async () => + { + var funding = await okx.FetchFundingRateAsync("BTC-USDT-SWAP", cancellationToken).ConfigureAwait(false); + var interest = await okx.FetchOpenInterestAsync("BTC-USDT-SWAP", cancellationToken).ConfigureAwait(false); + await _mood.UpsertAsync( + [ + new MoodReading(MoodIndicators.BtcFunding, funding.At, funding.Rate, MoodLabels.Funding(funding.Rate, funding.Interval), Venues.Okx), + new MoodReading(MoodIndicators.BtcOpenInterest, interest.At, interest.Usd, null, Venues.Okx), + ], cancellationToken).ConfigureAwait(false); + return "funding " + funding.Rate.ToString("P4", CultureInfo.InvariantCulture); + }, cancellationToken).ConfigureAwait(false); + return fng && vix && derivatives; + } + + public Task > StatesAsync(CancellationToken cancellationToken) => _states.ListAsync(cancellationToken); + + /// + /// Runs one source if its minimum interval has passed and records the outcome. Returns true when it succeeded or + /// was not due yet; false when it failed. + /// + private async TaskRunAsync(string source, Func > work, CancellationToken cancellationToken) + { + var state = (await _states.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(s => s.Source == source); + if (state?.LastRequestAt is { } last && clock.UtcNow - last < MinInterval.GetValueOrDefault(source, TimeSpan.FromMinutes(5))) + { + return true; + } + + try + { + var note = await work().ConfigureAwait(false); + await _states.RecordAsync(source, enabled: true, success: true, null, note, cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is MarketDataException or HttpRequestException or FormatException or System.Text.Json.JsonException + or System.Xml.XmlException or TaskCanceledException or InvalidDataException or KeyNotFoundException or InvalidOperationException or IndexOutOfRangeException) + { + if (cancellationToken.IsCancellationRequested) + { + throw; + } + + await _states.RecordAsync(source, enabled: true, success: false, Redactor.Redact(ex.Message), state?.Note, cancellationToken).ConfigureAwait(false); + return false; + } + } +} diff --git a/src/Anubis/Data/ResearchStore.cs b/src/Anubis/Data/ResearchStore.cs new file mode 100644 index 0000000..55aa43b --- /dev/null +++ b/src/Anubis/Data/ResearchStore.cs @@ -0,0 +1,189 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; + +namespace Anubis.Data; + +/// +/// A bar of the research history. Values keep the decimal text the source wrote, so a round trip through the file +/// loses no digit (issue #21); backtests convert to +public sealed record ResearchBar(DateTimeOffset OpensAt, decimal Open, decimal High, decimal Low, decimal Close, decimal Volume) +{ + public decimal? QuoteVolume { get; init; } + + public long? Trades { get; init; } + + public Bar ToBar() => new(OpensAt, (double)Open, (double)High, (double)Low, (double)Close, (double)Volume) + { + QuoteVolume = QuoteVolume is { } q ? (double)q : null, + }; +} + +///when they read. +/// +/// The research history (SPEC 6.6, ADR 0003): one gzip-compressed CSV per instrument, timeframe and year under +/// +public sealed class ResearchStore(string root) +{ + public const string Header = "opens_at,open,high,low,close,volume,quote_volume,trades"; + + private const string MomentFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + + public string Root { get; } = root; + + public string PathFor(string venue, string symbol, string timeframe, int year) => + Path.Combine(Root, Safe(venue), Safe(symbol), Safe(timeframe), year.ToString(CultureInfo.InvariantCulture) + ".csv.gz"); + + ///research/{venue}/{symbol}/{timeframe}/{year}.csv.gz . Backtests read it from here, never from the database. +/// Writing a year merges with what is there: a bar with the same opening time is replaced. Files are written to a +/// temporary name and moved into place, so a crash never leaves half a file. +///Writes bars, merging each year with its existing file. Returns the number of bars now in the touched files. + public async TaskWriteAsync(string venue, string symbol, string timeframe, IEnumerable bars, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bars); + var total = 0; + foreach (var year in bars.GroupBy(b => b.OpensAt.UtcDateTime.Year)) + { + var path = PathFor(venue, symbol, timeframe, year.Key); + var merged = new SortedDictionary (); + if (File.Exists(path)) + { + await foreach (var bar in ReadFileAsync(path, cancellationToken).ConfigureAwait(false)) + { + merged[bar.OpensAt] = bar; + } + } + + foreach (var bar in year) + { + merged[bar.OpensAt.ToUniversalTime()] = bar with { OpensAt = bar.OpensAt.ToUniversalTime() }; + } + + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var temp = path + ".tmp"; + await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true)) + await using (var gzip = new GZipStream(file, CompressionLevel.Optimal)) + await using (var writer = new StreamWriter(gzip, new UTF8Encoding(false)) { NewLine = "\n" }) + { + await writer.WriteLineAsync(Header).ConfigureAwait(false); + foreach (var bar in merged.Values) + { + cancellationToken.ThrowIfCancellationRequested(); + await writer.WriteLineAsync(Format(bar)).ConfigureAwait(false); + } + } + + File.Move(temp, path, overwrite: true); + total += merged.Count; + } + + return total; + } + + /// Bars opening from + public async IAsyncEnumerable(included) to (excluded), oldest first. ReadAsync(string venue, string symbol, string timeframe, DateTimeOffset from, DateTimeOffset to, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) + { + foreach (var year in Years(venue, symbol, timeframe).Where(y => y >= from.UtcDateTime.Year && y <= to.UtcDateTime.Year)) + { + await foreach (var bar in ReadFileAsync(PathFor(venue, symbol, timeframe, year), cancellationToken).ConfigureAwait(false)) + { + if (bar.OpensAt >= from && bar.OpensAt < to) + { + yield return bar; + } + } + } + } + + public IReadOnlyList Years(string venue, string symbol, string timeframe) + { + var folder = Path.Combine(Root, Safe(venue), Safe(symbol), Safe(timeframe)); + if (!Directory.Exists(folder)) + { + return []; + } + + return Directory.EnumerateFiles(folder, "*.csv.gz") + .Select(f => Path.GetFileName(f)[..^".csv.gz".Length]) + .Select(n => int.TryParse(n, NumberStyles.None, CultureInfo.InvariantCulture, out var y) ? y : 0) + .Where(y => y > 0) + .Order() + .ToList(); + } + + /// Every (venue, symbol, timeframe) with at least one file. + public IReadOnlyList<(string Venue, string Symbol, string Timeframe)> Series() + { + if (!Directory.Exists(Root)) + { + return []; + } + + return Directory.EnumerateFiles(Root, "*.csv.gz", SearchOption.AllDirectories) + .Select(f => Path.GetRelativePath(Root, f).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) + .Where(p => p.Length == 4) + .Select(p => (p[0], p[1], p[2])) + .Distinct() + .Order() + .ToList(); + } + + private static async IAsyncEnumerableReadFileAsync(string path, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, useAsync: true); + await using var gzip = new GZipStream(file, CompressionMode.Decompress); + using var reader = new StreamReader(gzip, Encoding.UTF8); + var header = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); + if (header != Header) + { + throw new InvalidDataException($"Unexpected header in {path}: {header}"); + } + + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (line.Length > 0) + { + yield return Parse(line, path); + } + } + } + + private static string Format(ResearchBar bar) => string.Join(',', + bar.OpensAt.UtcDateTime.ToString(MomentFormat, CultureInfo.InvariantCulture), + Text(bar.Open), Text(bar.High), Text(bar.Low), Text(bar.Close), Text(bar.Volume), + bar.QuoteVolume is { } q ? Text(q) : "", + bar.Trades?.ToString(CultureInfo.InvariantCulture) ?? ""); + + private static ResearchBar Parse(string line, string path) + { + var f = line.Split(','); + if (f.Length != 8) + { + throw new InvalidDataException($"Bad line in {path}: {line}"); + } + + return new ResearchBar( + DateTimeOffset.ParseExact(f[0], MomentFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), + Number(f[1]), Number(f[2]), Number(f[3]), Number(f[4]), Number(f[5])) + { + QuoteVolume = f[6].Length == 0 ? null : Number(f[6]), + Trades = f[7].Length == 0 ? null : long.Parse(f[7], NumberStyles.None, CultureInfo.InvariantCulture), + }; + } + + ///