diff --git a/.gitattributes b/.gitattributes index f2da781..950a3c0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,3 +6,5 @@ Dockerfile text eol=lf *.png binary *.ico binary *.ttf binary +# Recorded API responses stay byte for byte as the source sent them (CRLF in nasdaqtraded.txt included). +tests/Anubis.Tests/Fixtures/** -text diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index a7ebd94..34f3b34 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -157,6 +157,36 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio | M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 | | V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 | | V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 | +| Storia dei flag ETF e frazionabile | Gli universi passati usano i flag di oggi; il limite è scritto nel rapporto della prova storica. | 4 | +| Barre dei titoli tolti dalla borsa su Alpaca | Da controllare con le chiavi del conto di prova; fino ad allora gli universi passati vanno letti come ottimisti. | 2, 4 | +| Minuti senza scambi su OKX | Il buco si riscarica una volta, poi resta segnato come non recuperabile e non blocca nulla. | 2 | + +## Verifiche della Fase 2 (dati di mercato) + +Fatti controllati scrivendo gli adapter dei dati, il 10/11/2026. Le risposte registrate stanno in `tests/Anubis.Tests/Fixtures` e i test le leggono senza rete. + +| Fonte | Fatto | Come è stato verificato | +|---|---|---| +| OKX | `history-candles` con `1Dutc` dà lo storico giornaliero intero di BTC-EUR, ETH-EUR e SOL-EUR dal 21/11/2023: 1.085 giorni ciascuna, senza buchi né anomalie. | Prova reale `RealHistoryProof` (categoria LiveDemo) | +| OKX | Una candela con `confirm` = 0 è ancora aperta: lo storico la scarta e il flusso dal vivo la salva solo quando si chiude. | Risposte registrate di `candles` e del WebSocket | +| OKX | Finanziamento e open interest di BTC-USDT-SWAP rispondono senza chiave su eea.okx.com. | Risposte registrate | +| Alpaca | Con il piano gratuito una richiesta `feed=sip` che arriva a meno di 15 minuti fa risponde `{"code":42210000,"message":"subscription does not permit querying recent SIP data"}`. | Esempio della FAQ di Alpaca (`errors.md` nei fixture) | +| Alpaca | Le barre giornaliere hanno l'orario della mezzanotte di New York: il giorno della barra è la data di New York. `adjustment=raw` e `adjustment=all` si chiedono separatamente. | Esempi della documentazione | +| Alpaca | Le chiavi si leggono solo da `ALPACA_API_KEY_DEMO` e `ALPACA_API_SECRET_DEMO`, quelle del conto di prova. Senza chiavi nessuna chiamata parte verso Alpaca. | Test `ServerCollectsWithoutAlpacaKeysAndSaysWhatIsOff` | +| BCE | Lo storico completo è nello zip `eurofxref-hist.zip` (CSV dal più recente, virgola finale su ogni riga, `N/A` dove manca); poi basta il file a 90 giorni o quello giornaliero. | Risposte registrate | +| Forex Factory | Se al posto del JSON arriva una pagina di blocco, la lettura fallisce e conta come errore della fonte; il calendario già salvato resta. | Test | +| Fed e BCE | Calendari 2026–2027 letti dalle pagine ufficiali; la Fed avverte che ogni data è provvisoria fino alla riunione precedente. Per questo l'elenco è un'impostazione modificabile in Impostazioni → Dati. | `central-banks.md` nei fixture | +| alternative.me | Valori giornalieri con timestamp Unix in secondi. Anubis chiede 400 giorni la prima volta e poi solo gli ultimi 2. | Risposte registrate | +| nasdaqtraded.txt | La colonna ETF non segna molti ETN e nessun fondo chiuso: Anubis legge anche il nome del titolo. I codici delle borse comprendono ora anche `F` (Texas Stock Exchange) e `M` (NYSE Texas). | File del 10/11/2026 | +| Binance | Ogni zip mensile ha accanto un file `.CHECKSUM` con lo SHA-256; i timestamp passano dai millisecondi ai microsecondi da gennaio 2025. Il primo giorno di BTCUSDT è il 17/08/2017; il mese in corso non è ancora pubblicato. | Prova reale: 3.363 giorni dal 17/08/2017 al 31/10/2026 | + +**Distorsioni che restano negli universi a una data passata** +- I flag di oggi (frazionabile su Alpaca, ETF in `nasdaqtraded.txt`) valgono anche per le date passate: le fonti gratuite non hanno la storia di questi flag. +- Un titolo che ha cambiato simbolo è riconosciuto come fondo solo se il nome lo dice. +- Non è verificato che Alpaca dia le barre dei titoli tolti dalla borsa: se mancano, gli universi passati sono un po' troppo ottimisti (distorsione dei sopravvissuti). Si controlla con le chiavi del conto di prova. + +**Non verificabile senza scambi reali** +- Se OKX ometta i minuti senza scambi o li dia a volume zero. Il collector tratta un minuto mancante come buco, lo riscarica una volta e poi lo segna "non recuperabile, forse minuti senza scambi". ## Versioni di .NET e dei pacchetti ammessi diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e5eb4d8..e5a9be6 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -86,22 +86,22 @@ Storico e dati dal vivo affidabili, controllati e senza sguardi in avanti. **Lavori** -- [ ] [#18](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/18) Catalogo degli strumenti e parte dati dell'adapter OKX Europe -- [ ] [#19](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/19) Parte dati dell'adapter Alpaca (piano gratuito) -- [ ] [#20](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/20) Collector storico e dal vivo, recupero dei buchi, controlli di qualità, freschezza -- [ ] [#21](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/21) Importatori: archivi Binance e CSV dell'utente verso lo storico di ricerca -- [ ] [#22](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/22) Calendari e cambi: calendario di borsa, EUR/USD BCE, calendario economico, trimestrali, umore -- [ ] [#23](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/23) Azioni societarie e serie rettificate ancorate al giorno della decisione -- [ ] [#24](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/24) Universi "a una certa data" con esclusione degli ETF -- [ ] [#25](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/25) Chiusura della fase, revisione indipendente e tag `fase-2` +- [x] [#18](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/18) Catalogo degli strumenti e parte dati dell'adapter OKX Europe +- [x] [#19](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/19) Parte dati dell'adapter Alpaca (piano gratuito) +- [x] [#20](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/20) Collector storico e dal vivo, recupero dei buchi, controlli di qualità, freschezza +- [x] [#21](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/21) Importatori: archivi Binance e CSV dell'utente verso lo storico di ricerca +- [x] [#22](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/22) Calendari e cambi: calendario di borsa, EUR/USD BCE, calendario economico, trimestrali, umore +- [x] [#23](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/23) Azioni societarie e serie rettificate ancorate al giorno della decisione +- [x] [#24](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/24) Universi "a una certa data" con esclusione degli ETF +- [x] [#25](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/25) Chiusura della fase, revisione indipendente e tag `fase-2` **Criteri di accettazione** -- [ ] Storico giornaliero delle crypto dall'inizio disponibile (coppie in EUR di OKX, più gli archivi Binance dal 2017) e delle azioni dal 2016 -- [ ] Senza chiavi Alpaca la parte azionaria si prova su dati sintetici e risposte d'esempio, e il criterio resta in attesa dell'utente -- [ ] Un test stacca il flusso per 10 minuti e verifica che il buco venga recuperato -- [ ] Rapporto di qualità dei dati -- [ ] L'elenco dell'universo azionario a tre date passate non contiene ETF +- [ ] Storico giornaliero delle crypto dall'inizio disponibile (coppie in EUR di OKX, più gli archivi Binance dal 2017) e delle azioni dal 2016 — **crypto fatto** (BTC, ETH e SOL in EUR dal 21/11/2023, BTCUSDT dal 17/08/2017); **azioni in attesa dell'utente** (chiavi del conto di prova Alpaca) +- [x] Senza chiavi Alpaca la parte azionaria si prova su dati sintetici e risposte d'esempio, e il criterio resta in attesa dell'utente +- [x] Un test stacca il flusso per 10 minuti e verifica che il buco venga recuperato +- [x] Rapporto di qualità dei dati +- [x] L'elenco dell'universo azionario a tre date passate non contiene ETF ## Fase 3 — Conti, ordini, contabilità diff --git a/docs/STATE.md b/docs/STATE.md index c8aeed4..77fe03e 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-10 ## Fase corrente -**Fase 1 — Fondamenta: completata.** La prossima è la Fase 2 (Dati di mercato), da iniziare con il via dell'utente. +**Fase 2 — Dati di mercato: completata**, con la parte azionaria in attesa delle chiavi del conto di prova Alpaca. La prossima è la Fase 3 (Conti, ordini, contabilità), da iniziare con il via dell'utente. ## Fatto @@ -45,6 +45,15 @@ Aggiornato: 2026-11-10 - Immagine Docker definitiva: `PUID`/`PGID`, controllo di salute, l'applicazione non gira come root. Provata con SQLite, PostgreSQL, configurazione sbagliata e database staccato. - `tasks screenshots` per confrontare le schermate con i mockup. - Dopo la chiusura, con il permesso dell'utente: carattere Instrument Sans incluso nell'applicazione (ADR 0007, punto 5). +- **Fase 2** (scelte nell'ADR 0008, fatti verificati in `docs/API-NOTES.md`): + - Catalogo degli strumenti e parte dati degli adapter OKX Europe (coppie in EUR, candele, prezzi, libro, WebSocket) e Alpaca (barre consolidate reali e rettificate, minuti, calendario, orologio, azioni societarie, flusso IEX). + - Collector storico e dal vivo dentro il server: recupero dei buchi, controlli di qualità con seconda lettura immediata, freschezza dei dati, ripresa con attese crescenti. + - Storico di ricerca in file `csv.gz` per anno; importatori degli archivi Binance (con controllo SHA-256) e dei CSV dell'utente (`anubis data binance`, `anubis data csv`). + - Fonti gratuite: cambi BCE, calendario economico, date FRED e trimestrali Finnhub (con chiave facoltativa), riunioni di Fed e BCE modificabili, umore (Fear & Greed, VIX, finanziamento e open interest di OKX). + - Azioni societarie e serie rettificate ancorate al giorno della decisione. + - Universi azionario e crypto "a una certa data", senza ETF né fondi. + - Rapporto di qualità dei dati (`anubis data report`, `/api/data/quality`) e sezione Dati in Impostazioni con lo stato di ogni fonte. + - Prova sui dati reali: BTC, ETH e SOL in EUR dal 21/11/2023 (1.085 giorni ciascuna, nessun buco) e BTCUSDT di Binance dal 17/08/2017 (3.363 giorni). ## In corso @@ -52,7 +61,7 @@ Nulla. ## Prossimo passo -Fase 2, dati di mercato: storico e dati dal vivo, controlli di qualità, cambi del giorno. Servono le chiavi del conto paper di Alpaca (vedi sotto); senza, la parte azionaria si prova su dati sintetici. +Fase 3, conti, ordini e contabilità: simulatore interno, gestione degli ordini, stop di protezione, contabilità, riconciliazione. Servono le chiavi demo di OKX Europe e quelle del conto di prova Alpaca (vedi sotto); senza, la batteria di conformità gira su risposte d'esempio. ## Da sapere @@ -61,6 +70,9 @@ Fase 2, dati di mercato: storico e dati dal vivo, controlli di qualità, cambi d - `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`. - Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14). - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). +- Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT, da convertire in euro nella Fase 4. +- I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti. +- Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2). - Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale. - Su questo PC Docker Desktop non partiva: erano rimasti due file di comunicazione di una sessione di ottobre, che Windows non riusciva a cancellare. Le cartelle che li contengono sono state rinominate, non cancellate: `%LOCALAPPDATA%\Docker\run.stale*` e `%LOCALAPPDATA%\docker-secrets-engine.stale*`. Si possono eliminare dopo un riavvio. @@ -68,12 +80,12 @@ Fase 2, dati di mercato: storico e dati dal vivo, controlli di qualità, cambi d | Cosa | Da quando serve | Senza | |---|---|---| -| Via libera per la Fase 2 | Subito | Non si parte | -| Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa | +| Via libera per la Fase 3 | Subito | Non si parte | +| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 in attesa | | Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | | Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server | -| Chiavi FRED e Finnhub (facoltative, gratuite) | Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | +| Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | | Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale | | Prova del template su Unraid | Fase 9 | Criterio in attesa | | Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa | diff --git a/docs/adr/0008-scelte-fase-2.md b/docs/adr/0008-scelte-fase-2.md new file mode 100644 index 0000000..09b1752 --- /dev/null +++ b/docs/adr/0008-scelte-fase-2.md @@ -0,0 +1,71 @@ +# 0008 — Scelte della Fase 2: dati di mercato + +Data: 2026-11-10 · Stato: accettata · Precisa la specifica (sezioni 4, 5.3, 6, 10.4) e gli ADR 0003 e 0007, senza aggiungere componenti esterni + +## Contesto + +La Fase 2 porta in Anubis i dati di mercato: catalogo degli strumenti, storico e flusso dal vivo, controlli di qualità, cambi, calendari, umore del mercato, azioni societarie e universi. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui. + +## Decisione + +**1. Storico di ricerca in CSV compresso, non Parquet.** +- La specifica (6.6) parla di file Parquet. Leggerli e scriverli richiede un pacchetto che l'ADR 0004 non elenca. +- Al suo posto: un file `csv.gz` per strumento, intervallo e anno, in `research/{mercato}/{simbolo}/{intervallo}/{anno}.csv.gz`. Usa solo `System.IO.Compression`, che fa parte di .NET. +- I prezzi restano nel testo decimale scritto dalla fonte: andata e ritorno dal file senza perdere cifre. Le prove storiche li convertono in `double` quando li leggono. +- Ogni file si scrive con un nome temporaneo e poi si sposta: un'interruzione non lascia mai mezzo file. +- Se un giorno servirà Parquet, si chiederà il pacchetto all'utente; il formato sta dietro `ResearchStore`. + +**2. Scritture idempotenti.** Barre, cambi, eventi e letture dell'umore si salvano con `INSERT … ON CONFLICT … DO UPDATE`, che entrambi i motori capiscono. Riscaricare lo stesso periodo non crea doppioni. + +**3. Dato anomalo: seconda lettura subito.** +- Un dato che non passa i controlli (prezzo zero o negativo, massimo sotto il minimo, salto improbabile) si salva come "sospetto" e si apre un problema. +- La fonte si interroga di nuovo subito per lo stesso periodo: + - stessi valori: il dato è **confermato**; + - valori diversi: i nuovi lo sostituiscono (**corretto**); + - nessun dato o ancora impossibile: il dato si scarta (**non recuperabile**). +- Un buco si riscarica una volta. Ciò che manca ancora resta segnato come non recuperabile ("forse minuti senza scambi") e non blocca nulla. +- Un buco tra l'ultimo dato salvato e il primo dato nuovo conta come gli altri: anche un minuto saltato dal flusso dal vivo si riscarica. +- I buchi al minuto si cercano solo per la crypto, che scambia sempre. Per le azioni il controllo dei minuti arriva con il flusso dal vivo (Fase 3); i giorni mancanti si cercano sulle sedute del calendario di borsa. + +**4. Solo le coppie in EUR di OKX Europe.** Il catalogo tiene le coppie spot quotate in EUR. Le coppie in USDC (più profonde per le monete minori, API-NOTES O18) restano fuori finché la Fase 3 non verifica con le chiavi demo quali si possono davvero negoziare. + +**5. Alpaca solo con le chiavi del conto di prova.** +- Le chiavi si leggono da `ALPACA_API_KEY_DEMO` e `ALPACA_API_SECRET_DEMO`, mai da altre variabili. +- Senza chiavi la parte azionaria è spenta: nessuna chiamata parte verso Alpaca, e Impostazioni → Dati dice cosa manca. +- I criteri azionari della fase restano "in attesa dell'utente" e si provano su risposte d'esempio e dati sintetici. + +**6. Azioni societarie gestite.** Frazionamenti (diretti e inversi), dividendi in contanti, dividendi in azioni e cambi di simbolo. Gli altri tipi di Alpaca (unità, scorpori, fusioni) non si scaricano: un titolo che li subisce compare come salto nelle serie e il controllo dei salti lo segnala. + +**6b. Prezzi rettificati sempre sulla stessa base.** +- Alpaca dà i prezzi rettificati sulla base del giorno in cui si scaricano. Ogni scaricamento riparte quindi dall'ultimo giorno già salvato, che fa da testimone. +- Se il rapporto tra prezzo rettificato e prezzo reale di quel giorno è cambiato, è arrivato un frazionamento o un dividendo: tutti i prezzi rettificati salvati si moltiplicano per lo stesso fattore prima dei controlli. +- Così un frazionamento non sembra un crollo, e la serie rettificata nel database resta continua. I prezzi reali non si toccano mai. + +**7. Fondi riconosciuti anche dal nome.** La colonna ETF di `nasdaqtraded.txt` non segna molti ETN e nessun fondo chiuso. Un titolo è escluso dall'universo azionario se il file lo segna come ETF, oppure se il nome contiene parole come "ETF", "ETN", "Fund", "Closed-End", "Beneficial Interest", "Index", "Leveraged", "Preferred", "Warrant", "Right", "Unit", "Notes" (l'elenco completo è in `NasdaqTraded`). Meglio escludere un'azione vera che comprare un fondo vietato (SPEC 4.6). + +**8. Universi a una data passata.** +- Azioni: NYSE e NASDAQ, frazionabili, non fondi, almeno 300 sedute di storia, ultima barra entro 7 giorni, chiusura reale sopra 10 $, le prime 150 per controvalore mediano su 60 sedute. +- Crypto: coppie in EUR quotate da almeno 400 giorni, controvalore mediano a 30 giorni sopra 250.000 €, spread mediano sotto 20 punti base (senza spread noto la coppia è esclusa), niente stablecoin, monete "wrapped" o token a leva; le prime 10. +- Si usano solo i dati fino alla data: un test lo verifica. +- Limite noto: i flag di oggi (frazionabile, ETF) valgono anche per il passato (API-NOTES, "Distorsioni che restano"). + +**9. I lavori lunghi in un esecutore a parte.** Il pianificatore esegue i lavori uno dopo l'altro. Lo scaricamento dello storico può durare ore, quindi i lavori del pianificatore svegliano soltanto un esecutore in sottofondo (`MarketDataService`), che fa un giro alla volta. + +**10. Dati di mercato spenti dove non servono.** +- Nella modalità dimostrativa, con `ANUBIS_MARKET_DATA=off` (o `0`, `false`) e nei test del server, salvo quelli che passano una rete finta. +- I test non toccano mai la rete. La prova sui dati reali (`RealHistoryProof`) sta nella categoria `LiveDemo`, esclusa dal giro normale. + +**11. Archivi Binance per la ricerca.** +- Si tengono le candele giornaliere in USDT di 25 monete dal 2017, per avere storia prima della nascita delle coppie in EUR (novembre 2023). +- Ogni zip si controlla con il suo SHA-256. Il giro si ripete al massimo ogni 25 giorni. +- La conversione da USDT a EUR, e la scelta di come usarle nelle prove, spetta alla Fase 4. + +**12. Flusso dal vivo solo per la crypto.** Il flusso WebSocket segue l'universo crypto (o BTC, ETH e SOL finché l'universo non c'è). Il flusso IEX delle azioni, limitato a 30 simboli, arriva con la Fase 3, quando ci sono le chiavi e le posizioni da seguire. + +**13. Calendario delle banche centrali modificabile.** La Fed avverte che le date sono provvisorie. L'elenco delle riunioni è un'impostazione (`calendar.central_banks`), con un valore iniziale letto dalle pagine ufficiali e un controllo del formato prima di salvarlo. + +## Conseguenze + +- Nessun componente esterno nuovo: l'elenco dell'ADR 0004 non cambia. +- Il rapporto di qualità (`anubis data report`, `/api/data/quality`) mostra per ogni strumento storia, buchi, anomalie e come sono finite, i problemi aperti e lo stato di ogni fonte. +- Le prove storiche della Fase 4 leggono dai file di ricerca, mai dal database. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index f5a4490..5816877 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -1,5 +1,6 @@ using Anubis.Access; using Anubis.Core; +using Anubis.Data; using Anubis.Db; using Anubis.Demo; using Anubis.Platform; @@ -34,7 +35,8 @@ public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Id internal sealed record HostChanged(HostMode Mode); /// Everything that needs the database, built once it is reachable and the installation checks out. -internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler); +internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler, + MarketDataService? MarketData = null); /// /// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured @@ -60,6 +62,7 @@ internal sealed partial class AnubisHost( private Database? _db; private Task? _schedulerLoop; private CancellationTokenSource? _schedulerStop; + private MarketDataService? _market; private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0); private volatile AppServices? _services; @@ -280,7 +283,10 @@ internal sealed partial class AnubisHost( } var scheduler = new Scheduler(clock, bus); - _services = new AppServices(_db, settings, secrets, access, backups, scheduler); + _market = MarketDataEnabled + ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger) + : null; + _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market); StartScheduler(scheduler, backups); SetStatus(HostMode.Ready, null); } @@ -375,17 +381,32 @@ internal sealed partial class AnubisHost( Wake(); } + /// + /// Market data needs the network: off in demo mode (SPEC 13.7), when ANUBIS_MARKET_DATA is off, and + /// in tests unless they bring their own fake network. + /// + private bool MarketDataEnabled => + !options.Demo && overrides?.MarketData != false && + environment.GetValueOrDefault("ANUBIS_MARKET_DATA") is not ("0" or "off" or "false"); + private void StartScheduler(Scheduler scheduler, Backups backups) { scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone), async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false)) { MaxLateness = TimeSpan.FromHours(2) }); + foreach (var job in _market?.Jobs() ?? []) + { + scheduler.Add(job); + } + _schedulerStop = new CancellationTokenSource(); var token = _schedulerStop.Token; + var market = _market; _schedulerLoop = Task.Run(async () => { using var runs = bus.Subscribe(); var recorder = RecordJobsAsync(runs, token); + var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token); try { await scheduler.RunAsync(token).ConfigureAwait(false); @@ -394,10 +415,26 @@ internal sealed partial class AnubisHost( { } + await collecting.ConfigureAwait(false); await recorder.ConfigureAwait(false); }, CancellationToken.None); } + private async Task RunMarketDataAsync(MarketDataService market, CancellationToken cancellationToken) + { + try + { + await market.RunAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + LogMarketDataFailed(logger, ex); + } + } + // The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6). private async Task RecordJobsAsync(EventSubscription runs, CancellationToken cancellationToken) { @@ -449,6 +486,8 @@ internal sealed partial class AnubisHost( _schedulerStop.Dispose(); _schedulerStop = null; _schedulerLoop = null; + _market?.Dispose(); + _market = null; } // Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5). @@ -485,6 +524,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Error, Message = "Startup step failed")] private static partial void LogStepFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")] + private static partial void LogMarketDataFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")] private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job); } diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index f72ad25..d040a84 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -203,6 +203,10 @@ code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-siz height: 40px; border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text); font: inherit; font-size: 14px; padding: 0 12px; } +textarea { + border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text); + font-family: ui-monospace, Consolas, monospace; font-size: 13.5px; padding: 8px 12px; resize: vertical; +} .currency select { appearance: none; padding: 0 40px 0 16px; font-weight: 550; cursor: pointer; } .select-chevron { position: absolute; right: 14px; top: 12px; pointer-events: none; color: var(--text-2); } diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 99ce779..091ecf4 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -3,6 +3,7 @@ @inject AnubisHost Host @inject ShellData Shell @inject SecondFactorDrafts Drafts +@inject Anubis.Core.IClock Clock Impostazioni · Anubis @@ -24,7 +25,7 @@ }
@@ -55,6 +56,51 @@

Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.

+
+

Dati

+ @if (Host.Services!.MarketData is not { } market) + { +

@(Shell.IsDemo ? "Nella modalità dimostrativa i dati di mercato non si scaricano." : "La raccolta dei dati di mercato è spenta (ANUBIS_MARKET_DATA).")

+ } + else + { +
+
Prezzi crypto in diretta
@(market.LiveConnected ? "collegati" : "non collegati")
+
Ultimo giro dello storico
@(market.LastHistoryRun is { } run ? Format.ShortDate(run, Shell.Now, Shell.Zone) : "in corso o non ancora fatto")
+
+ } + @if (_sources.Count > 0) + { +

Fonti

+
+ + + + @foreach (var s in _sources) + { + + + + + + + } + +
FonteStatoUltima rispostaNote
@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

+ +

Riunioni di Fed e BCE

+
+ + + + + + +
+

Sicurezza

@if (Shell.IsDemo) @@ -171,6 +217,8 @@ @code { private readonly List _appearance = []; + private IReadOnlyList _sources = []; + private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private List _history = []; private IReadOnlyList _backups = []; private bool _hasSecondFactor; @@ -193,6 +241,8 @@ _appearance.Add(await services.Settings.GetAsync(SettingsStore.Theme.Key, ct)); _appearance.Add(await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)); _history = await services.Settings.HistoryAsync(null, 50, ct); + _meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct); + _sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct); _backups = services.Backups.List(); var user = HttpContext!.User; _hasSecondFactor = CurrentUser.HasSecondFactor(user); @@ -210,10 +260,29 @@ "segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.", "salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.", "impostazione" => "Questa impostazione non si può cambiare così.", + "riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».", "bot" => "Comando non ammesso nello stato attuale del bot.", _ => PasswordMessages.For(Errore), }; + private static string SourceName(string source) => source switch + { + "okx" => "OKX Europe (crypto)", + "alpaca" => "Alpaca (azioni, conto di prova)", + "storico" => "Storico giornaliero delle crypto", + "storico_azioni" => "Storico giornaliero delle azioni", + "binance" => "Archivi Binance (ricerca)", + "ecb" => "Cambi della BCE", + "forexfactory" => "Calendario economico (Forex Factory)", + "fred" => "Date dei dati USA (FRED)", + "finnhub" => "Date delle trimestrali (Finnhub)", + "central_banks" => "Riunioni di Fed e BCE", + "alternative.me" => "Indice di paura e avidità", + "cboe" => "VIX (Cboe)", + "okx_derivatives" => "Funding e interesse aperto di BTC (OKX)", + _ => source, + }; + private static string Label(string? value) => value switch { null => "—", diff --git a/src/Anubis.Server/DataCommand.cs b/src/Anubis.Server/DataCommand.cs new file mode 100644 index 0000000..6178111 --- /dev/null +++ b/src/Anubis.Server/DataCommand.cs @@ -0,0 +1,130 @@ +using System.Collections; +using System.Globalization; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Server; + +/// +/// Command line tools for the data (Phase 2): the quality report, and the imports into the research history of the +/// data folder (SPEC 6.6). They read the same startup configuration as the server. +/// +internal static class DataCommand +{ + private const string Usage = + "Uso: anubis data report [--days N] [--out file.md]\n" + + " anubis data binance <1d|1m> (per esempio BTCUSDT 1d 2017-08)\n" + + " anubis data csv (colonne descritte in file.mapping.json o mapping.json)\n" + + "Opzioni comuni: [--platform docker|desktop] [--data-dir ]"; + + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, + HttpMessageHandler? handler = null) + { + output ??= Console.Out; + if (args.Length < 1 || args[0] is not ("report" or "binance" or "csv")) + { + await output.WriteLineAsync(Usage).ConfigureAwait(false); + return 2; + } + + var (positional, rest) = Split(args[1..]); + environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); + var options = ServerOptions.Parse([.. rest], environment); + var config = options.LoadConfig(environment); + var clock = new SystemClock(); + try + { + switch (args[0]) + { + case "report": + return await ReportAsync(config, clock, rest, output).ConfigureAwait(false); + case "binance" when positional.Count == 3: + config.Data.Ensure(); + var month = DateOnly.ParseExact(positional[2] + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture); + using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false)) + { + http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), new ResearchStore(config.Data.Research), clock); + await WriteAsync(output, await importer.ImportAsync(positional[0].ToUpperInvariant(), positional[1], month.Year, month.Month, CancellationToken.None) + .ConfigureAwait(false)).ConfigureAwait(false); + } + + return 0; + case "csv" when positional.Count == 1: + config.Data.Ensure(); + var file = Path.GetFullPath(positional[0]); + var result = await new CsvImporter(new ResearchStore(config.Data.Research)).ImportAsync(file, CsvImporter.MappingFor(file), CancellationToken.None) + .ConfigureAwait(false); + await WriteAsync(output, result).ConfigureAwait(false); + return 0; + default: + await output.WriteLineAsync(Usage).ConfigureAwait(false); + return 2; + } + } + catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or System.Text.Json.JsonException + or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException) + { + await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); + return 1; + } + } + + private static async Task ReportAsync(Platform.StartupConfig config, IClock clock, IReadOnlyList rest, TextWriter output) + { + if (!config.IsComplete) + { + await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false); + return 1; + } + + Redactor.Register(config.Db!.Password); + var days = Option(rest, "--days") is { } d ? int.Parse(d, CultureInfo.InvariantCulture) : 7; + await using var db = Database.Open(config.Db!, allowCreate: false); + var markdown = (await QualityReport.BuildAsync(db, clock, TimeSpan.FromDays(days), CancellationToken.None).ConfigureAwait(false)).ToMarkdown(); + if (Option(rest, "--out") is { } path) + { + await File.WriteAllTextAsync(path, markdown).ConfigureAwait(false); + await output.WriteLineAsync("Rapporto scritto in " + Path.GetFullPath(path)).ConfigureAwait(false); + } + else + { + await output.WriteAsync(markdown).ConfigureAwait(false); + } + + return 0; + } + + private static Task WriteAsync(TextWriter output, ImportResult result) + { + var lines = new List + { + string.Create(CultureInfo.InvariantCulture, + $"{result.Venue} {result.Symbol} {result.Timeframe}: {result.Bars} barre, dal {result.First:yyyy-MM-dd HH:mm} al {result.Last:yyyy-MM-dd HH:mm} (UTC)."), + }; + lines.AddRange(result.Notes.Select(n => "- " + n)); + return output.WriteLineAsync(string.Join(Environment.NewLine, lines)); + } + + private static string? Option(IReadOnlyList args, string name) + { + for (var i = 0; i < args.Count - 1; i++) + { + if (args[i] == name) + { + return args[i + 1]; + } + } + + return null; + } + + // Positional arguments come first; from the first "--" option on, everything is options. + private static (List Positional, List Options) Split(string[] args) + { + var index = Array.FindIndex(args, a => a.StartsWith("--", StringComparison.Ordinal)); + return index < 0 ? (args.ToList(), []) : (args[..index].ToList(), args[index..].ToList()); + } +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 4d3c8cc..ae96ff6 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -5,6 +5,7 @@ using System.Text; using System.Text.Json; using Anubis.Access; using Anubis.Core; +using Anubis.Data; using Anubis.Db; using Anubis.Platform; using Microsoft.AspNetCore.Antiforgery; @@ -138,6 +139,28 @@ internal static partial class Endpoints api.MapGet("/settings/history", async (AnubisHost host, CancellationToken ct) => Results.Json(await host.Services!.Settings.HistoryAsync(null, 100, ct).ConfigureAwait(false), _json)); + // Data quality report (SPEC 6.4): JSON, or Markdown with ?format=md. + api.MapGet("/data/quality", async (AnubisHost host, IClock clock, int? days, string? format, CancellationToken ct) => + { + var report = await QualityReport.BuildAsync(host.Services!.Db, clock, TimeSpan.FromDays(Math.Clamp(days ?? 7, 1, 3650)), ct).ConfigureAwait(false); + return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json); + }); + + // The external sources and the live feed: what is on, what is off and why (SPEC 4.4). + api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) => + { + var services = host.Services!; + var market = services.MarketData; + return Results.Json(new + { + enabled = market is not null, + live = market?.LiveConnected ?? false, + lastHistoryRun = market?.LastHistoryRun, + sources = await new SourceStateStore(services.Db, clock).ListAsync(ct).ConfigureAwait(false), + freshness = market?.Freshness.Snapshot() ?? [], + }, _json); + }); + // Only whether a secret is set and where it comes from: the value never leaves the server (SPEC 15.4). api.MapGet("/secrets/{name}", async (string name, AnubisHost host, CancellationToken ct) => Results.Json(await host.Services!.Secrets.StatusAsync(name, ct).ConfigureAwait(false), _json)); diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index f4a1eeb..9f05537 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -151,11 +151,16 @@ internal static partial class Forms private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/impostazioni"); - if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key) + if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key) { return Results.Redirect(With(back, "errore", "impostazione")); } + if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null) + { + return Results.Redirect(With(back, "errore", "riunioni")); + } + var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false); return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione")); } diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index a9595bc..f8c172c 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -6,6 +6,12 @@ if (args.Length >= 1 && args[0] == "db") return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false); } +// "anubis data report|binance|csv": the data quality report and the research imports (Phase 2). +if (args.Length >= 1 && args[0] == "data") +{ + return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false); +} + var app = ServerApp.Build(args); await app.RunAsync().ConfigureAwait(false); return 0; diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs index a872996..fb853e0 100644 --- a/src/Anubis.Server/ServerOptions.cs +++ b/src/Anubis.Server/ServerOptions.cs @@ -67,4 +67,12 @@ internal sealed record ServerOverrides /// How often the database is checked while running and retried while it is missing. public TimeSpan? DatabaseCheckInterval { get; init; } + + /// False turns market data off (tests without network); null follows demo mode and ANUBIS_MARKET_DATA. + public bool? MarketData { get; init; } + + /// Answers the market data requests instead of the network (tests). + public HttpMessageHandler? MarketHttp { get; init; } + + public Func? MarketSockets { get; init; } } diff --git a/src/Anubis/Brokers/Alpaca.cs b/src/Anubis/Brokers/Alpaca.cs new file mode 100644 index 0000000..51089f0 --- /dev/null +++ b/src/Anubis/Brokers/Alpaca.cs @@ -0,0 +1,408 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Brokers; + +/// Addresses and limits of Alpaca on the free "Basic" plan (SPEC 4.1, docs re-read on 10/11/2026: API-NOTES). +public sealed record AlpacaOptions +{ + public Uri DataUrl { get; init; } = new("https://data.alpaca.markets"); + + /// Trading API: paper by default. Assets, calendar and clock come from here. + public Uri TradingUrl { get; init; } = new("https://paper-api.alpaca.markets"); + + /// Real-time feed of the free plan: IEX only. + public Uri StreamUrl { get; init; } = new("wss://stream.data.alpaca.markets/v2/iex"); + + /// Symbols the free plan allows on the stream. + public int MaxStreamSymbols { get; init; } = 30; + + /// Consolidated (SIP) data only when the request ends at least 15 minutes ago; one more minute of margin. + public TimeSpan SipDelay { get; init; } = TimeSpan.FromMinutes(16); + + /// The plan allows 200 calls a minute; Anubis stays a little below. + public int CallsPerMinute { get; init; } = 190; +} + +/// Key id and secret of an Alpaca API key. Never logged (trap 17). +public sealed record AlpacaCredentials(string KeyId, string Secret) +{ + public override string ToString() => "AlpacaCredentials(***)"; +} + +/// The broker's clock: whether the market is open and when it opens and closes next. +public sealed record MarketClock(DateTimeOffset At, bool IsOpen, DateTimeOffset NextOpen, DateTimeOffset NextClose); + +/// +/// The data part of the Alpaca adapter on the free plan (issue #19): assets, daily bars from the consolidated +/// tape (real and adjusted, volumes never from IEX: trap 8), minute bars, quotes, the IEX stream within 30 +/// symbols, calendar, clock and corporate actions. Without keys every call says so and nothing is sent. +/// +public sealed class AlpacaClient : IMarketDataSource +{ + public static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + private const int SymbolsPerRequest = 100; + // Unit splits (SPAC units turning into shares and warrants) are not price splits and are not read. + private const string ActionTypes = "forward_split,reverse_split,cash_dividend,stock_dividend,name_change"; + + private readonly ApiHttp _http; + private readonly IClock _clock; + private readonly AlpacaOptions _options; + private readonly AlpacaCredentials? _credentials; + private readonly Func _sockets; + private readonly RateLimiter _limiter; + + public AlpacaClient(HttpClient http, IClock clock, AlpacaCredentials? credentials, AlpacaOptions? options = null, Func? sockets = null) + { + _clock = clock; + _options = options ?? new AlpacaOptions(); + _credentials = credentials; + _http = new ApiHttp(http, clock, "Alpaca"); + _sockets = sockets ?? (() => new ClientWebSocketTransport()); + _limiter = new RateLimiter(clock, _options.CallsPerMinute, TimeSpan.FromMinutes(1)); + if (credentials is not null) + { + Redactor.Register(credentials.KeyId); + Redactor.Register(credentials.Secret); + } + } + + public string Venue => Venues.Alpaca; + + /// False until the user saves the Alpaca keys: the stock part waits for them (SPEC 2.3). + public bool IsConfigured => _credentials is not null; + + public async Task> ListInstrumentsAsync(CancellationToken cancellationToken) + { + // Every status: inactive assets stay in the catalogue for the universe "as of" a past date (SPEC 6.7). + using var json = await GetAsync(_options.TradingUrl, "/v2/assets?asset_class=us_equity", cancellationToken).ConfigureAwait(false); + return json.RootElement.EnumerateArray().Select(ReadAsset).ToList(); + } + + public static InstrumentSpec ReadAsset(JsonElement item) => + new(Venues.Alpaca, Text(item, "symbol"), Text(item, "name"), AssetClasses.Equity, "USD") + { + Exchange = Text(item, "exchange"), + Status = Text(item, "status"), + Fractionable = item.TryGetProperty("fractionable", out var f) && f.ValueKind == JsonValueKind.True, + }; + + public async Task> FetchDailyBarsAsync(string symbol, DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + var all = await FetchDailyBarsAsync([symbol], first, last, cancellationToken).ConfigureAwait(false); + return all.TryGetValue(symbol, out var bars) ? bars : []; + } + + /// + /// Consolidated daily bars of many symbols, real and adjusted for splits and dividends, for the days from + /// to . A day whose close is not 15 minutes old is left out. + /// + public async Task>> FetchDailyBarsAsync( + IReadOnlyCollection symbols, DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(symbols); + var end = DayStart(last.AddDays(1)); + var latest = _clock.UtcNow - _options.SipDelay; + if (end > latest) + { + end = latest; + } + + var result = new Dictionary>(StringComparer.Ordinal); + foreach (var chunk in symbols.Distinct().Chunk(SymbolsPerRequest)) + { + var raw = await BarsAsync(chunk, "1Day", "sip", "raw", DayStart(first), end, cancellationToken).ConfigureAwait(false); + var adjusted = await BarsAsync(chunk, "1Day", "sip", "all", DayStart(first), end, cancellationToken).ConfigureAwait(false); + foreach (var (symbol, bars) in raw) + { + var adjustedByDay = adjusted.TryGetValue(symbol, out var a) ? a.ToDictionary(b => NewYorkDay(b.OpensAt)) : []; + result[symbol] = bars + .Select(b => + { + var day = NewYorkDay(b.OpensAt); + return new DailyBar(day, b.Open, b.High, b.Low, b.Close, b.Volume) + { + Adjusted = adjustedByDay.TryGetValue(day, out var adj) ? new Ohlc(adj.Open, adj.High, adj.Low, adj.Close) : null, + }; + }) + .Where(b => b.Day >= first && b.Day <= last) + .ToList(); + } + } + + return result; + } + + public async Task> FetchMinuteBarsAsync(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken cancellationToken) + { + // Older than 15 minutes: the consolidated tape. Otherwise IEX, the only real-time feed of the free plan. + var feed = until <= _clock.UtcNow - _options.SipDelay ? "sip" : "iex"; + var bars = await BarsAsync([symbol], "1Min", feed, "raw", start, until.AddTicks(-1), cancellationToken).ConfigureAwait(false); + return bars.TryGetValue(symbol, out var list) ? list.Where(b => b.OpensAt >= start && b.OpensAt < until).ToList() : []; + } + + public async Task 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 to , in UTC (times are New York's). + public async Task> 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 corporate_actions object of the response, grouped by type. + public static IReadOnlyList 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 IReadOnlyList ParseStreamMessage(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 permits requests in any window of window, on the injected clock. Every source keeps under +/// its published limits (SPEC 2.2: limits are never bypassed). +/// +public sealed class RateLimiter(IClock clock, int permits, TimeSpan window) +{ + private readonly Lock _gate = new(); + private readonly Queue _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 Task GetStringAsync(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 Task GetBytesAsync(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. + Task ReceiveAsync(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 x-simulated-trading: 1 header, other stream host. + public bool Demo { get; init; } + + /// 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 ping; the server drops a silent connection after 30. + 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"), + }; +} + +/// 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 Dictionary Headers(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 (1Dutc, trap 23), one-minute candles, ticker and the live streams. +/// Every answer carries code: OKX reports errors with HTTP 200, so the code is what counts. +/// +public sealed class OkxClient : IMarketDataSource +{ + /// Daily bars: 1D opens at 16:00 UTC (Hong Kong midnight), 1Dutc at 00:00 UTC. + public const string DailyBar = "1Dutc"; + + /// 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. BTC-USDT-SWAP: public data, used only as an indicator. + public async Task 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 Task ServerTimeAsync(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 IReadOnlyList ParseStreamMessage(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 after (rows older than it). + private async Task> 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. , when present, returns +/// the reason a free-text value is refused, in the words the interface shows, or null when it is valid. +/// +public sealed record SettingDefinition(string Key, string Label, string Default, IReadOnlyList? 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 IReadOnlyList All = [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 IReadOnlyList All = [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). +/// +/// 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. +/// +/// +public static class Adjustments +{ + /// + /// 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 : 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. + /// + public static IReadOnlyList 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 : 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. + /// + public static IReadOnlyList 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. is needed for cash dividends. + /// + 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; + } + + /// 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 IReadOnlyList Detect(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 ON CONFLICT, which both engines understand. The research history lives in +/// files instead (). +/// +public sealed class BarStore(Database db, IClock clock) +{ + /// 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 Task UpsertDailyAsync(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 to , both included, oldest first. + public async Task> 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 by : a new + /// split or dividend changes the basis of every older adjusted price, and the history must stay on one basis. + /// + public Task 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 (included) to (excluded), oldest first. + public async Task> 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 Task PruneMinutesAsync(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 ) 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. +/// +public sealed partial class MarketCollector +{ + /// 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 IReadOnlyList Backoff = + [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 the 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. + /// + public async Task 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 Task BackfillMinutesAsync(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 on 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. + /// + public async Task RunLiveAsync(IReadOnlyList 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 Task AcceptMinutesAsync(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 Task ConcludeAsync(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; downloads them within their limits. +/// +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"; + + /// Rates of the daily or 90-day XML for the asked, EUR as base. + public static IReadOnlyList 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 IReadOnlyList ParseHistoryCsv(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 IReadOnlyList Parse(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 IReadOnlyList Parse(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)}"); + + /// + /// hour: 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. + /// + public static IReadOnlyList 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, +/// FED 2026-12-09 or BCE 2026-12-17. Fed decisions come at 14:00 New York, ECB ones at 14:15 Frankfurt. +/// +public static class CentralBanks +{ + public const string Source = "central_banks"; + + /// 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 IReadOnlyList Parse(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 IReadOnlyList Parse(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 , dated at midnight UTC of the session day. + public static IReadOnlyList 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 IReadOnlyDictionary Exchanges = 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 IReadOnlyList MarkFunds(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 IReadOnlyList Parse(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 IReadOnlyList ReadZip(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 IReadOnlyList ParseCsv(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 , and risk blocks new entries +/// on that instrument (SPEC 6.5, 9.2). Exits and stops are never blocked by this. +/// +public sealed class FreshnessMonitor(IClock clock, EventBus bus, TimeSpan? maxAge = null) +{ + /// 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 IReadOnlyCollection Followed => _entries.Keys.ToList(); + + /// A datum arrived. is the venue's time; the age counts from when it arrived here if that is earlier. + 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)); + } + } + + /// 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 IReadOnlyList Snapshot() + { + 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, IReadOnlyList Notes); + +/// +/// 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 Task ImportAsync(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 /data/import (SPEC 6.6): a JSON file next to the CSV with the same name and +/// .mapping.json, or mapping.json for the whole folder. Columns are named by header or by 0-based number. +/// +public sealed record CsvMapping +{ + /// 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"; + + /// unix_ms, unix_s, unix_us, auto (milliseconds or microseconds by size), or a .NET date format such as yyyy-MM-dd HH:mm:ss. + public string TimeFormat { get; init; } = "auto"; + + /// 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 +/// delisted: its history and the orders that used it still point to it. +/// +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); + + /// + /// Writes what the venue listed today. With the list is the venue's whole catalogue + /// and instruments missing from it become delisted. + /// + public async Task 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 Task EnsureAsync(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 instruments.venue. +public static class Venues +{ + public const string Okx = "okx"; + public const string Alpaca = "alpaca"; + + /// 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. +/// is the venue's own identifier: BTC-EUR on OKX, AAPL on Alpaca. +/// +public sealed record InstrumentSpec( + string Venue, + string Symbol, + string Name, + string AssetClass, + string QuoteCurrency) +{ + public string? BaseCurrency { get; init; } + + /// 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: live, suspend, active, inactive… + public string? Status { get; init; } + + public bool? Fractionable { get; init; } + + /// 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 (UTC). Bars are analysis data and stay +/// floating point (SPEC 5.4). +/// +public sealed record Bar(DateTimeOffset OpensAt, double Open, double High, double Low, double Close, double Volume) +{ + /// Traded value in the quote currency, when the source gives it (OKX volCcyQuote). + public double? QuoteVolume { get; init; } +} + +/// +/// A daily bar. 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). +/// +public sealed record DailyBar(DateOnly Day, double Open, double High, double Low, double Close, double Volume) +{ + public double? QuoteVolume { get; init; } + + /// 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. is the moment the venue gives, in UTC. +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); + +/// A one-minute bar. is false while the minute is still running. +public sealed record BarEvent(string Symbol, Bar Bar, bool Closed) : MarketEvent(Symbol, Bar.OpensAt); + +/// Kinds of corporate action (SPEC 6.10). +public static class CorporateActionKinds +{ + /// Forward or reverse split: ratio new shares for each old one (2 = 2-for-1, 0.1 = 1-for-10). + public const string Split = "split"; + + public const string CashDividend = "cash_dividend"; + + /// 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. identifies it at the source, so a second reading does not add it twice. +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; } + + /// 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 (_DEMO): without them the stock part is off and the sources list says so. +/// +public sealed partial class MarketDataService : IDisposable +{ + /// 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 IReadOnlyList CoreCrypto = ["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 IReadOnlyList BinanceCoins = + [ + "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 IReadOnlyList Jobs() => + [ + 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 Task AlpacaAsync(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 days. + public Task 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 IReadOnlyList CheckDaily(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. lists the minutes that should exist (every minute for + /// crypto, the session minutes for stocks); without it gaps are not looked for. + /// + public static IReadOnlyList 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 IEnumerable EveryMinute(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(List closes) + { + 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 and with no bar, grouped in runs of + /// consecutive expected moments: a weekend between two missing sessions does not split the gap. + /// + private static List<(DateTimeOffset First, DateTimeOffset Last, int Count)> MissingRuns( + IEnumerable 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 data_issues. +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); + +/// +/// 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 Task RecordAsync(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, IReadOnlyList Instruments, 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: units of for one , as published for . +public sealed record FxRate(string Base, string Quote, DateOnly Date, decimal Rate, string Source); + +/// +/// 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 Task UpsertAsync(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 , or the last one before it; null if none is known. + public Task 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). 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. +/// +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; } + + /// For earnings: bmo before the open, amc after the close, dmh during market hours. + public string? TimeHint { get; init; } + + /// 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 Task UpsertAsync(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", + }; + + /// is the funding of one period; its length (usually 8 hours). + 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 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 ; null when the market is closed or the day is not covered yet. + public MarketSession? SessionOn(DateOnly day) => _days.TryGetValue(day, out var session) ? session : null; + + public bool Covers(DateOnly day) => _days.ContainsKey(day); + + /// Saves the sessions of [first, last]; days without a session are saved as closed. + public async Task SaveAsync(IReadOnlyCollection sessions, 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 IReadOnlyList Sessions(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 source_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. +/// +public sealed class ReferenceSources( + ApiHttp http, + Database db, + IClock clock, + SettingsStore settings, + Func> secret, + OkxClient? okx = null) +{ + /// Currencies kept from the ECB: the dollar for display and the tax export (SPEC 6.8). + public static readonly IReadOnlyList Currencies = ["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 IReadOnlyDictionary MinInterval = 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 Task RefreshFxAsync(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 Task RefreshCalendarAsync(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 Task RefreshFredAsync(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 Task EarningsFilterActiveAsync(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 Task RefreshMoodAsync(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 Task RunAsync(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 when they read. +/// +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, + }; +} + +/// +/// The research history (SPEC 6.6, ADR 0003): one gzip-compressed CSV per instrument, timeframe and year under +/// 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. +/// +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"); + + /// Writes bars, merging each year with its existing file. Returns the number of bars now in the touched files. + public async Task WriteAsync(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 (included) to (excluded), oldest first. + public async IAsyncEnumerable 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 IAsyncEnumerable ReadFileAsync(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), + }; + } + + /// Canonical decimal text: no exponent, no trailing zeros. + private static string Text(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture); + + private static decimal Number(string text) => decimal.Parse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + + /// File-name-safe form of a symbol: letters, digits, dash and underscore; anything else becomes underscore. + public static string Safe(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var chars = name.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' ? c : '_').ToArray(); + var safe = new string(chars); + return safe is "." or ".." ? "_" : safe; + } +} diff --git a/src/Anubis/Data/Sources.cs b/src/Anubis/Data/Sources.cs new file mode 100644 index 0000000..959d548 --- /dev/null +++ b/src/Anubis/Data/Sources.cs @@ -0,0 +1,32 @@ +namespace Anubis.Data; + +/// +/// The data part of a broker adapter (SPEC 5.3): instruments, bars, quotes and the live feed. The order part +/// arrives in Phase 3 on the same adapters. +/// +public interface IMarketDataSource +{ + string Venue { get; } + + Task> ListInstrumentsAsync(CancellationToken cancellationToken); + + /// Daily bars for the days from to , both included, oldest first. + Task> FetchDailyBarsAsync(string symbol, DateOnly first, DateOnly last, CancellationToken cancellationToken); + + /// Closed one-minute bars opening from (included) to (excluded), oldest first. + Task> FetchMinuteBarsAsync(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken cancellationToken); + + Task FetchQuoteAsync(string symbol, CancellationToken cancellationToken); + + /// + /// Opens a live feed for . The sequence ends when the connection drops: the caller + /// reconnects and recovers the gap (trap 10). + /// + IAsyncEnumerable StreamAsync(IReadOnlyCollection symbols, CancellationToken cancellationToken); +} + +/// A source refused or failed. says whether trying again later can help. +public sealed class MarketDataException(string message, bool retryable = true, Exception? inner = null) : Exception(message, inner) +{ + public bool Retryable { get; } = retryable; +} diff --git a/src/Anubis/Data/Universes.cs b/src/Anubis/Data/Universes.cs new file mode 100644 index 0000000..464ca48 --- /dev/null +++ b/src/Anubis/Data/Universes.cs @@ -0,0 +1,293 @@ +using System.Text.RegularExpressions; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Data; + +/// A member of a universe on a date, with its rank and the measure it was ranked by. +public sealed record UniverseMember(Guid InstrumentId, string Symbol, int Rank, double Measure); + +public static class Universes +{ + public const string Equity = "equity_us"; + public const string Crypto = "crypto_eur"; +} + +/// An instrument with the daily bars known for it; bars after the date are ignored, never used. +public sealed record UniverseCandidate(Instrument Instrument, IReadOnlyList Bars) +{ + /// Hourly spread samples of the last 30 days (crypto), in basis points. + public IReadOnlyList<(DateTimeOffset At, double Bp)> Spreads { get; init; } = []; + + /// The spread right now (crypto), used until 30 days of samples exist. + public double? CurrentSpreadBp { get; init; } +} + +/// +/// The stock universe "as of a date" (SPEC 6.7, 8.2): common shares on NYSE and Nasdaq, fractionable on Alpaca, +/// raw close above 10 $, at least 300 sessions, the 150 with the highest median traded value over 60 sessions. +/// ETFs, ETNs and funds are out. Only bars up to the date count; instruments delisted later are included if they +/// traded then. The flags the API gives only as of today (fractionable, fund) apply as they are (API-NOTES). +/// +public static class EquityUniverse +{ + public const int Size = 150; + public const double MinPrice = 10; + public const int MinSessions = 300; + public const int Window = 60; + + public static readonly IReadOnlySet Exchanges = new HashSet(StringComparer.Ordinal) { "NYSE", "NASDAQ" }; + + public static bool Eligible(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + return spec.AssetClass == AssetClasses.Equity && spec.Exchange is { } exchange && Exchanges.Contains(exchange) && spec.Fractionable == true && spec.IsFund != true; + } + + public static IReadOnlyList Select(DateOnly asOf, IEnumerable candidates, int size = Size) + { + ArgumentNullException.ThrowIfNull(candidates); + var ranked = new List<(Instrument Instrument, double Value)>(); + foreach (var candidate in candidates) + { + if (!Eligible(candidate.Instrument.Spec)) + { + continue; + } + + var bars = UpTo(candidate.Bars, asOf); + if (bars.Count < MinSessions || bars[^1].Day < asOf.AddDays(-7) || bars[^1].Close <= MinPrice) + { + continue; // Too young, not trading any more on that date, or too cheap. + } + + ranked.Add((candidate.Instrument, Median(bars.TakeLast(Window).Select(b => b.Close * b.Volume)))); + } + + return Rank(ranked, size); + } + + internal static List UpTo(IReadOnlyList bars, DateOnly asOf) => bars.Where(b => b.Day <= asOf).OrderBy(b => b.Day).ToList(); + + internal static double Median(IEnumerable values) + { + var sorted = values.Order().ToList(); + if (sorted.Count == 0) + { + return 0; + } + + var middle = sorted.Count / 2; + return sorted.Count % 2 == 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; + } + + internal static IReadOnlyList Rank(List<(Instrument Instrument, double Value)> ranked, int size) => + ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Instrument.Symbol, StringComparer.Ordinal).Take(size) + .Select((r, i) => new UniverseMember(r.Instrument.Id, r.Instrument.Symbol, i + 1, r.Value)).ToList(); +} + +/// +/// The crypto universe of SPEC 8.1: EUR spot pairs listed for at least 400 days, 30-day median traded value above +/// 250,000 €, 30-day median spread below 20 basis points (the current spread until 30 days of samples exist), no +/// stablecoins, wrapped or leveraged tokens; the 10 with the highest value. Recomputed on the first day of each month. +/// +public static partial class CryptoUniverse +{ + public const int Size = 10; + public const int MinAgeDays = 400; + public const double MinValueEur = 250_000; + public const double MaxSpreadBp = 20; + public const int Window = 30; + + /// Stablecoins pegged to a currency or to gold, as listed by the main venues. + public static readonly IReadOnlySet Stablecoins = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "USDT", "USDC", "DAI", "EURC", "EUROC", "EURT", "EURS", "EURI", "EURQ", "EURR", "TUSD", "FDUSD", "PYUSD", "USDE", "USDS", "BUSD", "USDP", "GUSD", + "FRAX", "LUSD", "USDD", "USD1", "RLUSD", "USDG", "USDQ", "USDR", "AEUR", "XAUT", "PAXG", + }; + + /// Wrapped or staked receipts of another coin. + public static readonly IReadOnlySet Wrapped = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "WBTC", "WETH", "WBETH", "STETH", "WSTETH", "CBBTC", "CBETH", "RETH", "WEETH", "EETH", "TBTC", "WBNB", "WSOL", "JITOSOL", "MSOL", "BBSOL", + "STSOL", "WTRX", "WAVAX", "WMATIC", "WPOL", "WFTM", "WHBAR", "SAVAX", "OKSOL", "BETH", "LBTC", + }; + + [GeneratedRegex(@"^\w+?(\d+[LS]|UP|DOWN|BULL|BEAR)$", RegexOptions.IgnoreCase)] + private static partial Regex LeveragedPattern(); + + public static bool Excluded(string baseCurrency) => + Stablecoins.Contains(baseCurrency) || Wrapped.Contains(baseCurrency) || LeveragedPattern().IsMatch(baseCurrency); + + public static IReadOnlyList Select(DateOnly asOf, IEnumerable candidates, int size = Size) + { + ArgumentNullException.ThrowIfNull(candidates); + var ranked = new List<(Instrument Instrument, double Value)>(); + var cutoff = QualityChecks.Midnight(asOf.AddDays(1)); + foreach (var candidate in candidates) + { + var spec = candidate.Instrument.Spec; + var baseCurrency = spec.BaseCurrency ?? spec.Symbol.Split('-')[0]; + if (spec.AssetClass != AssetClasses.Crypto || spec.QuoteCurrency != "EUR" || Excluded(baseCurrency)) + { + continue; + } + + var bars = EquityUniverse.UpTo(candidate.Bars, asOf); + var listedOn = spec.ListedAt is { } listed ? DateOnly.FromDateTime(listed.UtcDateTime) : bars.Count > 0 ? bars[0].Day : asOf; + if (bars.Count < Window || listedOn > asOf.AddDays(-MinAgeDays) || bars[^1].Day < asOf.AddDays(-3)) + { + continue; + } + + var value = EquityUniverse.Median(bars.TakeLast(Window).Select(b => b.QuoteVolume ?? b.Close * b.Volume)); + var samples = candidate.Spreads.Where(s => s.At < cutoff && s.At >= cutoff.AddDays(-Window)).ToList(); + var spread = samples.Count > 0 && samples.Min(s => s.At) <= cutoff.AddDays(-Window + 1) + ? EquityUniverse.Median(samples.Select(s => s.Bp)) + : candidate.CurrentSpreadBp; + if (value <= MinValueEur || spread is not { } bp || bp >= MaxSpreadBp) + { + continue; // An unknown spread counts as too wide. + } + + ranked.Add((candidate.Instrument, value)); + } + + return EquityUniverse.Rank(ranked, size); + } +} + +/// Universes as they were chosen, and the hourly spread samples the crypto one needs. +public sealed class UniverseStore(Database db, IClock clock) +{ + public async Task SaveAsync(string universe, DateOnly asOf, IReadOnlyList members, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(members); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await s.ExecuteAsync("DELETE FROM universe_members WHERE universe = @u AND as_of = @d", cancellationToken, ("u", universe), ("d", BarStore.DayText(asOf))) + .ConfigureAwait(false); + foreach (var m in members) + { + await s.ExecuteAsync( + "INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, @d, @i, @r, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("u", universe), ("d", BarStore.DayText(asOf)), ("i", m.InstrumentId), ("r", m.Rank), ("now", now)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + /// The members of the last computation on or before , by rank. + public async Task> AsOfAsync(string universe, DateOnly asOf, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT m.instrument_id, i.symbol, m.rank FROM universe_members m JOIN instruments i ON i.id = m.instrument_id " + + "WHERE m.universe = @u AND m.as_of = (SELECT MAX(as_of) FROM universe_members WHERE universe = @u AND as_of <= @d) ORDER BY m.rank", + r => new UniverseMember(r.Id("instrument_id"), r.Text("symbol"), (int)r.Number("rank"), 0), ("u", universe), ("d", BarStore.DayText(asOf))), + cancellationToken).ConfigureAwait(false); + + public Task AddSpreadAsync(Guid instrumentId, DateTimeOffset at, double bp, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO spread_samples (id, instrument_id, sampled_at, spread_bp, created_at) VALUES (@id, @i, @t, @bp, @now) " + + "ON CONFLICT (instrument_id, sampled_at) DO UPDATE SET spread_bp = excluded.spread_bp", cancellationToken, + ("id", Ids.NewId(clock)), ("i", instrumentId), ("t", at), ("bp", bp), ("now", clock.UtcNow)), cancellationToken); + + public async Task> SpreadsAsync(Guid instrumentId, DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT sampled_at, spread_bp FROM spread_samples WHERE instrument_id = @i AND sampled_at >= @f AND sampled_at < @t ORDER BY sampled_at", + r => (r.Moment("sampled_at"), r.Measure("spread_bp")), ("i", instrumentId), ("f", from), ("t", to)), cancellationToken).ConfigureAwait(false); + + public Task PruneSpreadsAsync(CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("DELETE FROM spread_samples WHERE sampled_at < @t", cancellationToken, ("t", clock.UtcNow.AddDays(-90))), + cancellationToken); +} + +/// Computes the universes from what the database holds and saves them (issue #24). +public sealed class UniverseBuilder(Database db, IClock clock) +{ + private readonly InstrumentCatalog _catalog = new(db, clock); + private readonly BarStore _bars = new(db, clock); + private readonly UniverseStore _store = new(db, clock); + + public async Task> EquityAsync(DateOnly asOf, CancellationToken cancellationToken) + { + var candidates = new List(); + foreach (var instrument in (await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false)).Where(i => EquityUniverse.Eligible(i.Spec))) + { + var bars = await _bars.DailyAsync(instrument.Id, asOf.AddDays(-(EquityUniverse.MinSessions * 7 / 5) - 30), asOf, cancellationToken).ConfigureAwait(false); + candidates.Add(new UniverseCandidate(instrument, bars)); + } + + var members = EquityUniverse.Select(asOf, candidates); + await _store.SaveAsync(Universes.Equity, asOf, members, cancellationToken).ConfigureAwait(false); + return members; + } + + /// The spread now, for pairs without 30 days of samples; null when unknown. + public async Task> CryptoAsync(DateOnly asOf, Func> currentSpread, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(currentSpread); + var candidates = new List(); + var end = QualityChecks.Midnight(asOf.AddDays(1)); + foreach (var instrument in (await _catalog.ListAsync(Venues.Okx, cancellationToken).ConfigureAwait(false)) + .Where(i => i.IsCrypto && i.Spec.QuoteCurrency == "EUR" && !CryptoUniverse.Excluded(i.Spec.BaseCurrency ?? ""))) + { + var bars = await _bars.DailyAsync(instrument.Id, asOf.AddDays(-CryptoUniverse.Window * 2), asOf, cancellationToken).ConfigureAwait(false); + var spreads = await _store.SpreadsAsync(instrument.Id, end.AddDays(-CryptoUniverse.Window), end, cancellationToken).ConfigureAwait(false); + candidates.Add(new UniverseCandidate(instrument, bars) + { + Spreads = spreads, + CurrentSpreadBp = spreads.Count > 0 && spreads[0].At <= end.AddDays(-CryptoUniverse.Window + 1) ? null : await currentSpread(instrument).ConfigureAwait(false), + }); + } + + var members = CryptoUniverse.Select(asOf, candidates); + await _store.SaveAsync(Universes.Crypto, asOf, members, cancellationToken).ConfigureAwait(false); + return members; + } +} + +/// Corporate actions as they arrive from Alpaca (SPEC 6.10), kept to adjust series and convert levels. +public sealed class CorporateActionStore(Database db, IClock clock) +{ + private const string Columns = "symbol, kind, ex_date, ratio, cash_amount, currency, new_symbol, source, source_key"; + + public async Task UpsertAsync(IEnumerable actions, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actions); + var list = actions.DistinctBy(a => a.SourceKey).ToList(); + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + foreach (var a in list) + { + var instrument = await s.FirstOrDefaultAsync("SELECT id FROM instruments WHERE venue = @v AND symbol = @s", r => (Guid?)r.Id("id"), + ("v", Venues.Alpaca), ("s", a.Symbol)).ConfigureAwait(false); + await s.ExecuteAsync( + $"INSERT INTO corporate_actions (id, instrument_id, {Columns}, created_at) VALUES (@id, @i, @sym, @k, @d, @r, @c, @ccy, @n, @src, @key, @now) " + + "ON CONFLICT (source_key) DO UPDATE SET instrument_id = excluded.instrument_id, kind = excluded.kind, ex_date = excluded.ex_date, " + + "ratio = excluded.ratio, cash_amount = excluded.cash_amount, currency = excluded.currency, new_symbol = excluded.new_symbol", + cancellationToken, ("id", Ids.NewId(clock)), ("i", instrument), ("sym", a.Symbol), ("k", a.Kind), ("d", BarStore.DayText(a.ExDate)), + ("r", a.Ratio), ("c", a.CashAmount), ("ccy", a.Currency), ("n", a.NewSymbol), ("src", a.Source), ("key", a.SourceKey), ("now", now)) + .ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return list.Count; + } + + public async Task> ForSymbolAsync(string symbol, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM corporate_actions WHERE symbol = @s ORDER BY ex_date", Read, ("s", symbol)), + cancellationToken).ConfigureAwait(false); + + /// Actions effective on : the positions and levels of these symbols change at the open (Phase 3). + public async Task> OnAsync(DateOnly day, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM corporate_actions WHERE ex_date = @d ORDER BY symbol", Read, ("d", BarStore.DayText(day))), + cancellationToken).ConfigureAwait(false); + + private static CorporateAction Read(DbRow r) => new(r.Text("symbol"), r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) + { + Ratio = r.MoneyOrNull("ratio"), + CashAmount = r.MoneyOrNull("cash_amount"), + Currency = r.TextOrNull("currency"), + NewSymbol = r.TextOrNull("new_symbol"), + }; +} diff --git a/src/Anubis/Db/Database.cs b/src/Anubis/Db/Database.cs index 350bdfb..2da0f35 100644 --- a/src/Anubis/Db/Database.cs +++ b/src/Anubis/Db/Database.cs @@ -79,7 +79,7 @@ public sealed class Database : IAsyncDisposable Username = settings.User, Password = settings.Password, }; - pg.Timeout = 5; + pg.Timeout = settings.ConnectTimeoutSeconds; pg.CommandTimeout = 60; pg.ApplicationName = "anubis"; var dataSource = new NpgsqlDataSourceBuilder(pg.ToString()).Build(); diff --git a/src/Anubis/Db/Migrations/0002_market_data.sql b/src/Anubis/Db/Migrations/0002_market_data.sql new file mode 100644 index 0000000..f5e1441 --- /dev/null +++ b/src/Anubis/Db/Migrations/0002_market_data.sql @@ -0,0 +1,185 @@ +-- Phase 2: market data (SPEC 5.4, 6, 10.4; ADR 0008). Same text on PostgreSQL and SQLite, as in 0001. +-- Days are TEXT 'yyyy-MM-dd': the exchange date for stocks, the UTC date for crypto. Bars are analysis data and +-- stay floating point (SPEC 5.4); prices that orders use come from quotes and instrument rules, which are exact. + +-- The instrument catalogue (SPEC 6.1): rules read from the venue every day, never written in code. +ALTER TABLE instruments ADD COLUMN base_currency TEXT; +ALTER TABLE instruments ADD COLUMN exchange TEXT; +ALTER TABLE instruments ADD COLUMN tick_size {money}; +ALTER TABLE instruments ADD COLUMN lot_size {money}; +ALTER TABLE instruments ADD COLUMN min_size {money}; +ALTER TABLE instruments ADD COLUMN min_notional {money}; +ALTER TABLE instruments ADD COLUMN status TEXT; +ALTER TABLE instruments ADD COLUMN fractionable {bool}; +ALTER TABLE instruments ADD COLUMN is_fund {bool}; +ALTER TABLE instruments ADD COLUMN listed_at {timestamp}; +ALTER TABLE instruments ADD COLUMN updated_at {timestamp}; + +-- Daily bars for every strategy. Stocks keep both the real prices (orders, universe filters) and the adjusted ones +-- as the source gave them on the last download (signals, anchored to the decision day: SPEC 6.10). +-- quality: ok, suspect (failed a check, waiting for a second reading) or confirmed (a second reading agreed). +CREATE TABLE bars_1d ( + id {uuid} PRIMARY KEY, + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + day TEXT NOT NULL, + open {float} NOT NULL, + high {float} NOT NULL, + low {float} NOT NULL, + close {float} NOT NULL, + volume {float} NOT NULL, + quote_volume {float}, + adj_open {float}, + adj_high {float}, + adj_low {float}, + adj_close {float}, + source TEXT NOT NULL, + quality TEXT NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL, + UNIQUE (instrument_id, day) +){strict}; + +-- One-minute bars, only for instruments in the portfolio and order simulation; kept 400 days (SPEC 5.4, 6.2). +CREATE TABLE bars_1m ( + id {uuid} PRIMARY KEY, + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + opens_at {timestamp} NOT NULL, + open {float} NOT NULL, + high {float} NOT NULL, + low {float} NOT NULL, + close {float} NOT NULL, + volume {float} NOT NULL, + source TEXT NOT NULL, + quality TEXT NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (instrument_id, opens_at) +){strict}; + +-- Splits, reverse splits, dividends, symbol changes (SPEC 6.10). ratio = new shares per old share. +CREATE TABLE corporate_actions ( + id {uuid} PRIMARY KEY, + instrument_id {uuid} REFERENCES instruments (id), + symbol TEXT NOT NULL, + kind TEXT NOT NULL, + ex_date TEXT NOT NULL, + ratio {money}, + cash_amount {money}, + currency TEXT, + new_symbol TEXT, + source TEXT NOT NULL, + source_key TEXT NOT NULL UNIQUE, + applied_at {timestamp}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX corporate_actions_symbol ON corporate_actions (symbol, ex_date); + +-- Reference exchange rates, one per day as published (SPEC 6.8): rate = units of quote for one base. +CREATE TABLE fx_rates ( + id {uuid} PRIMARY KEY, + base TEXT NOT NULL, + quote TEXT NOT NULL, + rate_date TEXT NOT NULL, + rate {money} NOT NULL, + source TEXT NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (base, quote, rate_date) +){strict}; + +-- The exchange calendar as the broker gives it, one row per day of the downloaded range, closed days included. +CREATE TABLE market_calendar ( + id {uuid} PRIMARY KEY, + market TEXT NOT NULL, + session_date TEXT NOT NULL, + is_open {bool} NOT NULL, + open_at {timestamp}, + close_at {timestamp}, + created_at {timestamp} NOT NULL, + UNIQUE (market, session_date) +){strict}; + +-- Economic events, central bank meetings and earnings dates (SPEC 10.4). +CREATE TABLE calendar_events ( + id {uuid} PRIMARY KEY, + kind TEXT NOT NULL, + title TEXT NOT NULL, + currency TEXT, + symbol TEXT, + occurs_at {timestamp} NOT NULL, + time_known {bool} NOT NULL, + time_hint TEXT, + impact TEXT, + forecast TEXT, + previous TEXT, + source TEXT NOT NULL, + source_key TEXT NOT NULL UNIQUE, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX calendar_events_time ON calendar_events (occurs_at); + +-- Mood indicators (SPEC 10.4): fear and greed, VIX, Bitcoin funding and open interest. +CREATE TABLE market_mood ( + id {uuid} PRIMARY KEY, + indicator TEXT NOT NULL, + as_of {timestamp} NOT NULL, + value {float} NOT NULL, + label TEXT, + source TEXT NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (indicator, as_of) +){strict}; + +-- Hourly spread samples of the crypto pairs, for the universe filter of SPEC 8.1. +CREATE TABLE spread_samples ( + id {uuid} PRIMARY KEY, + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + sampled_at {timestamp} NOT NULL, + spread_bp {float} NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (instrument_id, sampled_at) +){strict}; + +-- What the data checks found (SPEC 6.3, 6.4): gaps, duplicates, impossible or suspicious prices, stale feeds. +-- status: open, recovered, unrecoverable, confirmed (a second reading agreed), corrected (it did not). +CREATE TABLE data_issues ( + id {uuid} PRIMARY KEY, + instrument_id {uuid} REFERENCES instruments (id), + timeframe TEXT NOT NULL, + kind TEXT NOT NULL, + starts_at {timestamp} NOT NULL, + ends_at {timestamp} NOT NULL, + status TEXT NOT NULL, + attempts INTEGER NOT NULL, + detail TEXT NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX data_issues_instrument ON data_issues (instrument_id, status); + +-- State of each external source: last request (to respect limits across restarts), last success, last error, +-- and whether it is off because a key is missing (SPEC 4.4: the interface says so). +CREATE TABLE source_state ( + id {uuid} PRIMARY KEY, + source TEXT NOT NULL UNIQUE, + enabled {bool} NOT NULL, + last_request_at {timestamp}, + last_success_at {timestamp}, + last_error TEXT, + note TEXT, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +-- Universes as they were chosen (SPEC 6.7, 8.1, 8.2): the crypto one is recomputed on the first day of each month. +CREATE TABLE universe_members ( + id {uuid} PRIMARY KEY, + universe TEXT NOT NULL, + as_of TEXT NOT NULL, + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + rank INTEGER NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (universe, as_of, instrument_id) +){strict}; diff --git a/src/Anubis/Platform/StartupConfig.cs b/src/Anubis/Platform/StartupConfig.cs index 7d596ef..fd5c238 100644 --- a/src/Anubis/Platform/StartupConfig.cs +++ b/src/Anubis/Platform/StartupConfig.cs @@ -33,6 +33,9 @@ public sealed record DbSettings /// A full PostgreSQL address (ANUBIS_DB_URL) that replaces the five fields. public string? Url { get; init; } + /// Seconds to wait for a new PostgreSQL connection. Short, so a lost server shows quickly; tests raise it. + public int ConnectTimeoutSeconds { get; init; } = 5; + /// What the interface shows: engine and place, never the password. public string Describe() => Engine switch { diff --git a/tests/Anubis.Tests/AlpacaTests.cs b/tests/Anubis.Tests/AlpacaTests.cs new file mode 100644 index 0000000..383eec3 --- /dev/null +++ b/tests/Anubis.Tests/AlpacaTests.cs @@ -0,0 +1,195 @@ +using System.Text.Json; +using Anubis.Brokers; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The data part of the Alpaca adapter on the documentation's examples and synthetic answers (issue #19). Without +/// the user's keys nothing here touches the network; the real check waits for them (SPEC 2.3). +/// +[TestClass] +public sealed class AlpacaTests +{ + private static readonly DateTimeOffset _now = new(2026, 11, 10, 15, 0, 0, TimeSpan.Zero); + private static readonly AlpacaCredentials _keys = new("PKTEST", "test-secret-value"); + + private static (AlpacaClient Client, FakeHttp Http) Create(Action setup, AlpacaCredentials? keys = null) + { + var http = new FakeHttp(); + setup(http); + return (new AlpacaClient(http.Client(), new FastClock(_now), keys ?? _keys), http); + } + + private static string Query(HttpRequestMessage request, string name) => + System.Web.HttpUtility.ParseQueryString(request.RequestUri!.Query)[name] ?? ""; + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task WithoutKeysNothingIsSentAndTheReasonIsClear() + { + var http = new FakeHttp(); + var alpaca = new AlpacaClient(http.Client(), new FastClock(_now), credentials: null); + Assert.IsFalse(alpaca.IsConfigured); + var error = await Assert.ThrowsAsync(() => alpaca.FetchQuoteAsync("AAPL", CancellationToken.None)).ConfigureAwait(false); + StringAssert.Contains(error.Message, "mancano le chiavi"); + Assert.IsFalse(error.Retryable); + Assert.IsEmpty(http.Requests); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task DailyBarsAreConsolidatedWithRealAndAdjustedPricesByNewYorkDate() + { + const string raw = """ + {"bars":{"AAPL":[ + {"t":"2023-09-29T04:00:00Z","o":172.02,"h":173.07,"l":170.341,"c":171.21,"v":51861083,"n":535134,"vw":171.599691}, + {"t":"2024-01-02T05:00:00Z","o":187.15,"h":188.44,"l":183.885,"c":185.64,"v":82488674,"n":1009074,"vw":185.9} + ]},"next_page_token":null} + """; + const string adjusted = """ + {"bars":{"AAPL":[ + {"t":"2023-09-29T04:00:00Z","o":170.0,"h":171.0,"l":168.3,"c":169.2,"v":51861083,"n":535134,"vw":169.6}, + {"t":"2024-01-02T05:00:00Z","o":185.0,"h":186.2,"l":181.7,"c":183.4,"v":82488674,"n":1009074,"vw":183.7} + ]},"next_page_token":null} + """; + var (alpaca, http) = Create(h => h.On("adjustment=raw", raw).On("adjustment=all", adjusted)); + var bars = await alpaca.FetchDailyBarsAsync("AAPL", new DateOnly(2023, 9, 1), new DateOnly(2024, 1, 31), CancellationToken.None).ConfigureAwait(false); + + // T04:00Z in summer and T05:00Z in winter are both midnight in New York. + CollectionAssert.AreEqual(new[] { new DateOnly(2023, 9, 29), new DateOnly(2024, 1, 2) }, bars.Select(b => b.Day).ToArray()); + Assert.AreEqual((172.02, 171.21, 51861083.0), (bars[0].Open, bars[0].Close, bars[0].Volume)); + Assert.AreEqual(new Ohlc(170.0, 171.0, 168.3, 169.2), bars[0].Adjusted); + + foreach (var request in http.Requests) + { + // Consolidated volumes, never IEX (trap 8); the feed is always explicit. + Assert.AreEqual("sip", Query(request, "feed")); + Assert.AreEqual("1Day", Query(request, "timeframe")); + Assert.AreEqual("PKTEST", request.Headers.GetValues("APCA-API-KEY-ID").Single()); + Assert.AreEqual("data.alpaca.markets", request.RequestUri!.Host); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task RecentDaysWaitFifteenMinutesForTheConsolidatedTape() + { + var (alpaca, http) = Create(h => h.On("/v2/stocks/bars", """{"bars":{},"next_page_token":null}""")); + await alpaca.FetchDailyBarsAsync("AAPL", new DateOnly(2026, 11, 1), new DateOnly(2026, 11, 10), CancellationToken.None).ConfigureAwait(false); + var end = DateTimeOffset.Parse(Query(http.Requests[0], "end"), System.Globalization.CultureInfo.InvariantCulture); + Assert.IsLessThanOrEqualTo(_now.AddMinutes(-15), end, "a free plan may ask the SIP only for data at least 15 minutes old"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task PagesAreFollowedUntilTheTokenIsNull() + { + var (alpaca, http) = Create(h => h + .On("page_token=", """{"bars":{},"next_page_token":null}""") + .On("/v2/stocks/bars", Fixture.Text("alpaca/stocks-bars.json"))); + var from = new DateTimeOffset(2022, 1, 3, 9, 0, 0, TimeSpan.Zero); + var bars = await alpaca.FetchMinuteBarsAsync("AAPL", from, from.AddMinutes(1), CancellationToken.None).ConfigureAwait(false); + Assert.HasCount(2, http.Requests); + Assert.AreEqual("QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg==", Query(http.Requests[1], "page_token")); + Assert.AreEqual("sip", Query(http.Requests[0], "feed"), "old minutes come from the consolidated tape"); + Assert.AreEqual(new Bar(from, 178.26, 178.26, 178.21, 178.21, 1118), bars.Single()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task RecentMinutesAndQuotesComeFromIex() + { + var (alpaca, http) = Create(h => h + .On("/v2/stocks/bars", """{"bars":{},"next_page_token":null}""") + .On("/v2/stocks/quotes/latest", Fixture.Text("alpaca/quotes-latest.json"))); + await alpaca.FetchMinuteBarsAsync("AAPL", _now.AddMinutes(-10), _now, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("iex", Query(http.Requests[0], "feed")); + + var quote = await alpaca.FetchQuoteAsync("AAPL", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("iex", Query(http.Requests[1], "feed")); + Assert.AreEqual((172.62m, 172.7m, 2m, 1m), (quote.Bid, quote.Ask, quote.BidSize, quote.AskSize)); + Assert.AreEqual(new DateTimeOffset(2022, 8, 17, 10, 7, 40, TimeSpan.Zero).AddTicks(2865874), quote.At); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CorporateActionsOfTheDocumentation() + { + using var json = JsonDocument.Parse(Fixture.Text("alpaca/corporate-actions.json")); + var actions = AlpacaClient.ReadCorporateActions(json.RootElement).ToDictionary(a => a.Symbol); + + Assert.AreEqual((CorporateActionKinds.Split, new DateOnly(2023, 8, 22), (decimal?)2m), (actions["SRE"].Kind, actions["SRE"].ExDate, actions["SRE"].Ratio)); + Assert.AreEqual(0.02m, actions["MNTS"].Ratio, "1-for-50 reverse split"); + Assert.AreEqual((CorporateActionKinds.CashDividend, (decimal?)0.125m), (actions["FCF"].Kind, actions["FCF"].CashAmount)); + Assert.AreEqual((CorporateActionKinds.StockDividend, (decimal?)1.05m), (actions["MSBC"].Kind, actions["MSBC"].Ratio)); + Assert.AreEqual((CorporateActionKinds.SymbolChange, "VFS"), (actions["BSAQ"].Kind, actions["BSAQ"].NewSymbol)); + Assert.IsTrue(actions.Values.All(a => a.SourceKey.StartsWith("alpaca:", StringComparison.Ordinal))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task CalendarTimesAreNewYorkConvertedToUtc() + { + const string calendar = """ + [{"date":"2026-07-02","open":"09:30","close":"16:00","session_open":"0400","session_close":"2000","settlement_date":"2026-07-06"}, + {"date":"2026-11-27","open":"09:30","close":"13:00","session_open":"0400","session_close":"1700","settlement_date":"2026-11-30"}] + """; + var (alpaca, http) = Create(h => h.On("/v2/calendar", calendar)); + var sessions = await alpaca.FetchCalendarAsync(new DateOnly(2026, 7, 1), new DateOnly(2026, 11, 30), CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("paper-api.alpaca.markets", http.Requests[0].RequestUri!.Host); + Assert.AreEqual(new DateTimeOffset(2026, 7, 2, 13, 30, 0, TimeSpan.Zero), sessions[0].OpenUtc, "summer: New York is UTC−4"); + Assert.AreEqual(new DateTimeOffset(2026, 11, 27, 18, 0, 0, TimeSpan.Zero), sessions[1].CloseUtc, "short session after Thanksgiving, UTC−5"); + + using var clock = JsonDocument.Parse(Fixture.Text("alpaca/clock-v2.json")); + var read = AlpacaClient.ReadClock(clock.RootElement); + Assert.IsTrue(read.IsOpen); + Assert.AreEqual(new DateTimeOffset(2025, 6, 24, 20, 0, 0, TimeSpan.Zero), read.NextClose); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AssetsKeepExchangeStatusAndFractions() + { + using var json = JsonDocument.Parse(Fixture.Text("alpaca/assets.json")); + var spec = AlpacaClient.ReadAsset(json.RootElement); + Assert.AreEqual(("AAPL", "NASDAQ", "active", (bool?)true, "USD"), (spec.Symbol, spec.Exchange, spec.Status, spec.Fractionable, spec.QuoteCurrency)); + Assert.IsNull(spec.IsFund, "Alpaca has no ETF flag: it comes from nasdaqtraded.txt"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task StreamStaysWithinThirtySymbolsAndReadsBarsAndQuotes() + { + var socket = new FakeSocket(); + var alpaca = new AlpacaClient(new FakeHttp().Client(), new FastClock(_now), _keys, sockets: () => socket); + var many = Enumerable.Range(0, 31).Select(i => "S" + i).ToList(); + await Assert.ThrowsAsync(async () => + { + await foreach (var unused in alpaca.StreamAsync(many, CancellationToken.None).ConfigureAwait(false)) + { + _ = unused; + } + }).ConfigureAwait(false); + + socket.Push("""[{"T":"success","msg":"connected"}]"""); + socket.Push("""[{"T":"success","msg":"authenticated"}]"""); + socket.Push("""[{"T":"subscription","trades":[],"quotes":["FAKEPACA"],"bars":["FAKEPACA"]}]"""); + socket.Push("""[{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:53.639713735Z"},{"T":"b","S":"FAKEPACA","o":133.8,"h":134.1,"l":133.7,"c":134.0,"v":1200,"t":"2024-07-24T07:56:00Z","n":12,"vw":133.9}]"""); + socket.Close(); + var events = new List(); + await foreach (var item in alpaca.StreamAsync(["FAKEPACA"], CancellationToken.None).ConfigureAwait(false)) + { + events.Add(item); + } + + Assert.AreEqual(new Uri("wss://stream.data.alpaca.markets/v2/iex"), socket.Url); + StringAssert.Contains(socket.Sent[0], "\"action\":\"auth\""); + StringAssert.Contains(socket.Sent[1], "\"bars\":[\"FAKEPACA\"]"); + Assert.AreEqual(133.85m, events.OfType().Single().Quote.Bid); + Assert.AreEqual(134.0, events.OfType().Single().Bar.Close); + + var error = Assert.Throws(() => AlpacaClient.ParseStreamMessage("""[{"T":"error","code":405,"msg":"symbol limit exceeded"}]""")); + StringAssert.Contains(error.Message, "405"); + } +} diff --git a/tests/Anubis.Tests/Anubis.Tests.csproj b/tests/Anubis.Tests/Anubis.Tests.csproj index 891b2d4..058578d 100644 --- a/tests/Anubis.Tests/Anubis.Tests.csproj +++ b/tests/Anubis.Tests/Anubis.Tests.csproj @@ -9,6 +9,9 @@ + + + diff --git a/tests/Anubis.Tests/CollectorTests.cs b/tests/Anubis.Tests/CollectorTests.cs new file mode 100644 index 0000000..622b07f --- /dev/null +++ b/tests/Anubis.Tests/CollectorTests.cs @@ -0,0 +1,309 @@ +using System.Threading.Channels; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// The collector of issue #20: backfill, checks, second readings, live feed, drops and gap recovery. +[TestClass] +public sealed class CollectorTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task FeedDetachedForTenMinutesIsRecoveredOnReconnection() + { + var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 10, 0, 30, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var bus = new EventBus(); + using var feed = bus.Subscribe(); + var freshness = new FreshnessMonitor(clock, bus); + var btc = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None).ConfigureAwait(false); + var source = new FakeMarketSource(clock); + var quiet = new DateTimeOffset(2026, 11, 10, 9, 30, 0, TimeSpan.Zero); + source.NoTrades.Add(quiet); + var collector = new MarketCollector(source, test.Db, clock, bus, freshness); + var bars = new BarStore(test.Db, clock); + var issues = new DataIssueStore(test.Db, clock); + + using var stop = new CancellationTokenSource(); + var live = collector.RunLiveAsync([btc], stop.Token); + await OkxTests.WaitForAsync(() => source.Connections == 1).ConfigureAwait(false); + + // Startup: two days of minutes downloaded; the minute without trades is recorded, not invented. + var start = clock.UtcNow; + Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 9, 59, 0, TimeSpan.Zero), await bars.LastMinuteAsync(btc.Id, CancellationToken.None).ConfigureAwait(false)); + var startup = await bars.MinuteAsync(btc.Id, start.AddDays(-3), start, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(2 * 24 * 60 - 1, startup.Count); + var unrecoverable = (await issues.SinceAsync(start.AddDays(-1), CancellationToken.None).ConfigureAwait(false)).Single(); + Assert.AreEqual((IssueKinds.Gap, IssueStatus.Unrecoverable, quiet), (unrecoverable.Kind, unrecoverable.Status, unrecoverable.StartsAt)); + StringAssert.Contains(unrecoverable.Detail, "senza scambi"); + + // Live: a closed bar arrives and the instrument is fresh. + clock.Advance(TimeSpan.FromSeconds(31)); + await source.Live!.Writer.WriteAsync(new BarEvent("BTC-EUR", FakeMarketSource.MinuteBar(new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero)), true)) + .ConfigureAwait(false); + await OkxTests.WaitForAsync(() => freshness.IsFresh(btc.Id)).ConfigureAwait(false); + Assert.IsTrue(collector.Connected); + + // The network goes down for ten minutes: the feed drops and nothing answers, not even the REST calls. + var dropAt = clock.UtcNow; + source.DownUntil = dropAt.AddMinutes(10); + source.Live.Writer.Complete(); + await OkxTests.WaitForAsync(() => source.Connections == 2).ConfigureAwait(false); + Assert.IsTrue(clock.UtcNow >= dropAt.AddMinutes(10), "reconnected only after the outage"); + Assert.IsFalse(freshness.IsFresh(btc.Id), "no live datum since the drop: no new entries"); + + // Back: every minute missed is downloaded before the feed resumes. + var resumed = new DateTimeOffset(clock.UtcNow.UtcTicks - (clock.UtcNow.UtcTicks % TimeSpan.TicksPerMinute), TimeSpan.Zero); + var recovered = await bars.MinuteAsync(btc.Id, new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero), resumed, CancellationToken.None).ConfigureAwait(false); + Assert.IsTrue(recovered.Count >= 11, $"at least the ten minutes of the outage, got {recovered.Count}"); + CollectionAssert.AreEqual( + QualityChecks.EveryMinute(new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero), resumed).ToList(), + recovered.Select(b => b.OpensAt).ToList(), "no minute is missing"); + Assert.AreEqual(1, (await issues.SinceAsync(start.AddDays(-1), CancellationToken.None).ConfigureAwait(false)).Count, "no new issue"); + + await source.Live!.Writer.WriteAsync(new TradeEvent("BTC-EUR", clock.UtcNow, 50_010m, 0.01m)).ConfigureAwait(false); + await OkxTests.WaitForAsync(() => freshness.IsFresh(btc.Id)).ConfigureAwait(false); + + await stop.CancelAsync().ConfigureAwait(false); + await live.ConfigureAwait(false); + var changes = new List(); + while (feed.TryRead(out var change)) + { + changes.Add(change!.Connected); + } + + CollectionAssert.AreEqual(new[] { true, false, true, false }, changes); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task SuspectBarsAreReadAgainAndNeverFixedInSilence() + { + var day0 = new DateOnly(2026, 6, 1); + var clock = new FastClock(new DateTimeOffset(day0.AddDays(120).ToDateTime(new TimeOnly(6, 0)), TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var bus = new EventBus(); + var btc = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None).ConfigureAwait(false); + var walk = MarketDataLogicTests.Walk(120, day0); + var source = new FakeMarketSource(clock); + foreach (var bar in walk) + { + source.Days[bar.Day] = bar; + } + + var spike = day0.AddDays(80); + var broken = day0.AddDays(90); + var lost = day0.AddDays(50); + source.FirstReadings[spike] = new Queue([walk[80] with { High = walk[80].High * 3, Close = walk[80].Close * 3 }]); + source.Days[broken] = walk[90] with { Low = -1 }; + source.MissingOnFirstRead.Add(lost); + + var collector = new MarketCollector(source, test.Db, clock, bus, new FreshnessMonitor(clock, bus)); + var result = await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false); + + var bars = new BarStore(test.Db, clock); + var stored = await bars.DailyAsync(btc.Id, day0, day0.AddDays(200), CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(119, stored.Count, "the impossible day is dropped, the lost one recovered"); + Assert.AreEqual(walk[80].Close, stored.Single(b => b.Day == spike).Close, "the second reading replaced the spike"); + Assert.IsFalse(stored.Any(b => b.Day == broken)); + Assert.IsTrue(stored.Any(b => b.Day == lost)); + + var issues = await new DataIssueStore(test.Db, clock).SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).ConfigureAwait(false); + var byDay = issues.ToLookup(i => DateOnly.FromDateTime(i.StartsAt.UtcDateTime)); + Assert.AreEqual(IssueStatus.Corrected, byDay[spike].Single(i => i.Kind == IssueKinds.Jump).Status); + StringAssert.Contains(byDay[spike].Single(i => i.Kind == IssueKinds.Jump).Detail, "invece di"); + Assert.AreEqual(IssueStatus.Unrecoverable, byDay[broken].Single(i => i.Kind == IssueKinds.NonPositive).Status); + Assert.AreEqual(IssueStatus.Recovered, byDay[lost].Single(i => i.Kind == IssueKinds.Gap).Status); + Assert.IsTrue(issues.All(i => i.Attempts == 1), "each problem was tried once more"); + Assert.AreEqual(0, (await new DataIssueStore(test.Db, clock).BlockedInstrumentsAsync(CancellationToken.None).ConfigureAwait(false)).Count, + "once read again, nothing blocks new entries"); + Assert.IsTrue(result.Suspect >= 2 && result.Corrected >= 1 && result.Unrecoverable == 1 && result.Recovered == 1, result.ToString()); + + // A suspect bar the second reading confirms stays, marked as confirmed. + source.Days[day0.AddDays(120)] = walk[^1] with { Day = day0.AddDays(120), Open = walk[^1].Close, Low = walk[^1].Close * 0.5, Close = walk[^1].Close * 0.5 }; + clock.Advance(TimeSpan.FromDays(1)); + var next = await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(1, next.Confirmed); + Assert.AreEqual(BarQuality.Confirmed, (await bars.DailyAsync(btc.Id, day0.AddDays(120), day0.AddDays(120), CancellationToken.None).ConfigureAwait(false))[0].Quality); + Assert.AreEqual(CollectionResult.None, await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false), "nothing new"); + + // The first day after the stored history is missing on the first read: the hole between what is held and + // what arrived is a gap like any other, read again and recovered. + var basis = source.Days[day0.AddDays(120)]; + foreach (var day in new[] { day0.AddDays(121), day0.AddDays(122) }) + { + source.Days[day] = basis with { Day = day, Open = basis.Close, High = basis.Close * 1.002, Low = basis.Close * 0.998, Quality = BarQuality.Ok }; + } + + source.MissingOnFirstRead.Add(day0.AddDays(121)); + clock.Advance(TimeSpan.FromDays(2)); + var after = await collector.BackfillDailyAsync(btc, day0, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual((1, 1), (after.Gaps, after.Recovered), after.ToString()); + Assert.AreEqual(3, (await bars.DailyAsync(btc.Id, day0.AddDays(120), day0.AddDays(122), CancellationToken.None).ConfigureAwait(false)).Count); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task LiveMinuteSkippedByTheFeedIsDownloadedAgain() + { + var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 10, 0, 30, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var bus = new EventBus(); + var btc = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None).ConfigureAwait(false); + var source = new FakeMarketSource(clock); + var collector = new MarketCollector(source, test.Db, clock, bus, new FreshnessMonitor(clock, bus)); + var bars = new BarStore(test.Db, clock); + var issues = new DataIssueStore(test.Db, clock); + + using var stop = new CancellationTokenSource(); + var live = collector.RunLiveAsync([btc], stop.Token); + await OkxTests.WaitForAsync(() => source.Connections == 1).ConfigureAwait(false); + Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 9, 59, 0, TimeSpan.Zero), await bars.LastMinuteAsync(btc.Id, CancellationToken.None).ConfigureAwait(false)); + + // The stream was subscribed too late for the 10:00 candle and sends 10:01 first. + var skipped = new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero); + clock.Advance(TimeSpan.FromMinutes(2)); + await source.Live!.Writer.WriteAsync(new BarEvent("BTC-EUR", FakeMarketSource.MinuteBar(skipped.AddMinutes(1)), true)).ConfigureAwait(false); + // The minute is stored first and the issue closed right after: wait for the issue's final state. + await OkxTests.WaitForAsync(() => issues.SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).GetAwaiter().GetResult() + .Any(i => i.Status != IssueStatus.Open)).ConfigureAwait(false); + + var gap = (await issues.SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).ConfigureAwait(false)).Single(); + Assert.AreEqual((IssueKinds.Gap, IssueStatus.Recovered, skipped), (gap.Kind, gap.Status, gap.StartsAt)); + Assert.AreEqual(2, (await bars.MinuteAsync(btc.Id, skipped, skipped.AddMinutes(2), CancellationToken.None).ConfigureAwait(false)).Count); + await stop.CancelAsync().ConfigureAwait(false); + await live.ConfigureAwait(false); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ASplitAfterTheHistoryRebasesTheStoredAdjustedPrices() + { + var day0 = new DateOnly(2026, 6, 1); + var clock = new FastClock(new DateTimeOffset(day0.AddDays(100).ToDateTime(new TimeOnly(6, 0)), TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var bus = new EventBus(); + var stock = await new InstrumentCatalog(test.Db, clock).EnsureAsync(MarketDataStoreTests.Okx("ACME-EUR"), CancellationToken.None).ConfigureAwait(false); + static DailyBar Adjusted(DailyBar bar, double factor) => + bar with { Adjusted = new Ohlc(bar.Open * factor, bar.High * factor, bar.Low * factor, bar.Close * factor) }; + + var walk = MarketDataLogicTests.Walk(100, day0); + var source = new FakeMarketSource(clock); + foreach (var bar in walk) + { + source.Days[bar.Day] = Adjusted(bar, 1); + } + + var collector = new MarketCollector(source, test.Db, clock, bus, new FreshnessMonitor(clock, bus)); + Assert.AreEqual(100, (await collector.BackfillDailyAsync(stock, day0, CancellationToken.None).ConfigureAwait(false)).Stored); + + // A 2-for-1 split on day 100: the source now gives every older adjusted price halved, and the real price halves. + foreach (var bar in walk) + { + source.Days[bar.Day] = Adjusted(bar, 0.5); + } + + var close = walk[^1].Close / 2; + source.Days[day0.AddDays(100)] = Adjusted(new DailyBar(day0.AddDays(100), close, close * 1.003, close * 0.997, close * 1.001, 2000), 1); + clock.Advance(TimeSpan.FromDays(1)); + var result = await collector.BackfillDailyAsync(stock, day0, CancellationToken.None).ConfigureAwait(false); + + Assert.AreEqual((1, 0), (result.Stored, result.Suspect), "the split is not a jump"); + var stored = await new BarStore(test.Db, clock).DailyAsync(stock.Id, day0, day0.AddDays(100), CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(walk[50].Close, stored[50].Close, 1e-9, "real prices stay as they were"); + Assert.AreEqual(walk[50].Close / 2, stored[50].Adjusted!.Value.Close, 1e-9, "older adjusted prices are on the new basis"); + Assert.IsEmpty(await new DataIssueStore(test.Db, clock).SinceAsync(DateTimeOffset.MinValue, CancellationToken.None).ConfigureAwait(false)); + } +} + +/// +/// A venue for the collector tests: minute bars exist for every past minute except , daily +/// bars come from , and the whole venue can be down until . +/// +internal sealed class FakeMarketSource(IClock clock) : IMarketDataSource +{ + public string Venue => Venues.Okx; + + public HashSet NoTrades { get; } = []; + + public Dictionary Days { get; } = []; + + /// What the first reading of a day returns instead of . + public Dictionary> FirstReadings { get; } = []; + + public HashSet MissingOnFirstRead { get; } = []; + + public DateTimeOffset? DownUntil { get; set; } + + public Channel? Live { get; private set; } + + public int Connections; + + public static Bar MinuteBar(DateTimeOffset t) + { + var price = 50_000 + (20 * Math.Sin(t.ToUnixTimeSeconds() / 60.0 / 15)); + return new Bar(t, price, price + 5, price - 5, price + 1, 0.5); + } + + public Task> ListInstrumentsAsync(CancellationToken cancellationToken) => + Task.FromResult>([MarketDataStoreTests.Okx("BTC-EUR")]); + + public Task> FetchDailyBarsAsync(string symbol, DateOnly first, DateOnly last, CancellationToken cancellationToken) + { + ThrowIfDown(); + var list = new List(); + for (var day = first; day <= last; day = day.AddDays(1)) + { + if (FirstReadings.TryGetValue(day, out var queue) && queue.Count > 0) + { + list.Add(queue.Dequeue()); + } + else if (!MissingOnFirstRead.Remove(day) && Days.TryGetValue(day, out var bar)) + { + list.Add(bar); + } + } + + return Task.FromResult>(list); + } + + public Task> FetchMinuteBarsAsync(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken cancellationToken) + { + ThrowIfDown(); + var now = clock.UtcNow; + var list = new List(); + for (var t = start; t < until && t.AddMinutes(1) <= now; t = t.AddMinutes(1)) + { + if (!NoTrades.Contains(t)) + { + list.Add(MinuteBar(t)); + } + } + + return Task.FromResult>(list); + } + + public Task FetchQuoteAsync(string symbol, CancellationToken cancellationToken) => + Task.FromResult(new Quote(symbol, 49_999m, 50_001m, clock.UtcNow)); + + public async IAsyncEnumerable StreamAsync(IReadOnlyCollection symbols, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + ThrowIfDown(); + Live = Channel.CreateUnbounded(); + Interlocked.Increment(ref Connections); + await foreach (var item in Live.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + yield return item; + } + } + + private void ThrowIfDown() + { + if (DownUntil is { } until && clock.UtcNow < until) + { + throw new MarketDataException("rete assente", retryable: true); + } + } +} diff --git a/tests/Anubis.Tests/FakeNetwork.cs b/tests/Anubis.Tests/FakeNetwork.cs new file mode 100644 index 0000000..310fb56 --- /dev/null +++ b/tests/Anubis.Tests/FakeNetwork.cs @@ -0,0 +1,154 @@ +using System.Net; +using System.Text; +using System.Threading.Channels; +using Anubis.Brokers; + +namespace Anubis.Tests; + +/// Recorded responses saved under Fixtures/ (trap 12: no network in tests). +internal static class Fixture +{ + public static string Path(string relative) => System.IO.Path.Combine(AppContext.BaseDirectory, "Fixtures", relative); + + public static string Text(string relative) => File.ReadAllText(Path(relative)); + + public static byte[] Bytes(string relative) => File.ReadAllBytes(Path(relative)); +} + +/// +/// An HTTP handler that answers from a list of rules (first match wins) and records every request. +/// A request no rule matches fails the test with its address. +/// +internal sealed class FakeHttp : HttpMessageHandler +{ + private readonly List<(Func Match, Func Answer)> _rules = []; + + public List Requests { get; } = []; + + public HttpClient Client() => new(this, disposeHandler: false); + + public FakeHttp On(Func match, Func answer) + { + _rules.Add((match, answer)); + return this; + } + + public FakeHttp On(string contains, string body, HttpStatusCode status = HttpStatusCode.OK) => + On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => Respond(body, status)); + + public FakeHttp OnBytes(string contains, byte[] body) => + On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) }); + + public static HttpResponseMessage Respond(string body, HttpStatusCode status = HttpStatusCode.OK) => + new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + + public IEnumerable Urls => Requests.Select(r => r.RequestUri!); + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + lock (Requests) + { + Requests.Add(request); + } + + foreach (var (match, answer) in _rules) + { + if (match(request.RequestUri!)) + { + return Task.FromResult(answer(request)); + } + } + + throw new AssertFailedException("Unexpected request: " + request.RequestUri); + } +} + +/// A WebSocket that plays messages pushed by the test and records what the client sends. +internal sealed class FakeSocket : IWebSocketTransport +{ + private readonly Channel _incoming = Channel.CreateUnbounded(); + + public Uri? Url { get; private set; } + + public IReadOnlyDictionary? Headers { get; private set; } + + public List Sent { get; } = []; + + public TaskCompletionSource Connected { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool Disposed { get; private set; } + + public void Push(string message) => _incoming.Writer.TryWrite(message); + + /// The server closes the connection. + public void Close() => _incoming.Writer.TryWrite(null); + + public Task ConnectAsync(Uri url, IReadOnlyDictionary? headers, CancellationToken cancellationToken) + { + Url = url; + Headers = headers; + Connected.TrySetResult(); + return Task.CompletedTask; + } + + public Task SendAsync(string text, CancellationToken cancellationToken) + { + lock (Sent) + { + Sent.Add(text); + } + + return Task.CompletedTask; + } + + public async Task ReceiveAsync(CancellationToken cancellationToken) => + await _incoming.Reader.ReadAsync(cancellationToken).ConfigureAwait(false); + + public ValueTask DisposeAsync() + { + Disposed = true; + return ValueTask.CompletedTask; + } +} + +/// A clock whose waits finish at once by moving time forward: back-offs and rate limits cost nothing in tests. +internal sealed class FastClock(DateTimeOffset start) : Anubis.Core.IClock +{ + private readonly Lock _gate = new(); + private DateTimeOffset _now = start; + + public DateTimeOffset UtcNow + { + get + { + lock (_gate) + { + return _now; + } + } + } + + public TimeSpan Waited { get; private set; } + + public void Advance(TimeSpan by) + { + lock (_gate) + { + _now += by; + } + } + + public Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken) + { + lock (_gate) + { + if (dueUtc > _now) + { + Waited += dueUtc - _now; + _now = dueUtc; + } + } + + return Task.CompletedTask; + } +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/assets-single-cgrnq.faq.jsonc b/tests/Anubis.Tests/Fixtures/alpaca/assets-single-cgrnq.faq.jsonc new file mode 100644 index 0000000..878c01d --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/assets-single-cgrnq.faq.jsonc @@ -0,0 +1,15 @@ +{ + "id": "dc2d8be9-33b5-4a32-8f57-5b7d209d2c82", + "class": "us_equity", + "exchange": "OTC", // << This symbol is traded in OTC + "symbol": "CGRNQ", + "name": "CAPSTONE GREEN ENERGY CORP COM PAR $.001", + "status": "active", + "tradable": false, + "marginable": false, + "maintenance_margin_requirement": 100, + "shortable": true, + "easy_to_borrow": true, + "fractionable": true, + "attributes": [] +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/assets.json b/tests/Anubis.Tests/Fixtures/alpaca/assets.json new file mode 100644 index 0000000..759b759 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/assets.json @@ -0,0 +1,14 @@ +{ + "borrow_status": "easy_to_borrow", + "class": "us_equity", + "easy_to_borrow": true, + "exchange": "NASDAQ", + "fractionable": true, + "id": "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415", + "marginable": true, + "name": "Apple Inc. Common Stock", + "shortable": true, + "status": "active", + "symbol": "AAPL", + "tradable": true +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/clock-v2.json b/tests/Anubis.Tests/Fixtures/alpaca/clock-v2.json new file mode 100644 index 0000000..f0c200f --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/clock-v2.json @@ -0,0 +1,6 @@ +{ + "is_open": true, + "next_close": "2025-06-24T16:00:00-04:00", + "next_open": "2025-06-25T09:30:00-04:00", + "timestamp": "2025-06-24T14:15:22-04:00" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/corporate-actions.json b/tests/Anubis.Tests/Fixtures/alpaca/corporate-actions.json new file mode 100644 index 0000000..9a07251 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/corporate-actions.json @@ -0,0 +1,183 @@ +{ + "capital_gains_distribution": [ + { + "currency": "USD", + "cusip": "36261K509", + "ex_date": "2025-12-26", + "id": "98c905a1-08c7-450c-8669-b8e7aee8b44d", + "isin": "US36261K5090", + "long_term_rate": 0.45855, + "payable_date": "2026-01-09", + "process_date": "2026-01-08", + "record_date": "2025-12-29", + "short_term_rate": 0.11019, + "symbol": "GCAD" + } + ], + "cash_dividend": [ + { + "cusip": "319829107", + "ex_date": "2023-05-04", + "foreign": false, + "id": "11cfd108-292e-4cc6-bfbf-5999cdbc4029", + "payable_date": "2023-05-19", + "process_date": "2023-05-19", + "rate": 0.125, + "record_date": "2023-05-05", + "special": false, + "symbol": "FCF" + } + ], + "cash_merger": [ + { + "acquiree_cusip": "Y2687W108", + "acquiree_symbol": "GLOP", + "effective_date": "2023-07-17", + "id": "3772bbd7-4ad5-44d4-9cc0-f69156a2f8f5", + "payable_date": "2023-07-17", + "process_date": "2023-07-17", + "rate": 5.37 + } + ], + "forward_split": [ + { + "cusip": "816851109", + "due_bill_redemption_date": "2023-08-23", + "ex_date": "2023-08-22", + "id": "189bd849-ab9f-4b4d-aaaa-a6d415fd976d", + "new_rate": 2, + "old_rate": 1, + "payable_date": "2023-08-21", + "process_date": "2023-08-22", + "record_date": "2023-08-14", + "symbol": "SRE" + } + ], + "name_change": [ + { + "id": "5a774c35-edec-4532-a812-a56d0bbb623a", + "new_cusip": "Y9390M103", + "new_symbol": "VFS", + "old_cusip": "G11537100", + "old_symbol": "BSAQ", + "process_date": "2023-08-15" + } + ], + "redemption": [ + { + "cusip": "687305102", + "id": "395da031-0e57-4918-a6fb-64a7c713aca4", + "payable_date": "2023-06-13", + "process_date": "2023-06-13", + "rate": 0.141134, + "symbol": "ORPHY" + } + ], + "reverse_split": [ + { + "ex_date": "2023-08-24", + "id": "913de862-c02c-46dc-a89c-fc8779a50d30", + "new_cusip": "60879E200", + "new_rate": 1, + "old_cusip": "60879E101", + "old_rate": 50, + "process_date": "2023-08-24", + "record_date": "2023-08-24", + "symbol": "MNTS" + } + ], + "rights_distribution": [ + { + "ex_date": "2024-04-17", + "expiration_date": "2024-05-14", + "id": "69794cfd-0adc-4e11-9211-9210a9cf8932", + "new_cusip": "454089111", + "new_symbol": "IFN.RTWI", + "payable_date": "2024-04-19", + "process_date": "2024-04-19", + "rate": 1, + "record_date": "2024-04-18", + "source_cusip": "454089103", + "source_symbol": "IFN" + } + ], + "spin_off": [ + { + "ex_date": "2023-08-15", + "id": "82e602f6-35bc-4651-a5dd-f6d88ff37c55", + "new_cusip": "85237B101", + "new_rate": 1, + "new_symbol": "SRM", + "process_date": "2023-08-15", + "record_date": "2023-08-15", + "source_cusip": "48208F105", + "source_rate": 19.35, + "source_symbol": "JUPW" + } + ], + "stock_and_cash_merger": [ + { + "acquiree_cusip": "561409103", + "acquiree_rate": 1, + "acquiree_symbol": "MLVF", + "acquirer_cusip": "31931U102", + "acquirer_rate": 0.7733, + "acquirer_symbol": "FRBA", + "cash_rate": 7.8, + "effective_date": "2023-07-18", + "id": "e5248356-2c06-42cf-aeb9-1595bd616cdb", + "payable_date": "2023-07-18", + "process_date": "2023-07-18" + } + ], + "stock_dividend": [ + { + "cusip": "605015106", + "ex_date": "2023-05-19", + "id": "3ae94c30-2d37-473a-bf29-5f7b4ab6d3ca", + "payable_date": "2023-05-05", + "process_date": "2023-05-19", + "rate": 0.05, + "record_date": "2023-05-22", + "symbol": "MSBC" + } + ], + "stock_merger": [ + { + "acquiree_cusip": "53223X107", + "acquiree_rate": 1, + "acquiree_symbol": "LSI", + "acquirer_cusip": "30225T102", + "acquirer_rate": 0.895, + "acquirer_symbol": "EXR", + "effective_date": "2023-07-20", + "id": "728f8cb2-a00e-4bc7-ad14-d15fe82bbcff", + "payable_date": "2023-07-20", + "process_date": "2023-07-20" + } + ], + "unit_split": [ + { + "alternate_cusip": "G5391L110", + "alternate_rate": 0.3333, + "alternate_symbol": "LVROW", + "effective_date": "2023-03-01", + "id": "3e68e87e-ae95-4d68-91d1-715d52ef143a", + "new_cusip": "G5391L102", + "new_rate": 1, + "new_symbol": "LVRO", + "old_cusip": "G8990L119", + "old_rate": 1, + "old_symbol": "TPBAU", + "process_date": "2023-03-01" + } + ], + "worthless_removal": [ + { + "cusip": "078771300", + "id": "106c2149-ee04-4d2e-a943-98dbb4d21a3c", + "process_date": "2024-12-19", + "symbol": "BLPH" + } + ] +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/error-sip-recent.faq.json b/tests/Anubis.Tests/Fixtures/alpaca/error-sip-recent.faq.json new file mode 100644 index 0000000..54aff8b --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/error-sip-recent.faq.json @@ -0,0 +1 @@ +{"code":42210000,"message":"subscription does not permit querying recent SIP data"} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/errors.md b/tests/Anubis.Tests/Fixtures/alpaca/errors.md new file mode 100644 index 0000000..89aac96 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/errors.md @@ -0,0 +1,78 @@ +# Alpaca REST errors and rate limiting: what the docs actually show + +Read 2026-11-10. Verbatim where quoted; "NOT DOCUMENTED" where the docs show nothing. + +## Market Data API (https://data.alpaca.markets) + +Source: OpenAPI blocks on https://docs.alpaca.markets/us/reference/stockbars (and every other +stock reference page, e.g. stocklatestquotes-1, stocksnapshots-1, corporateactions-1). + +Documented status codes, descriptions only (the OpenAPI declares NO response body schema +for any error): + +- 400: "One of the request parameters is invalid. See the returned message for details." + (carries the X-RateLimit-* headers) +- 401: "Authentication headers are missing or invalid. Make sure you authenticate your + request with a valid API key." +- 403: "The requested resource is forbidden." +- 429: "Too many requests. You hit the rate limit. Use the X-RateLimit-... response headers to + make sure you're under the rate limit." (carries the X-RateLimit-* headers) +- 500: "Internal server error. We recommend retrying these later. ..." +- 422: not listed on the market data reference pages. + +Rate-limit headers (declared on 200, 400 and 429): + +| Header | Doc description | Doc example | +|---|---|---| +| `X-RateLimit-Limit` | "Request limit per minute." | 100 | +| `X-RateLimit-Remaining` | "Request limit per minute remaining." | 90 | +| `X-RateLimit-Reset` | "The UNIX epoch when the remaining quota changes." | 1674044551 | + +Basic plan: "Historical API calls 200 / min" (https://docs.alpaca.markets/us/docs/about-market-data-api). + +Market Data FAQ (https://docs.alpaca.markets/us/docs/market-data-faq), "Why am I getting HTTP 403": +403 is returned if the request was not authenticated, the credentials were incorrect, or the user +has insufficient permissions. (So in practice bad keys may yield 403, while the OpenAPI says 401; +the docs do not reconcile the two.) + +The ONLY error body shown anywhere for market data (FAQ, latest trade with feed=sip on the free +plan; HTTP status NOT shown): + +``` +$ curl -H "APCA-API-KEY-ID: ${APCA_API_KEY_ID}" -H "APCA-API-SECRET-KEY: ${APCA_API_SECRET_KEY}" \ + "https://data.alpaca.markets/v2/stocks/AAPL/trades/latest?feed=sip" +{"code":42210000,"message":"subscription does not permit querying recent SIP data"} +``` + +Saved as `error-sip-recent.faq.json`. Shape: `{"code": , "message": }`. + +Adjustment parameter (stockbars): unknown values, empty values and repeated keys such as +`?adjustment=split&adjustment=all` "are rejected with a `400`". Body NOT DOCUMENTED. + +## Trading API (https://paper-api.alpaca.markets) + +- /v2/assets, /v2/calendar, /v2/clock, /v3/calendar, /v3/clock reference pages + (get-v2-assets-1, legacycalendar, legacyclock, calendar-2, clock-1): calendars list + 400 / 429 / 500, /v2/clock lists 429 / 500, all with the same X-RateLimit-* headers on 200; + /v2/assets lists only 200. No error bodies. +- /v2/assets/{symbol_or_asset_id}: 404 when not found (no body documented). +- POST /v2/orders (postorder): 403 "Forbidden\n\nBuying power or shares is not sufficient.", + 422 "Unprocessable\n\nInput parameters are not recognized." No bodies. +- Getting Started with Trading API (https://docs.alpaca.markets/us/docs/getting-started-with-trading-api): + every response carries `X-Request-ID`; the example is an unauthenticated + `GET /v2/account` -> `HTTP/1.1 403 Forbidden`, `Content-Type: application/json`, + `Content-Length: 26`. The body itself is elided ("...") in the docs: NOT DOCUMENTED. +- Trading API rate limit number: NOT DOCUMENTED on the current pages. + +## 429 behaviour + +Only the Broker API page documents behaviour explicitly +(https://docs.alpaca.markets/us/docs/broker-api-rate-limits): headers on every response, not +only 429; on 429 "stop, wait, and retry using exponential backoff", ideally not before +`X-RateLimit-Reset`. For the Trading/Market Data APIs the docs only say "Use the X-RateLimit-... +response headers". No Retry-After header is documented anywhere. + +## Bodies for 401 / 403 / 422 / 429 + +NOT DOCUMENTED (no example body exists in the docs). The only observed shape is the FAQ's +`{"code":42210000,"message":"..."}`. Treat other shapes as unknown and parse defensively. diff --git a/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest-single.json b/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest-single.json new file mode 100644 index 0000000..8fe7d04 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest-single.json @@ -0,0 +1,16 @@ +{ + "quote": { + "ap": 172.7, + "as": 1, + "ax": "Q", + "bp": 172.6, + "bs": 2, + "bx": "Q", + "c": [ + "R" + ], + "t": "2022-08-17T10:09:34.055031265Z", + "z": "C" + }, + "symbol": "AAPL" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest.json b/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest.json new file mode 100644 index 0000000..9911b9b --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/quotes-latest.json @@ -0,0 +1,30 @@ +{ + "quotes": { + "AAPL": { + "ap": 172.7, + "as": 1, + "ax": "Q", + "bp": 172.62, + "bs": 2, + "bx": "Q", + "c": [ + "R" + ], + "t": "2022-08-17T10:07:40.286587431Z", + "z": "C" + }, + "TSLA": { + "ap": 911.6, + "as": 1, + "ax": "Q", + "bp": 911.3, + "bs": 1, + "bx": "K", + "c": [ + "R" + ], + "t": "2022-08-17T10:07:49.387064037Z", + "z": "C" + } + } +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/snapshots.json b/tests/Anubis.Tests/Fixtures/alpaca/snapshots.json new file mode 100644 index 0000000..aa68d9f --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/snapshots.json @@ -0,0 +1,116 @@ +{ + "AAPL": { + "dailyBar": { + "c": 173.03, + "h": 173.71, + "l": 171.6618, + "n": 515139, + "o": 172.62, + "t": "2022-08-16T04:00:00Z", + "v": 56457696, + "vw": 172.743391 + }, + "latestQuote": { + "ap": 172.7, + "as": 5, + "ax": "Q", + "bp": 172.6, + "bs": 2, + "bx": "Q", + "c": [ + "R" + ], + "t": "2022-08-17T10:18:27.052763263Z", + "z": "C" + }, + "latestTrade": { + "c": [ + "@", + "T" + ], + "i": 1011, + "p": 172.61, + "s": 160, + "t": "2022-08-17T10:18:24.114694956Z", + "x": "Q", + "z": "C" + }, + "minuteBar": { + "c": 172.69, + "h": 172.69, + "l": 172.69, + "n": 3, + "o": 172.69, + "t": "2022-08-17T10:16:00Z", + "v": 106, + "vw": 172.688113 + }, + "prevDailyBar": { + "c": 173.19, + "h": 173.39, + "l": 171.345, + "n": 501626, + "o": 171.5, + "t": "2022-08-15T04:00:00Z", + "v": 54091719, + "vw": 172.625371 + } + }, + "TSLA": { + "dailyBar": { + "c": 919.69, + "h": 944, + "l": 908.65, + "n": 805572, + "o": 935, + "t": "2022-08-16T04:00:00Z", + "v": 29378774, + "vw": 925.215087 + }, + "latestQuote": { + "ap": 911.75, + "as": 4, + "ax": "P", + "bp": 911.31, + "bs": 1, + "bx": "Q", + "c": [ + "R" + ], + "t": "2022-08-17T10:18:23.84717767Z", + "z": "C" + }, + "latestTrade": { + "c": [ + "@", + "T" + ], + "i": 2047, + "p": 911.99, + "s": 100, + "t": "2022-08-17T10:13:12.952851456Z", + "x": "P", + "z": "C" + }, + "minuteBar": { + "c": 911.99, + "h": 911.99, + "l": 911.99, + "n": 64, + "o": 911.99, + "t": "2022-08-17T10:13:00Z", + "v": 740, + "vw": 911.780405 + }, + "prevDailyBar": { + "c": 927.96, + "h": 939.4, + "l": 903.69, + "n": 825109, + "o": 905.32, + "t": "2022-08-15T04:00:00Z", + "v": 29786389, + "vw": 923.982755 + } + } +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-iex.faq.json b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-iex.faq.json new file mode 100644 index 0000000..3911fe2 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-iex.faq.json @@ -0,0 +1,16 @@ +{ + "bars": [ + { + "t": "2023-09-29T04:00:00Z", + "o": 172.015, + "h": 173.06, + "l": 170.36, + "c": 171.29, + "v": 923134, + "n": 12630, + "vw": 171.716432 + } + ], + "symbol": "AAPL", + "next_page_token": null +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-sip.faq.json b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-sip.faq.json new file mode 100644 index 0000000..dd68a02 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single-1day-sip.faq.json @@ -0,0 +1,16 @@ +{ + "bars": [ + { + "t": "2023-09-29T04:00:00Z", + "o": 172.02, + "h": 173.07, + "l": 170.341, + "c": 171.21, + "v": 51861083, + "n": 535134, + "vw": 171.599691 + } + ], + "symbol": "AAPL", + "next_page_token": "QUFQTHxEfDIwMjMtMDktMjlUMDQ6MDA6MDAuMDAwMDAwMDAwWg==" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single.json b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single.json new file mode 100644 index 0000000..fdcb6e9 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars-single.json @@ -0,0 +1,16 @@ +{ + "bars": [ + { + "c": 178.21, + "h": 178.26, + "l": 178.21, + "n": 65, + "o": 178.26, + "t": "2022-01-03T09:00:00Z", + "v": 1118, + "vw": 178.235733 + } + ], + "next_page_token": "QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg==", + "symbol": "AAPL" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars.json b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars.json new file mode 100644 index 0000000..3e6cf15 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/stocks-bars.json @@ -0,0 +1,17 @@ +{ + "bars": { + "AAPL": [ + { + "c": 178.21, + "h": 178.26, + "l": 178.21, + "n": 65, + "o": 178.26, + "t": "2022-01-03T09:00:00Z", + "v": 1118, + "vw": 178.235733 + } + ] + }, + "next_page_token": "QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg==" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca/stream-examples.md b/tests/Anubis.Tests/Fixtures/alpaca/stream-examples.md new file mode 100644 index 0000000..e7eb80b --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca/stream-examples.md @@ -0,0 +1,328 @@ +# Alpaca market data stream v2: documented examples + +Copied verbatim from the official docs (read 2026-11-10). Nothing here is invented; +where the docs show no example, it says so. + +Sources: +- G = https://docs.alpaca.markets/us/docs/streaming-market-data (page updatedAt 2026-08-27) +- S = https://docs.alpaca.markets/us/docs/real-time-stock-pricing-data (page updatedAt 2026-05-18) +- P = https://docs.alpaca.markets/us/docs/about-market-data-api (plan table) + +## URLs (S) + + wss://stream.data.alpaca.markets/{version}/{feed} + +- `v2/sip`, `v2/iex`, `v2/delayed_sip`, `v1beta1/boats`, `v1beta1/overnight` +- Sandbox (broker partners): `wss://stream.data.sandbox.alpaca.markets/{version}/{feed}` +- Test stream, always on, symbol `FAKEPACA` (G): `wss://stream.data.alpaca.markets/v2/test` +- "Any attempt to access a data feed not available for your subscription will result in an + error during authentication." (G, S) + +## Connect (G) + +Welcome message: + +```json +[{"T":"success","msg":"connected"}] +``` + +## Authenticate (G) + +Option A, HTTP headers on the opening handshake (Trading API keys): + +```shell +websocat wss://stream.data.alpaca.markets/v2/test \ + -H="APCA-API-KEY-ID: {KEY_ID}" \ + -H="APCA-API-SECRET-KEY: {SECRET_KEY}" +``` + +Option B, message after connecting. "You must authenticate within 10 seconds." + +```json +{"action":"auth","key":"{KEY_ID}","secret":"{SECRET_KEY}"} +``` + +Success reply: + +```json +[{"T":"success","msg":"authenticated"}] +``` + +## Subscribe / unsubscribe (G) + +General form: + +```json +{ + "action": "subscribe", + "": [""], + "": ["",""], + "": ["*"] +} +``` + +Subscriptions are additive; `unsubscribe` subtracts: + +```json +{"action":"subscribe","trades":["FAKEPACA"]} +``` + +```json +{"action":"unsubscribe","quotes":["FAKEPACA"]} +``` + +The reply always lists the WHOLE current subscription set: + +```json +[{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":["VOO"],"statuses":["*"],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}] +``` + +Sample exchange (G): + +``` +> {"action": "subscribe", "trades": ["AAPL"], "quotes": ["AMD", "CLDR"], "bars": ["*"]} +< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}] +... +> {"action": "unsubscribe", "bars": ["*"]} +< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":[],"updatedBars":[],"dailyBars":[],"statuses":[],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}] +``` + +Stock channels (S): `trades`, `quotes`, `bars`, `dailyBars`, `updatedBars`, `statuses`, +`lulds`, `imbalances`. `corrections` and `cancelErrors` are subscribed automatically with +`trades`. (The `imbalances` key does not appear in any documented subscription reply.) + +## Message envelope (G) + +```json +[{"T": "{message_type}", {contents}},...] +``` + +- Control messages (`T` = `error`, `success`, `subscription`) always arrive in arrays of size one. +- Data messages may arrive in arrays longer than one. +- `Content-Type: application/json` or `Content-Type: application/msgpack` switches text/binary frames. +- Compression per RFC 7692 (permessage-deflate). + +## Data messages (S) + +| T | channel | fields | +|-----|----------------|--------| +| `t` | trades | T, S, i, x, p, s, c, t, z | +| `q` | quotes | T, S, ax, ap, as, bx, bp, bs, c, t, z (`as`/`bs` described as "in round lots" on this page) | +| `b` | bars (minute) | T, S, o, h, l, c, v, vw, n, t | +| `d` | dailyBars | same as `b` | +| `u` | updatedBars | same as `b` | +| `c` | corrections | T, S, x, oi, op, os, oc, ci, cp, cs, cc, t, z | +| `x` | cancelErrors | T, S, i, x, p, s, a ("C" cancel, "E" error), t, z | +| `l` | lulds | T, S, u, d, i, t, z | +| `s` | statuses | T, S, sc, sm, rc, rm, t, z | +| `i` | imbalances | T, S, p, z, t | + +Trade (`t`): + +```json +{ + "T": "t", + "i": 96921, + "S": "AAPL", + "x": "D", + "p": 126.55, + "s": 1, + "t": "2021-02-22T15:51:44.208Z", + "c": ["@", "I"], + "z": "C" +} +``` + +Quote (`q`): + +```json +{ + "T": "q", + "S": "AMD", + "bx": "U", + "bp": 87.66, + "bs": 1, + "ax": "Q", + "ap": 87.68, + "as": 4, + "t": "2021-02-22T15:51:45.335689322Z", + "c": ["R"], + "z": "C" +} +``` + +Bar (`b`). The docs show ONLY a `b` example; there is NO documented example of a `d` +(dailyBars) or `u` (updatedBars) message, only the shared schema. + +```json +{ + "T": "b", + "S": "SPY", + "o": 388.985, + "h": 389.13, + "l": 388.975, + "c": 389.12, + "v": 49378, + "n": 461, + "vw": 389.062639, + "t": "2021-02-22T19:15:00Z" +} +``` + +Bar semantics (S): +- `bars`: emitted right after each minute mark, containing the trades of the previous minute; + pre-market and after-hours trades are included. +- `dailyBars`: emitted right after each minute mark after the market opens; contain all trades + until the emission time. +- `updatedBars`: emitted after each half-minute mark if a late trade arrived after the previous + minute mark (e.g. trade 16:49:59.998 arriving after 16:50:00 -> just after 16:50:30 an updated + bar with `t` = 16:49:00). + +Trade correction (`c`): + +```json +{ + "T": "c", + "S": "EEM", + "x": "M", + "oi": 52983525033527, + "op": 39.1582, + "os": 440000, + "oc": [ + " ", + "7" + ], + "ci": 52983525034326, + "cp": 39.1809, + "cs": 440000, + "cc": [ + " ", + "7" + ], + "z": "B", + "t": "2023-04-06T14:25:06.542305024Z" +} +``` + +Trade cancel/error (`x`): + +```json +{ + "T": "x", + "S": "GOOGL", + "i": 465, + "x": "D", + "p": 105.31, + "s": 300, + "a": "C", + "z": "C", + "t": "2023-04-06T13:15:42.83540958Z" +} +``` + +LULD (`l`): + +```json +{ + "T": "l", + "S": "IONM", + "u": 3.24, + "d": 2.65, + "i": "B", + "t": "2023-04-06T13:34:45.565004401Z", + "z": "C" +} +``` + +Trading status (`s`): + +```json +{ + "T": "s", + "S": "AAPL", + "sc": "H", + "sm": "Trading Halt", + "rc": "T12", + "rm": "Trading Halted; For information requested by NASDAQ", + "t": "2021-02-22T19:15:00Z", + "z": "C" +} +``` + +Order imbalance (`i`), subscribe with `{"action":"subscribe","imbalances":["INAQU"]}`: + +```json +{ + "T": "i", + "S": "INAQU", + "p": 9.12, + "z": "C", + "t": "2024-12-13T19:58:09.242138635Z" +} +``` + +## Full sessions as documented + +Test stream (G): + +``` +$ wscat -c wss://stream.data.alpaca.markets/v2/test +Connected (press CTRL+C to quit) +< [{"T":"success","msg":"connected"}] +> {"action":"auth","key":"","secret":""} +< [{"T":"success","msg":"authenticated"}] +> {"action":"subscribe","bars":["FAKEPACA"],"quotes":["FAKEPACA"]} +< [{"T":"subscription","trades":[],"quotes":["FAKEPACA"],"bars":["FAKEPACA"]}] +< [{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:53.639713735Z"}] +< [{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:58.641207127Z"}] +< [{"T":"b","S":"FAKEPACA","o":132.65,"h":136,"l":132.12,"c":134.65,"v":205,"t":"2024-07-24T07:56:00Z","n":16,"vw":133.7}] +``` + +Note: in this test-stream transcript the subscription reply has only `trades`, `quotes`, `bars` +keys, unlike the full reply above. A parser must tolerate missing channel keys. + +SIP stream (S): + +``` +$ wscat -c wss://stream.data.alpaca.markets/v2/sip +connected (press CTRL+C to quit) +< [{"T":"success","msg":"connected"}] +> {"action": "auth", "key": "*****", "secret": "*****"} +< [{"T":"success","msg":"authenticated"}] +> {"action": "subscribe", "trades": ["AAPL"], "quotes": ["AMD", "CLDR"], "bars": ["*"],"dailyBars":["VOO"],"statuses":["*"]} +< [{"T":"subscription","trades":["AAPL"],"quotes":["AMD","CLDR"],"bars":["*"],"updatedBars":[],"dailyBars":["VOO"],"statuses":["*"],"lulds":[],"corrections":["AAPL"],"cancelErrors":["AAPL"]}] +< [{"T":"q","S":"AMD","bx":"K","bp":91.95,"bs":2,"ax":"Q","ap":91.98,"as":1,"c":["R"],"z":"C","t":"2023-04-06T11:54:21.670905508Z"}] +< [{"T":"t","S":"AAPL","i":628,"x":"K","p":162.92,"s":3,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.838232225Z"},{"T":"t","S":"AAPL","i":75,"x":"Z","p":162.92,"s":3,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.838562809Z"},{"T":"t","S":"AAPL","i":1465,"x":"P","p":162.91,"s":71,"c":["@","F","T","I"],"z":"C","t":"2023-04-06T11:54:26.83915973Z"}] +< [{"T":"q","S":"AMD","bx":"P","bp":91.9,"bs":1,"ax":"Q","ap":91.98,"as":1,"c":["R"],"z":"C","t":"2023-04-06T11:54:27.924933876Z"}] +``` + +## Errors (G) + +The only error message shown verbatim as JSON in the docs: + +```json +[{"T":"error","code":406,"msg":"connection limit exceeded"}] +``` + +The other codes are documented only as a table (code + msg + description), not as JSON: + +| Code | msg | Meaning (summarised) | +|------|-----|----------------------| +| 400 | invalid syntax | message not per spec; also sent for an invalid symbol format in a subscription | +| 401 | not authenticated | subscribe/unsubscribe before auth | +| 402 | auth failed | invalid credentials | +| 403 | already authenticated | auth sent twice in the session | +| 404 | auth timeout | did not authenticate in time after connecting | +| 405 | symbol limit exceeded | over the plan's symbol limit; previous subscriptions are kept unchanged | +| 406 | connection limit exceeded | already at the number of sessions allowed | +| 407 | slow client | client too slow; not guaranteed to arrive before disconnection | +| 409 | insufficient subscription | data source not in the plan | +| 410 | invalid subscribe action for this feed | channel not available on that stream | +| 500 | internal error | unexpected server error | + +## Limits + +- Basic plan: 30 symbols on the websocket (P, table "Websocket subscriptions"). +- Connections: "The number of connections to a single endpoint from a user is limited based on + the user's subscription, but in many subscriptions (or without one) this limit is 1." (G) + A second connection gets the 406 above. The docs do not state the Basic limit as an exact number. diff --git a/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2017-08.zip.CHECKSUM b/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2017-08.zip.CHECKSUM new file mode 100644 index 0000000..bf21ded --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2017-08.zip.CHECKSUM @@ -0,0 +1 @@ +c92970f74893163b848f117a37fa5e7110ee1d800c0d9ada949940fccccfdd2f BTCUSDT-1d-2017-08.zip \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2025-01.zip.CHECKSUM b/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2025-01.zip.CHECKSUM new file mode 100644 index 0000000..4fa3b86 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/BTCUSDT-1d-2025-01.zip.CHECKSUM @@ -0,0 +1 @@ +3a3eb1b723d944deb4dbef5ae361bbe39340a17fe987fe22e397ef03dca268d2 BTCUSDT-1d-2025-01.zip \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2017-08.csv b/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2017-08.csv new file mode 100644 index 0000000..dd86797 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2017-08.csv @@ -0,0 +1,5 @@ +1502928000000,4261.48000000,4485.39000000,4200.74000000,4285.08000000,795.15037700,1503014399999,3454770.05073206,3427,616.24854100,2678216.40060401,8733.91139481 +1503014400000,4285.08000000,4371.52000000,3938.77000000,4108.37000000,1199.88826400,1503100799999,5086958.30617151,5233,972.86871000,4129123.31651808,9384.14140858 +1503100800000,4108.37000000,4184.69000000,3850.00000000,4139.98000000,381.30976300,1503187199999,1549483.73542151,2153,274.33604200,1118001.87008735,9184.08552906 +1503187200000,4120.98000000,4211.08000000,4032.62000000,4086.29000000,467.08302200,1503273599999,1930364.39032646,2321,376.79594700,1557401.33373730,10125.41408414 +1503273600000,4069.13000000,4119.62000000,3911.79000000,4016.00000000,691.74306000,1503359999999,2797231.71402728,3972,557.35610700,2255662.55315837,11706.76997007 diff --git a/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2025-01.csv b/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2025-01.csv new file mode 100644 index 0000000..985b62a --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/binance-BTCUSDT-1d-2025-01.csv @@ -0,0 +1,5 @@ +1735689600000000,93576.00000000,95151.15000000,92888.00000000,94591.79000000,10373.32613000,1735775999999999,975444194.13799830,1516556,5347.73648000,502914035.64059070,0 +1735776000000000,94591.78000000,97839.50000000,94392.00000000,96984.79000000,21970.48948000,1735862399999999,2118411852.68127950,3569079,10915.96986000,1052226710.33367170,0 +1735862400000000,96984.79000000,98976.91000000,96100.01000000,98174.18000000,15253.82936000,1735948799999999,1486610768.59079170,2851164,7468.60797000,727787246.89655880,0 +1735948800000000,98174.17000000,98778.43000000,97514.79000000,98220.50000000,8990.05651000,1736035199999999,881223751.63536030,1559982,4350.80221000,426524714.13055390,0 +1736035200000000,98220.51000000,98836.85000000,97276.79000000,98363.61000000,8095.63723000,1736121599999999,793931715.95463240,1685799,3877.90985000,380355340.46860360,0 diff --git a/tests/Anubis.Tests/Fixtures/free/binance-listing.xml b/tests/Anubis.Tests/Fixtures/free/binance-listing.xml new file mode 100644 index 0000000..a1c3e08 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/binance-listing.xml @@ -0,0 +1,7 @@ + +data.binance.visiondata/spot/monthly/klines/BTCUSDT/1d/1000/false +data/spot/monthly/klines/BTCUSDT/1d/BTCUSDT-1d-2017-08.zip2021-06-22T11:34:18.000Z"de69dcc75a0d145a68ee7d2d7bb12e00"1150STANDARD +data/spot/monthly/klines/BTCUSDT/1d/BTCUSDT-1d-2017-08.zip.CHECKSUM2021-06-22T11:34:18.000Z"16214e8597f7b6dd811f97b4b8e9cb94"88STANDARD +data/spot/monthly/klines/BTCUSDT/1d/BTCUSDT-1d-2026-10.zip2026-11-02T10:54:15.000Z"9e3817dcfb6373a96ce8a37acc9ca433"CRC64NVMEFULL_OBJECT2224STANDARD +data/spot/monthly/klines/BTCUSDT/1d/BTCUSDT-1d-2026-10.zip.CHECKSUM2026-11-02T10:54:15.000Z"29b93f9f76a4673ed03ad9584cc7e476"CRC64NVMEFULL_OBJECT88STANDARD + diff --git a/tests/Anubis.Tests/Fixtures/free/central-banks.md b/tests/Anubis.Tests/Fixtures/free/central-banks.md new file mode 100644 index 0000000..bdd09d7 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/central-banks.md @@ -0,0 +1,48 @@ +# Central bank meeting calendars (retrieved 2026-11-10) + +Decision day = the day the rate decision is announced (second day of two-day meetings). + +## FOMC (Federal Reserve) + +Source: https://www.federalreserve.gov/monetarypolicy/fomccalendars.htm (page "Last Update: October 28, 2026"). +Statement at 14:00 America/New_York on the decision day (Fed practice, not stated on this page). +`*` = meeting with a Summary of Economic Projections (SEP). +Page note: "Each meeting date is tentative until confirmed at the meeting immediately preceding it." + +| Meeting | Decision day | SEP | +|---|---|---| +| 2026-12-08/09 | 2026-12-09 | yes | +| 2027-01-26/27 | 2027-01-27 | no | +| 2027-03-16/17 | 2027-03-17 | yes | +| 2027-04-27/28 | 2027-04-28 | no | +| 2027-06-08/09 | 2027-06-09 | yes | +| 2027-07-27/28 | 2027-07-28 | no | +| 2027-09-14/15 | 2027-09-15 | yes | +| 2027-10-26/27 | 2027-10-27 | no | +| 2027-12-07/08 | 2027-12-08 | yes | + +Next after that (page note): 2028-01-25/26, decision 2028-01-26. + +Already past in 2026 (for reference): Jan 27-28, Mar 17-18*, Apr 28-29, Jun 16-17*, Jul 28-29, Sep 15-16*, Oct 27-28. + +## ECB (Governing Council, monetary policy meetings) + +Source: https://www.ecb.europa.eu/press/calendars/mgcgc/html/index.en.html +("Schedules for the meetings of the Governing Council and General Council of the ECB and related press conferences"). +All listed as "monetary policy meeting in Frankfurt (Day 1)" + "(Day 2), followed by press conference". +Decision published on Day 2 at 14:15 CET, press conference 14:45 CET (ECB practice, not stated on this page). +Non-monetary policy meetings are not listed here. + +| Meeting | Decision day | +|---|---| +| 2026-12-16/17 | 2026-12-17 | +| 2027-02-03/04 | 2027-02-04 | +| 2027-03-17/18 | 2027-03-18 | +| 2027-04-28/29 | 2027-04-29 | +| 2027-06-09/10 | 2027-06-10 | +| 2027-07-21/22 | 2027-07-22 | +| 2027-09-08/09 | 2027-09-09 | +| 2027-10-27/28 | 2027-10-28 | +| 2027-12-15/16 | 2027-12-16 | + +The page also already lists 2028 decision days: 02-03, 03-23, 05-04, 06-08, 07-20, 09-07, 10-12, 12-07. diff --git a/tests/Anubis.Tests/Fixtures/free/ecb-daily.xml b/tests/Anubis.Tests/Fixtures/free/ecb-daily.xml new file mode 100644 index 0000000..403a997 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/ecb-daily.xml @@ -0,0 +1,15 @@ + + + Reference rates + + European Central Bank + + + + + + + + + + diff --git a/tests/Anubis.Tests/Fixtures/free/ecb-hist-90d.xml b/tests/Anubis.Tests/Fixtures/free/ecb-hist-90d.xml new file mode 100644 index 0000000..403f7a7 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/ecb-hist-90d.xml @@ -0,0 +1,4 @@ +Reference ratesEuropean Central Bank + + + \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/free/ecb-hist.csv b/tests/Anubis.Tests/Fixtures/free/ecb-hist.csv new file mode 100644 index 0000000..9437fbb --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/ecb-hist.csv @@ -0,0 +1,3 @@ +Date,USD,JPY,BGN,CYP,CZK,DKK,EEK,GBP,HUF,LTL,LVL,MTL,PLN,ROL,RON,SEK,SIT,SKK,CHF,ISK,NOK,HRK,RUB,TRL,TRY,AUD,BRL,CAD,CNY,HKD,IDR,ILS,INR,KRW,MXN,MYR,NZD,PHP,SGD,THB,ZAR, +2026-11-09,1.1193,176.79,N/A,N/A,24.365,7.4753,N/A,0.8343,362.99,N/A,N/A,N/A,4.3843,N/A,5.343,10.996,N/A,N/A,0.9164,136.8,10.5325,N/A,N/A,N/A,56.1199,1.6236,6.1748,1.5785,7.4689,8.7772,20234.31,3.549,105.1435,1507.46,20.8343,4.5432,1.9941,70.712,1.4328,37.485,18.4105, +2026-11-06,1.1165,176.77,N/A,N/A,24.35,7.4752,N/A,0.83415,363.9,N/A,N/A,N/A,4.3925,N/A,5.3403,11.026,N/A,N/A,0.9143,136.8,10.526,N/A,N/A,N/A,55.9957,1.625,6.1449,1.5705,7.4485,8.7505,20208.93,3.5717,104.8645,1517.02,20.8828,4.5319,2.0141,70.358,1.4309,37.459,18.4649, diff --git a/tests/Anubis.Tests/Fixtures/free/ff-calendar.json b/tests/Anubis.Tests/Fixtures/free/ff-calendar.json new file mode 100644 index 0000000..3cbfdfd --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/ff-calendar.json @@ -0,0 +1 @@ +[{"title":"RBA Assist Gov Hunter Speaks","country":"AUD","date":"2026-11-08T17:30:00-05:00","impact":"Low","forecast":"","previous":""},{"title":"CPI y\/y","country":"CNY","date":"2026-11-08T20:30:00-05:00","impact":"Low","forecast":"0.8%","previous":"0.9%"},{"title":"CPI m\/m","country":"USD","date":"2026-11-10T08:30:00-05:00","impact":"High","forecast":"0.3%","previous":"0.6%"},{"title":"Unemployment Claims","country":"USD","date":"2026-11-12T08:30:00-05:00","impact":"Medium","forecast":"194K","previous":"189K"},{"title":"Bank Holiday","country":"USD","date":"2026-11-11T08:00:00-05:00","impact":"Holiday","forecast":"","previous":""}] \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/free/finnhub-earnings.json b/tests/Anubis.Tests/Fixtures/free/finnhub-earnings.json new file mode 100644 index 0000000..1d02376 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/finnhub-earnings.json @@ -0,0 +1,26 @@ +{ + "earningsCalendar": [ + { + "date": "2020-01-28", + "epsActual": 4.99, + "epsEstimate": 4.5474, + "hour": "amc", + "quarter": 1, + "revenueActual": 91819000000, + "revenueEstimate": 88496400810, + "symbol": "AAPL", + "year": 2020 + }, + { + "date": "2019-10-30", + "epsActual": 3.03, + "epsEstimate": 2.8393, + "hour": "amc", + "quarter": 4, + "revenueActual": 64040000000, + "revenueEstimate": 62985161760, + "symbol": "AAPL", + "year": 2019 + } + ] +} diff --git a/tests/Anubis.Tests/Fixtures/free/fng.json b/tests/Anubis.Tests/Fixtures/free/fng.json new file mode 100644 index 0000000..bd0ed06 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/fng.json @@ -0,0 +1,19 @@ +{ + "name": "Fear and Greed Index", + "data": [ + { + "value": "32", + "value_classification": "Fear", + "timestamp": "1794268800", + "time_until_update": "36787" + }, + { + "value": "29", + "value_classification": "Fear", + "timestamp": "1794182400" + } + ], + "metadata": { + "error": null + } +} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/free/fred-release-dates.json b/tests/Anubis.Tests/Fixtures/free/fred-release-dates.json new file mode 100644 index 0000000..51ba61e --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/fred-release-dates.json @@ -0,0 +1,79 @@ +{ + "realtime_start": "1776-07-04", + "realtime_end": "9999-12-31", + "order_by": "release_date", + "sort_order": "asc", + "count": 17, + "offset": 0, + "limit": 10000, + "release_dates": [ + { + "release_id": 82, + "date": "1997-02-10" + }, + { + "release_id": 82, + "date": "1998-02-10" + }, + { + "release_id": 82, + "date": "1999-02-04" + }, + { + "release_id": 82, + "date": "2000-02-10" + }, + { + "release_id": 82, + "date": "2001-01-16" + }, + { + "release_id": 82, + "date": "2002-02-06" + }, + { + "release_id": 82, + "date": "2003-02-07" + }, + { + "release_id": 82, + "date": "2004-02-09" + }, + { + "release_id": 82, + "date": "2005-02-17" + }, + { + "release_id": 82, + "date": "2006-02-13" + }, + { + "release_id": 82, + "date": "2007-02-16" + }, + { + "release_id": 82, + "date": "2008-02-11" + }, + { + "release_id": 82, + "date": "2009-03-03" + }, + { + "release_id": 82, + "date": "2010-02-11" + }, + { + "release_id": 82, + "date": "2011-02-23" + }, + { + "release_id": 82, + "date": "2012-10-24" + }, + { + "release_id": 82, + "date": "2013-04-10" + } + ] +} diff --git a/tests/Anubis.Tests/Fixtures/free/nasdaqtraded.txt b/tests/Anubis.Tests/Fixtures/free/nasdaqtraded.txt new file mode 100644 index 0000000..9ffceff --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/nasdaqtraded.txt @@ -0,0 +1,14 @@ +Nasdaq Traded|Symbol|Security Name|Listing Exchange|Market Category|ETF|Round Lot Size|Test Issue|Financial Status|CQS Symbol|NASDAQ Symbol|NextShares +Y|AAPL|Apple Inc. - Common Stock|Q|Q|N|40|N|N||AAPL|N +Y|KO|Coca-Cola Company (The) Common Stock|N| |N|100|N||KO|KO|N +Y|SPY|State Street SPDR S&P 500 ETF Trust|P| |Y|40|N||SPY|SPY|N +Y|CECO|CECO Environmental Corp. Common Stock|F| |N|100|N||CECO|CECO|N +Y|BULZ|MicroSectors FANG & Innovation 3x Leveraged ETN|P| |Y|100|N||BULZ|BULZ|N +Y|AMUB|ETRACS Alerian MLP Index ETN Series B due July 18, 2042|P| |N|100|N||AMUB|AMUB|N +Y|PDI|PIMCO Dynamic Income Fund Common Stock|N| |N|100|N||PDI|PDI|N +Y|ABR$D|Arbor Realty Trust 6.375% Series D Cumulative Redeemable Preferred Stock, Liquidation Preference $25.00 per Share|N| |N|100|N||ABRpD|ABR-D|N +Y|AACIW|Armada Acquisition Corp. III - Warrant|Q|G|N|100|N|N||AACIW|N +Y|AACG|ATA Creativity Global - American Depositary Shares, each representing two common shares|Q|S|N|100|N|D||AACG|N +N|BRK.A|Berkshire Hathaway Inc. Common Stock|N| |N|1|N||BRK.A|BRK.A|N +Y|ZXIET|IEX Test Company Test Symbol Three for IEX|V| |N|100|Y||ZXIET|ZXIET|N +File Creation Time: 1110202608:47||||| diff --git a/tests/Anubis.Tests/Fixtures/free/vix.csv b/tests/Anubis.Tests/Fixtures/free/vix.csv new file mode 100644 index 0000000..b8070d9 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/free/vix.csv @@ -0,0 +1,5 @@ +DATE,OPEN,HIGH,LOW,CLOSE +01/02/1990,17.240000,17.240000,17.240000,17.240000 +01/03/1990,18.190000,18.190000,18.190000,18.190000 +11/06/2026,27.680000,27.760000,23.470000,25.640000 +11/09/2026,25.080000,25.080000,19.640000,19.920000 diff --git a/tests/Anubis.Tests/Fixtures/okx/books-btc-eur-sz5.json b/tests/Anubis.Tests/Fixtures/okx/books-btc-eur-sz5.json new file mode 100644 index 0000000..cfec831 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/books-btc-eur-sz5.json @@ -0,0 +1 @@ +{"code":"0","msg":"","data":[{"asks":[["65998.6","0.01847","0","1"],["66007.9","0.01950009","0","1"],["66017.2","0.02600013","0","1"],["66019.7","0.08124142","0","1"],["66040","0.00074","0","1"]],"bids": [["65986.1","0.02600013","0","1"],["65979.9","0.02600013","0","1"],["65967.5","0.02600013","0","1"],["65965.3","0.08130857","0","1"],["65940.4","0.00174173","0","1"]],"ts": "1794318312903","seqId": 8550771731}]} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/candles-1Dutc-btc-eur.json b/tests/Anubis.Tests/Fixtures/okx/candles-1Dutc-btc-eur.json new file mode 100644 index 0000000..a4bef17 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/candles-1Dutc-btc-eur.json @@ -0,0 +1 @@ +{"code":"0","data":[["1794268800000","67082.7","67169.1","65700","65995.6","49.49453348","3281596.15859545","3281596.15859545","0"],["1794182400000","67102.9","67730.8","65957.5","67058.9","87.03419039","5799147.867285542","5799147.867285542","1"],["1794096000000","68031.7","68329.2","66005.3","67090.9","68.34820078","4593882.883114905","4593882.883114905","1"],["1794009600000","68000.7","68380.8","67773.8","68045.9","28.39339742","1933533.396611748","1933533.396611748","1"],["1793923200000","67722.2","68333.3","67091","68003.4","70.5073903","4783491.931149474","4783491.931149474","1"]],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/candles-1m-btc-eur.json b/tests/Anubis.Tests/Fixtures/okx/candles-1m-btc-eur.json new file mode 100644 index 0000000..e442adf --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/candles-1m-btc-eur.json @@ -0,0 +1 @@ +{"code":"0","data":[["1794318240000","66014","66014","65959.8","65959.8","0.00566935","374.097328501","374.097328501","0"],["1794318180000","65999.8","66069.8","65999.8","66050.5","0.0523422","3457.089286529","3457.089286529","1"],["1794318120000","65890.5","65986.5","65886.7","65968","0.01010823","666.959143595","666.959143595","1"],["1794318060000","65920","65928.9","65893.8","65898.8","0.01617887","1066.219812468","1066.219812468","1"],["1794318000000","65962.4","65997.7","65940.4","65945","0.01322151","872.109237591","872.109237591","1"]],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/funding-rate-btc.json b/tests/Anubis.Tests/Fixtures/okx/funding-rate-btc.json new file mode 100644 index 0000000..1b3975b --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/funding-rate-btc.json @@ -0,0 +1 @@ +{"code":"0","data":[{"formulaType":"withRate","fundingRate":"-0.0000009390698834","fundingTime":"1794326400000","impactValue":"20000.0000000000000000","instId":"BTC-USDT-SWAP","instType":"SWAP","interestRate":"0.0001000000000000","maxFundingRate":"0.00375","method":"current_period","minFundingRate":"-0.00375","nextFundingRate":"","nextFundingTime":"1794355200000","premium":"-0.0004047059587875","prevFundingTime":"1794297600000","settFundingRate":"0.0001000000000000","settState":"settled","ts":"1794318013510"}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/history-candles-1Dutc-btc-eur-first.json b/tests/Anubis.Tests/Fixtures/okx/history-candles-1Dutc-btc-eur-first.json new file mode 100644 index 0000000..5839346 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/history-candles-1Dutc-btc-eur-first.json @@ -0,0 +1 @@ +{"code":"0","data":[["1700870400000","34593","34593","34511.2","34535.3","0.59821825","20677.171718216","20677.171718216","1"],["1700784000000","34275.4","34998.8","34275.4","34592.4","4.44982271","154238.594247212","154238.594247212","1"],["1700697600000","34397.3","34397.3","33953.5","34165.5","1.31890957","45071.044398169","45071.044398169","1"],["1700611200000","33316.2","34718.6","33309.5","34709.1","4.32517623","147240.001527279","147240.001527279","1"],["1700524800000","34255.8","34340.2","32774.3","32774.3","8.40657006","281736.604324771","281736.604324771","1"]],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/instruments-spot.json b/tests/Anubis.Tests/Fixtures/okx/instruments-spot.json new file mode 100644 index 0000000..799aaa3 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/instruments-spot.json @@ -0,0 +1 @@ +{"code":"0","data":[{"alias":"","auctionEndTime":"","baseCcy":"BTC","category":"1","contTdSwTime":"","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.005","freq":"","futureSettlement":false,"groupId":"18","initPxLmtPct":"","instCategory":"1","instFamily":"","instId":"BTC-EUR","instIdCode":138508,"instType":"SPOT","lever":"","listTime":"1700539860000","longPosRemainingQuota":"","lotSz":"0.00000001","maxIcebergSz":"9999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"9999999999","maxMktAmt":"400000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.01","maxStopSz":"1000000","maxTriggerSz":"9999999999.0000000000000000","maxTwapSz":"9999999999.0000000000000000","method":"","minSz":"0.0001","openType":"fix_price","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"EUR","rpiMinLevel":"2","rpiMinPxBand":"20","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"0.1","tradeQuoteCcyList":["EURC","EUR"],"uly":"","upcChg":[]},{"alias":"","auctionEndTime":"","baseCcy":"ETH","category":"1","contTdSwTime":"","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.005","freq":"","futureSettlement":false,"groupId":"18","initPxLmtPct":"","instCategory":"1","instFamily":"","instId":"ETH-EUR","instIdCode":138510,"instType":"SPOT","lever":"","listTime":"1700539860000","longPosRemainingQuota":"","lotSz":"0.000001","maxIcebergSz":"999999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"999999999999","maxMktAmt":"100000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.01","maxStopSz":"1000000","maxTriggerSz":"999999999999.0000000000000000","maxTwapSz":"999999999999.0000000000000000","method":"","minSz":"0.001","openType":"fix_price","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"EUR","rpiMinLevel":"2","rpiMinPxBand":"20","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"0.01","tradeQuoteCcyList":["EURC","EUR"],"uly":"","upcChg":[]},{"alias":"","auctionEndTime":"","baseCcy":"SOL","category":"1","contTdSwTime":"","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.005","freq":"","futureSettlement":false,"groupId":"18","initPxLmtPct":"","instCategory":"1","instFamily":"","instId":"SOL-EUR","instIdCode":138511,"instType":"SPOT","lever":"","listTime":"1700539860000","longPosRemainingQuota":"","lotSz":"0.000001","maxIcebergSz":"999999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"999999999999","maxMktAmt":"45000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.01","maxStopSz":"1000000","maxTriggerSz":"999999999999.0000000000000000","maxTwapSz":"999999999999.0000000000000000","method":"","minSz":"0.01","openType":"fix_price","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"EUR","rpiMinLevel":"2","rpiMinPxBand":"20","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"0.01","tradeQuoteCcyList":["EURC","EUR"],"uly":"","upcChg":[]},{"alias":"","auctionEndTime":"","baseCcy":"BTC","category":"1","contTdSwTime":"","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.005","freq":"","futureSettlement":false,"groupId":"12","initPxLmtPct":"0.1","instCategory":"1","instFamily":"","instId":"BTC-USDC","instIdCode":224008,"instType":"SPOT","lever":"","listTime":"1755763200000","longPosRemainingQuota":"","lotSz":"0.00000001","maxIcebergSz":"9999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"9999999999","maxMktAmt":"1000000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.01","maxStopSz":"1000000","maxTriggerSz":"9999999999.0000000000000000","maxTwapSz":"9999999999.0000000000000000","method":"","minSz":"0.00001","openType":"fix_price","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"USDC","rpiMinLevel":"2","rpiMinPxBand":"20","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"0.1","tradeQuoteCcyList":["USDG","USD","USDC","RLUSD"],"uly":"","upcChg":[]},{"alias":"","auctionEndTime":"","baseCcy":"BTC","category":"1","contTdSwTime":"","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.005","freq":"","futureSettlement":false,"groupId":"12","initPxLmtPct":"","instCategory":"1","instFamily":"","instId":"BTC-USDT","instIdCode":3,"instType":"SPOT","lever":"10","listTime":"1611907686000","longPosRemainingQuota":"","lotSz":"0.00000001","maxIcebergSz":"9999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"9999999999","maxMktAmt":"1000000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.01","maxStopSz":"1000000","maxTriggerSz":"9999999999.0000000000000000","maxTwapSz":"9999999999.0000000000000000","method":"","minSz":"0.00001","openType":"fix_price","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"USDT","rpiMinLevel":"3","rpiMinPxBand":"20","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"0.1","tradeQuoteCcyList":["USDT"],"uly":"","upcChg":[]},{"alias":"","auctionEndTime":"","baseCcy":"BTC","category":"1","contTdSwTime":"1790751600000","ctMult":"","ctType":"","ctVal":"","ctValCcy":"","expTime":"","floatPxLmtPct":"0.02","freq":"","futureSettlement":false,"groupId":"11","initPxLmtPct":"0.1","instCategory":"1","instFamily":"","instId":"BTC-PLN","instIdCode":485665,"instType":"SPOT","lever":"","listTime":"1790748000000","longPosRemainingQuota":"","lotSz":"0.00000001","maxIcebergSz":"9999999999.0000000000000000","maxLmtAmt":"20000000","maxLmtSz":"9999999999","maxMktAmt":"1000000","maxMktSz":"1000000","maxPlatOICoinLmt":"","maxPlatOILmt":"","maxPxLmtPct":"0.05","maxStopSz":"1000000","maxTriggerSz":"9999999999.0000000000000000","maxTwapSz":"9999999999.0000000000000000","method":"","minSz":"0.00001","openType":"pre_quote","optType":"","posLmtAmt":"","posLmtPct":"","preMktSwTime":"","quoteCcy":"PLN","ruleType":"normal","seriesId":"","settleCcy":"","shortPosRemainingQuota":"","state":"live","stk":"","tickSz":"1","tradeQuoteCcyList":["PLN"],"uly":"","upcChg":[]}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/open-interest-btc.json b/tests/Anubis.Tests/Fixtures/okx/open-interest-btc.json new file mode 100644 index 0000000..29560d4 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/open-interest-btc.json @@ -0,0 +1 @@ +{"code":"0","data":[{"instId":"BTC-USDT-SWAP","instType":"SWAP","oi":"3600677.00000001675","oiCcy":"36006.7700000001675","oiUsd":"2659809297.86901237317475","ts":"1794318321995"}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/public-time.json b/tests/Anubis.Tests/Fixtures/okx/public-time.json new file mode 100644 index 0000000..ebd6344 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/public-time.json @@ -0,0 +1 @@ +{"code":"0","data":[{"ts":"1794318266358"}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/ticker-btc-eur.json b/tests/Anubis.Tests/Fixtures/okx/ticker-btc-eur.json new file mode 100644 index 0000000..5a9f139 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/ticker-btc-eur.json @@ -0,0 +1 @@ +{"code":"0","data":[{"instType":"SPOT","instId":"BTC-EUR","last":"65958.9","lastSz":"0.00044","askPx":"65998.6","askSz":"0.01847","bidPx":"65986.1","bidSz":"0.02600011","open24h":"66683.7","high24h":"67457","low24h":"65700","volCcy24h":"5575007.141398614","vol24h":"83.82602516","ts":"1794318312368","sodUtc0":"67082.7","sodUtc8":"67429.6"}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/tickers-spot.json b/tests/Anubis.Tests/Fixtures/okx/tickers-spot.json new file mode 100644 index 0000000..e3a204f --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/tickers-spot.json @@ -0,0 +1 @@ +{"code":"0","data":[{"instType":"SPOT","instId":"BTC-USDC","last":"73887","lastSz":"0.0012911","askPx":"73887.1","askSz":"0.0015","bidPx":"73886.9","bidSz":"0.07498377","open24h":"74580.7","high24h":"75498.5","low24h":"73456","volCcy24h":"52361791.317870886","vol24h":"701.87662721","ts":"1794318321771","sodUtc0":"75273.2","sodUtc8":"75455.2"},{"instType":"SPOT","instId":"BTC-EUR","last":"65958.9","lastSz":"0.00044","askPx":"66065.1","askSz":"0.02599891","bidPx":"66047.5","bidSz":"0.01949918","open24h":"66683.7","high24h":"67457","low24h":"65700","volCcy24h":"5575007.141398614","vol24h":"83.82602516","ts":"1794318321672","sodUtc0":"67082.7","sodUtc8":"67429.6"},{"instType":"SPOT","instId":"ETH-EUR","last":"1848.25","lastSz":"0.005067","askPx":"1849.56","askSz":"0.18408","bidPx":"1849.41","bidSz":"2.900507","open24h":"1889.85","high24h":"1920.5","low24h":"1817","volCcy24h":"2854479.7139542","vol24h":"1526.885348","ts":"1794318321675","sodUtc0":"1900.62","sodUtc8":"1916.45"}],"msg":""} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/okx/ws-examples.md b/tests/Anubis.Tests/Fixtures/okx/ws-examples.md new file mode 100644 index 0000000..20a8552 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx/ws-examples.md @@ -0,0 +1,197 @@ +# OKX v5 WebSocket — examples + +Source of [DOCS] blocks: https://my.okx.com/docs-v5/en/ (sections "WebSocket > Connect", "Subscribe", +"Notification", "Connection count limit", "WS / Tickers channel", "WS / Candlesticks channel", +"Error Code > WebSocket"), read on 2026-11-10. +Source of [LIVE] blocks: real frames captured on 2026-11-10 from wseea.okx.com / wseeapap.okx.com +(no login). Frames are copied byte-for-byte as received. + +## URLs + +| Use | URL | Channels | +|---|---|---| +| Production public | `wss://wseea.okx.com/ws/v5/public` | `tickers`, `books*`, `trades`, ... | +| Production business | `wss://wseea.okx.com/ws/v5/business` | `candle*` (all candle channels) | +| Demo public | `wss://wseeapap.okx.com/ws/v5/public` | as production | +| Demo business | `wss://wseeapap.okx.com/ws/v5/business` | as production | + +## Keepalive [DOCS, "Connect"] + +- The server closes the connection if no subscription is established or no data is pushed for more than 30 s + (close code 4004 "No data received in 30s"). +- Client rule: reset an N-second timer (N < 30) on every received message; when it fires, send the + plain text frame `ping` (not JSON); expect the plain text frame `pong` within N s, otherwise reconnect. +- Connection limit: 3 connection requests per second per IP. +- Request limit: 480 `subscribe`/`unsubscribe`/`login` requests per connection per hour. +- Total length of the `args` of one request: max 64 KB. + +[LIVE] public, after a tickers subscription: +``` +> ping +< pong +``` +Note: pushes already in flight can arrive before the `pong` (observed live). + +## Subscribe request [DOCS] + +```json +{ + "id": "1512", + "op":"subscribe", + "args":[ + { + "channel":"tickers", + "instId":"BTC-USDT" + } + ] +} +``` +`id` is optional, client-chosen, up to 32 alphanumeric characters, echoed in the response. +Unsubscribe: same shape with `"op":"unsubscribe"`. + +## Subscription confirmation [DOCS] + +```json +{ + "id": "1512", + "event": "subscribe", + "arg": { + "channel": "tickers", + "instId": "BTC-USDT" + }, + "connId": "accb8e21" +} +``` + +[LIVE] public, tickers BTC-EUR: +```json +{"id":"1","event":"subscribe","arg":{"channel":"tickers","instId":"BTC-EUR"},"connId":"53efe456"} +``` + +[LIVE] business, two args in one request -> one confirmation per arg, same `id`: +``` +> {"id":"3","op":"subscribe","args":[{"channel":"candle1m","instId":"BTC-EUR"},{"channel":"candle1Dutc","instId":"BTC-EUR"}]} +< {"id":"3","event":"subscribe","arg":{"channel":"candle1m","instId":"BTC-EUR"},"connId":"3e5c5e42"} +< {"id":"3","event":"subscribe","arg":{"channel":"candle1Dutc","instId":"BTC-EUR"},"connId":"3e5c5e42"} +``` + +## Error response [DOCS] + +```json +{ + "id": "1512", + "event": "error", + "code": "60012", + "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"tickers\", \"instId\" : \"LTC-USD-200327\"}]}", + "connId": "a4d3ae55" +} +``` + +[LIVE] subscribing `candle1m` on the PUBLIC url (wrong url) -> code 60018 (not 64001): +```json +{"event":"error","msg":"Subscribe failed, wrong URL or channel:candle1m,instId:BTC-EUR doesn't exist. Please use the correct URL, channel and parameters referring to API document.","code":"60018","connId":"53efe456","id":"2"} +``` + +Main WS error codes [DOCS]: 60012 Invalid request; 60013 Invalid args; 60014 Requests too frequent; +60018 Wrong URL or {0} doesn't exist; 60019 Invalid op; 64001 channel migrated to '/business' URL; +64002 channel not supported by '/business' URL; 64008 connection will close for service upgrade; +64010 port 8443 will be retired. Close frames: 4004 No data received in 30s; 4008/4009 too many +subscribed channels; 1009 message exceeds the maximum frame length. + +## Tickers push (channel `tickers`, public URL) [DOCS] + +Fastest 1 update / 100 ms; only on trade or best bid/ask change. +```json +{ + "arg": { + "channel": "tickers", + "instId": "BTC-USDT" + }, + "data": [ + { + "instType": "SPOT", + "instId": "BTC-USDT", + "last": "9999.99", + "lastSz": "0.1", + "askPx": "9999.99", + "askSz": "11", + "bidPx": "8888.88", + "bidSz": "5", + "open24h": "9000", + "high24h": "10000", + "low24h": "8888.88", + "volCcy24h": "2222", + "vol24h": "2222", + "sodUtc0": "2222", + "sodUtc8": "2222", + "ts": "1597026383085" + } + ] +} +``` + +[LIVE] BTC-EUR: +```json +{"arg":{"channel":"tickers","instId":"BTC-EUR"},"data":[{"instType":"SPOT","instId":"BTC-EUR","last":"66148.9","lastSz":"0.00010133","askPx":"66134.7","askSz":"0.01847","bidPx":"66129.6","bidSz":"0.0193605","open24h":"66709.6","high24h":"67457","low24h":"65700","sodUtc0":"67082.7","sodUtc8":"67429.6","volCcy24h":"5581463.825401407","vol24h":"83.92407803","ts":"1794318514123"}]} +``` + +## Candle push (channels `candle1m`, `candle1Dutc`, ..., BUSINESS URL) [DOCS] + +Fastest push every 1 s. `data` is an array of arrays +`[ts,o,h,l,c,vol,volCcy,volCcyQuote,confirm]`; `confirm` "0" = in progress, "1" = closed. +Channel names include candle1s, candle1m, candle3m, candle5m, candle15m, candle30m, candle1H, candle2H, +candle4H, candle6H, candle12H, candle1D, candle2D, candle3D, candle5D, candle1W, candle1M, candle3M and the +UTC variants candle6Hutc, candle12Hutc, candle1Dutc, candle2Dutc, candle3Dutc, candle5Dutc, candle1Wutc, +candle1Mutc, candle3Mutc. Note `candle1m` = 1 minute, `candle1M` = 1 month. +```json +{ + "arg": { + "channel": "candle1D", + "instId": "BTC-USDT" + }, + "data": [ + [ + "1597026383085", + "8533.02", + "8553.74", + "8527.17", + "8548.26", + "45247", + "529.5858061", + "5529.5858061", + "0" + ] + ] +} +``` + +[LIVE] BTC-EUR candle1m: +```json +{"arg":{"channel":"candle1m","instId":"BTC-EUR"},"data":[["1794318480000","66104.2","66148.9","66104.2","66132.7","0.01956494","1293.950829541","1293.950829541","0"]]} +``` + +## Notices [DOCS + LIVE] + +[DOCS] service upgrade, sent 60 s before disconnect: +```json +{ + "event": "notice", + "code": "64008", + "msg": "The connection will soon be closed for a service upgrade. Please reconnect.", + "connId": "a4d3ae55" +} +``` + +[LIVE] connecting to port 8443 (both `wss://wseea.okx.com:8443/ws/v5/public` and +`wss://wseeapap.okx.com:8443/ws/v5/public` still accepted the connection on 2026-11-10 and sent this +once after the handshake; the connection stays open): +```json +{"event":"notice","msg":"WebSocket port 8443 will be retired soon. Please migrate to port 443.","code":"64010","connId":"6a3d66ba"} +``` + +## Connection count limit [DOCS] + +30 connections per channel per sub-account, but ONLY for private channels (orders, account, positions, +balance_and_position, liquidation-warning, account-greeks). Events `channel-conn-count` and +`channel-conn-count-error`. No per-connection limit on public channels is documented beyond the +480 requests/hour, 64 KB args and 3 connections/s per IP rules above. diff --git a/tests/Anubis.Tests/MarketDataLogicTests.cs b/tests/Anubis.Tests/MarketDataLogicTests.cs new file mode 100644 index 0000000..7aa76bf --- /dev/null +++ b/tests/Anubis.Tests/MarketDataLogicTests.cs @@ -0,0 +1,242 @@ +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// Quality checks, freshness, research files and adjusted series (issues #20, #21, #23). +[TestClass] +public sealed class MarketDataLogicTests +{ + private static readonly DateOnly _day0 = new(2026, 1, 1); + + /// A gentle random walk around 100: returns of about ±1%. + internal static List Walk(int days, DateOnly? first = null, int seed = 7) + { + var random = new Random(seed); + var bars = new List(); + var close = 100.0; + for (var i = 0; i < days; i++) + { + var open = close; + close = open * (1 + ((random.NextDouble() - 0.5) * 0.02)); + bars.Add(new DailyBar((first ?? _day0).AddDays(i), open, Math.Max(open, close) * 1.002, Math.Min(open, close) * 0.998, close, 1000 + i)); + } + + return bars; + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CleanSeriesHasNoFindings() + { + var bars = Walk(200); + Assert.IsEmpty(QualityChecks.CheckDaily(bars, QualityChecks.EveryDay(bars[0].Day, bars[^1].Day))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ChecksFindEachKindOfProblem() + { + var bars = Walk(120); + bars[100] = bars[100] with { Close = bars[99].Close * 1.6, High = bars[99].Close * 1.6 }; // +60% in a day of ±1% days + bars[101] = bars[101] with { Open = bars[100].Close, High = bars[100].Close }; + bars[50] = bars[50] with { Low = 0 }; + bars[60] = bars[60] with { High = bars[60].Low - 1 }; + bars.RemoveAt(30); // a missing day + bars.RemoveAt(30); // and the next one + bars.Add(bars[10]); // a duplicate + + var findings = QualityChecks.CheckDaily(bars, QualityChecks.EveryDay(_day0, _day0.AddDays(119))); + var kinds = findings.GroupBy(f => f.Kind).ToDictionary(g => g.Key, g => g.ToList()); + + Assert.AreEqual(QualityChecks.Midnight(_day0.AddDays(10)), kinds[IssueKinds.Duplicate].Single().StartsAt); + Assert.Contains("identiche", kinds[IssueKinds.Duplicate].Single().Detail); + var gap = kinds[IssueKinds.Gap].Single(); + Assert.AreEqual((QualityChecks.Midnight(_day0.AddDays(30)), QualityChecks.Midnight(_day0.AddDays(31))), (gap.StartsAt, gap.EndsAt)); + Assert.AreEqual(QualityChecks.Midnight(_day0.AddDays(50)), kinds[IssueKinds.NonPositive].Single().StartsAt); + Assert.AreEqual(QualityChecks.Midnight(_day0.AddDays(60)), kinds[IssueKinds.HighBelowLow].Single().StartsAt); + Assert.IsTrue(kinds[IssueKinds.Jump].Any(f => f.StartsAt == QualityChecks.Midnight(_day0.AddDays(100))), "the 60% jump"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void WeekendsBetweenMissingSessionsDoNotSplitAGap() + { + // Sessions Monday to Friday; Thursday 8, Friday 9 and Monday 12 January are missing: one gap of three sessions. + var sessions = QualityChecks.EveryDay(new DateOnly(2026, 1, 5), new DateOnly(2026, 1, 16)) + .Where(d => d.DayOfWeek is not DayOfWeek.Saturday and not DayOfWeek.Sunday).ToList(); + var missing = new[] { new DateOnly(2026, 1, 8), new DateOnly(2026, 1, 9), new DateOnly(2026, 1, 12) }; + var bars = sessions.Where(d => !missing.Contains(d)).Select(d => new DailyBar(d, 10, 11, 9, 10, 1)).ToList(); + var gap = QualityChecks.CheckDaily(bars, sessions).Single(); + Assert.AreEqual(IssueKinds.Gap, gap.Kind); + Assert.AreEqual(QualityChecks.Midnight(missing[0]), gap.StartsAt); + Assert.AreEqual(QualityChecks.Midnight(missing[2]), gap.EndsAt); + Assert.Contains("3 giorni", gap.Detail); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void SplitsDoNotLookLikeJumpsOnAdjustedPrices() + { + var bars = Walk(120); + var split = new CorporateAction("TEST", CorporateActionKinds.Split, bars[80].Day, "test", "s") { Ratio = 4m }; + var raw = bars.Select((b, i) => i >= 80 ? b with { Open = b.Open / 4, High = b.High / 4, Low = b.Low / 4, Close = b.Close / 4 } : b).ToList(); + Assert.IsTrue(QualityChecks.CheckDaily(raw).Any(f => f.Kind == IssueKinds.Jump), "on real prices the split is a jump"); + Assert.IsEmpty(QualityChecks.CheckDaily(Adjustments.Anchored(raw, [split], raw[^1].Day)), "on adjusted prices it is not"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MinuteGapsAreFoundAgainstEveryMinute() + { + var from = new DateTimeOffset(2026, 11, 10, 9, 0, 0, TimeSpan.Zero); + var bars = Enumerable.Range(0, 30).Where(i => i is < 12 or >= 22).Select(i => new Bar(from.AddMinutes(i), 10, 10.1, 9.9, 10, 1)).ToList(); + var gap = QualityChecks.CheckMinutes(bars, QualityChecks.EveryMinute(from, from.AddMinutes(30))).Single(); + Assert.AreEqual((from.AddMinutes(12), from.AddMinutes(21)), (gap.StartsAt, gap.EndsAt)); + Assert.Contains("10 minuti", gap.Detail); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void FreshnessFollowsTheAgeOfTheLastDatum() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 10, 9, 0, 0, TimeSpan.Zero)); + var bus = new EventBus(); + using var events = bus.Subscribe(); + var monitor = new FreshnessMonitor(clock, bus); + var id = Guid.NewGuid(); + monitor.Follow(id, "BTC-EUR"); + Assert.IsFalse(monitor.IsFresh(id), "no datum yet"); + + monitor.Touch(id, clock.UtcNow.AddSeconds(-2)); + Assert.IsTrue(monitor.IsFresh(id)); + Assert.IsTrue(events.TryRead(out var fresh) && fresh!.Fresh); + + // The connection stays up but nothing arrives: stale after 60 seconds (trap 10). + clock.Advance(TimeSpan.FromSeconds(58)); + monitor.Check(); + Assert.IsTrue(monitor.IsFresh(id)); + clock.Advance(TimeSpan.FromSeconds(1)); + monitor.Check(); + Assert.IsFalse(monitor.IsFresh(id)); + Assert.IsTrue(events.TryRead(out var stale) && !stale!.Fresh); + + // A datum from the venue's future clock counts from now, not later. + monitor.Touch(id, clock.UtcNow.AddMinutes(5)); + clock.Advance(TimeSpan.FromSeconds(61)); + Assert.IsFalse(monitor.IsFresh(id)); + Assert.IsFalse(monitor.IsFresh(Guid.NewGuid()), "an instrument not followed is never fresh"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task ResearchFilesRoundTripWithoutLosingDecimals() + { + var folder = TempFolder.Create("research"); + try + { + var store = new ResearchStore(folder); + var t0 = new DateTimeOffset(2017, 12, 31, 23, 58, 0, TimeSpan.Zero); + var bars = new[] + { + new ResearchBar(t0, 13850.01000000m, 13869.99m, 13800.00000001m, 13855m, 1.23456789m) { QuoteVolume = 17104.5m, Trades = 42 }, + new ResearchBar(t0.AddMinutes(1), 0.00000001m, 79228162514264.337593543950m, 0.1m, 0.3m, 0m), + new ResearchBar(t0.AddMinutes(2), 13855m, 13860m, 13850m, 13851.5m, 2m) { QuoteVolume = 27704m }, + }; + await store.WriteAsync(Venues.Binance, "BTCUSDT", Timeframes.Minute, bars, CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { 2017, 2018 }, store.Years(Venues.Binance, "BTCUSDT", Timeframes.Minute).ToArray(), "one file per year"); + + var read = new List(); + await foreach (var bar in store.ReadAsync(Venues.Binance, "BTCUSDT", Timeframes.Minute, t0, t0.AddDays(1)).ConfigureAwait(false)) + { + read.Add(bar); + } + + CollectionAssert.AreEqual(bars, read); + Assert.AreEqual("13850.01", read[0].Open.ToString(System.Globalization.CultureInfo.InvariantCulture), "trailing zeros dropped, digits kept"); + + // Writing again merges: the same minute is replaced, new ones are added. + await store.WriteAsync(Venues.Binance, "BTCUSDT", Timeframes.Minute, [bars[0] with { Close = 1m }, bars[0] with { OpensAt = t0.AddMinutes(-1) }], CancellationToken.None) + .ConfigureAwait(false); + read.Clear(); + await foreach (var bar in store.ReadAsync(Venues.Binance, "BTCUSDT", Timeframes.Minute, t0.AddHours(-1), t0.AddDays(1)).ConfigureAwait(false)) + { + read.Add(bar); + } + + Assert.HasCount(4, read); + Assert.AreEqual(1m, read[1].Close); + CollectionAssert.Contains(store.Series().ToList(), (Venues.Binance, "BTCUSDT", Timeframes.Minute)); + Assert.AreEqual("BTC_EUR", ResearchStore.Safe("BTC/EUR")); + Assert.AreEqual("__", ResearchStore.Safe("..")); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void SyntheticSplitKeepsTheAnchoredSeriesContinuousAndConvertsLevels() + { + // 2-for-1 split on day 50: real prices halve, the anchored adjusted series does not jump. + var adjustedTruth = Walk(80); + var exDay = adjustedTruth[50].Day; + var split = new CorporateAction("TEST", CorporateActionKinds.Split, exDay, "test", "split-1") { Ratio = 2m }; + var raw = adjustedTruth.Select((b, i) => i < 50 ? b with { Open = b.Open * 2, High = b.High * 2, Low = b.Low * 2, Close = b.Close * 2, Volume = b.Volume / 2 } : b).ToList(); + + // On the day before the split, nobody knew it: the anchored series is the real one. + var before = Adjustments.Anchored(raw, [split], exDay.AddDays(-1)); + Assert.HasCount(50, before); + Assert.IsTrue(before.All(b => b.Adjusted == b.Prices)); + + // From the ex-date on, older prices are halved and volumes doubled; the last price equals the real one. + var after = Adjustments.Anchored(raw, [split], raw[^1].Day); + Assert.AreEqual(raw[^1].Close, after[^1].Adjusted!.Value.Close); + for (var i = 0; i < after.Count; i++) + { + Assert.AreEqual(adjustedTruth[i].Close, after[i].Adjusted!.Value.Close, 1e-9); + Assert.AreEqual(adjustedTruth[i].Volume, after[i].Volume, 1e-9); + } + + // Saved levels and quantities across the split: a stop at 180 becomes 90, 3 shares become 6. + Assert.AreEqual(90m, Adjustments.ConvertLevel(180m, split, null)); + Assert.AreEqual(6m, Adjustments.ConvertQuantity(3m, split)); + var reverse = split with { Ratio = 0.1m }; + Assert.AreEqual(1800m, Adjustments.ConvertLevel(180m, reverse, null)); + Assert.AreEqual(0.3m, Adjustments.ConvertQuantity(3m, reverse)); + + // Without the corporate actions endpoint the split is recognised from the real and adjusted series. + var withSource = raw.Select((b, i) => b with { Adjusted = adjustedTruth[i].Prices }).ToList(); + var detected = Adjustments.Detect("TEST", withSource).Single(); + Assert.AreEqual((CorporateActionKinds.Split, exDay, (decimal?)2m), (detected.Kind, detected.ExDate, detected.Ratio)); + + // The backtest view at day 30 is the final adjusted series rescaled to the real price of day 30. + var view = Adjustments.RescaledAt(withSource, raw[30].Day); + Assert.HasCount(31, view); + Assert.AreEqual(raw[30].Close, view[^1].Close, 1e-9); + Assert.AreEqual(raw[10].Close, view[10].Close, 1e-9); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CashDividendsAdjustOlderPricesButNotQuantities() + { + var raw = Walk(10); + var exDay = raw[5].Day; + var dividend = new CorporateAction("TEST", CorporateActionKinds.CashDividend, exDay, "test", "div-1") { CashAmount = 1m }; + var closeBefore = raw[4].Close; + var anchored = Adjustments.Anchored(raw, [dividend], raw[^1].Day); + var factor = (closeBefore - 1) / closeBefore; + Assert.AreEqual(raw[4].Close * factor, anchored[4].Adjusted!.Value.Close, 1e-9); + Assert.AreEqual(raw[5].Close, anchored[5].Adjusted!.Value.Close); + Assert.AreEqual(raw[4].Volume, anchored[4].Volume, "a dividend does not touch volumes"); + Assert.AreEqual(5m, Adjustments.ConvertQuantity(5m, dividend)); + Assert.AreEqual(99m, Adjustments.ConvertLevel(100m, dividend, 100m)); + + var detected = Adjustments.Detect("TEST", anchored.Select((b, i) => raw[i] with { Adjusted = b.Adjusted }).ToList()).Single(); + Assert.AreEqual(CorporateActionKinds.CashDividend, detected.Kind); + Assert.AreEqual(1m, Math.Round(detected.CashAmount!.Value, 2)); + } +} diff --git a/tests/Anubis.Tests/MarketDataServerTests.cs b/tests/Anubis.Tests/MarketDataServerTests.cs new file mode 100644 index 0000000..1404628 --- /dev/null +++ b/tests/Anubis.Tests/MarketDataServerTests.cs @@ -0,0 +1,86 @@ +using System.Net; +using System.Text.Json; +using Anubis.Data; +using Anubis.Server; + +namespace Anubis.Tests; + +/// Market data inside the running server, on a fake network (issues #19, #20, #22). +[TestClass] +public sealed class MarketDataServerTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ServerCollectsWithoutAlpacaKeysAndSaysWhatIsOff() + { + var empty = """{"code":"0","msg":"","data":[]}"""; + var network = new FakeHttp() + .On("/api/v5/public/instruments?instType=SPOT", Fixture.Text("okx/instruments-spot.json")) + .On("candles", empty) + .On("/market/ticker?", Fixture.Text("okx/ticker-btc-eur.json")) + .On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network); + await server.SignInFirstTimeAsync(); + + var upcoming = server.Host.Services!.Scheduler.Upcoming(100).Select(u => u.Name).ToList(); + CollectionAssert.IsSubsetOf(new[] { "backup", "dati-storico", "dati-cambi-mattina", "dati-cambi-pomeriggio", "dati-calendario", "dati-umore", "dati-spread" }, + upcoming); + Assert.IsFalse(upcoming.Contains("dati-azioni-chiusura"), "without the broker's calendar the stock jobs have no time"); + + // The first history round runs at start: OKX answers, Alpaca is off for lack of the paper account keys. + JsonElement sources = default; + await OkxTests.WaitForAsync(() => + { + sources = JsonDocument.Parse(server.TextAsync("/api/data/sources").GetAwaiter().GetResult()).RootElement; + return sources.GetProperty("sources").EnumerateArray().Any(s => s.GetProperty("source").GetString() == MarketDataService.HistorySource); + }).ConfigureAwait(false); + Assert.IsTrue(sources.GetProperty("enabled").GetBoolean()); + var bySource = sources.GetProperty("sources").EnumerateArray().ToDictionary(s => s.GetProperty("source").GetString()!); + Assert.IsFalse(bySource[MarketDataService.AlpacaSource].GetProperty("enabled").GetBoolean()); + StringAssert.Contains(bySource[MarketDataService.AlpacaSource].GetProperty("note").GetString(), "ALPACA_API_KEY_DEMO"); + StringAssert.Contains(bySource[MarketDataService.OkxSource].GetProperty("note").GetString(), "3 nuovi"); + Assert.AreEqual(JsonValueKind.Null, bySource[MarketDataService.OkxSource].GetProperty("lastError").ValueKind); + Assert.IsTrue(network.Urls.All(u => u.Host is "eea.okx.com" or "data.binance.vision" or "nfs.faireconomy.media" or "www.ecb.europa.eu" + or "api.alternative.me" or "cdn.cboe.com"), string.Join(", ", network.Urls.Select(u => u.Host).Distinct())); + Assert.IsFalse(network.Urls.Any(u => u.Host.Contains("alpaca", StringComparison.Ordinal)), "no call to Alpaca without keys"); + + var report = await server.TextAsync("/api/data/quality?format=md"); + StringAssert.Contains(report, "# Qualità dei dati"); + StringAssert.Contains(report, "| alpaca | no |"); + + // The settings page says which source is off and why, and edits the central bank list. + var page = await server.TextAsync("/impostazioni"); + StringAssert.Contains(page, "Alpaca (azioni, conto di prova)"); + StringAssert.Contains(page, "mancano le chiavi del conto di prova Alpaca"); + StringAssert.Contains(page, "FED 2026-12-09"); + using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/calendar.central_banks", ("valore", "FED il 9 dicembre"), + ("ritorno", "/impostazioni#dati"))) + { + Assert.AreEqual("/impostazioni?errore=riunioni#dati", ServerHarness.Location(wrong)); + } + + using (var right = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/calendar.central_banks", ("valore", "FED 2027-01-27\r\nBCE 2027-02-04"), + ("ritorno", "/impostazioni#dati"))) + { + Assert.AreEqual("/impostazioni#dati", ServerHarness.Location(right)); + } + + StringAssert.Contains(await server.TextAsync("/impostazioni"), "BCE 2027-02-04"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task MarketDataStaysOffWhenSwitchedOff() + { + var env = ServerHarness.DockerSqlite(); + env["ANUBIS_MARKET_DATA"] = "off"; + var network = new FakeHttp(); + await using var server = await ServerHarness.StartAsync("docker", env, marketHttp: network); + await server.SignInFirstTimeAsync(); + Assert.IsNull(server.Host.Services!.MarketData); + Assert.IsFalse(server.Host.Services.Scheduler.Upcoming(100).Any(u => u.Name.StartsWith("dati-", StringComparison.Ordinal))); + var sources = JsonDocument.Parse(await server.TextAsync("/api/data/sources")).RootElement; + Assert.IsFalse(sources.GetProperty("enabled").GetBoolean()); + Assert.AreEqual(0, network.Requests.Count); + } +} diff --git a/tests/Anubis.Tests/MarketDataStoreTests.cs b/tests/Anubis.Tests/MarketDataStoreTests.cs new file mode 100644 index 0000000..7555ef2 --- /dev/null +++ b/tests/Anubis.Tests/MarketDataStoreTests.cs @@ -0,0 +1,119 @@ +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// Instrument catalogue, bar storage and the issue register on the engine of this run (issues #18, #20). +[TestClass] +public sealed class MarketDataStoreTests +{ + private static readonly DateTimeOffset _start = new(2026, 11, 10, 8, 0, 0, TimeSpan.Zero); + + internal static InstrumentSpec Okx(string symbol, string status = "live") => + new(Venues.Okx, symbol, symbol, AssetClasses.Crypto, "EUR") + { + BaseCurrency = symbol.Split('-')[0], + TickSize = 0.1m, + LotSize = 0.00000001m, + MinSize = 0.00001m, + Status = status, + ListedAt = new DateTimeOffset(2023, 11, 21, 4, 11, 0, TimeSpan.Zero), + }; + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task CatalogueAddsUpdatesAndKeepsDelistedInstruments() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var catalog = new InstrumentCatalog(test.Db, clock); + + var first = await catalog.SyncAsync(Venues.Okx, [Okx("BTC-EUR"), Okx("ETH-EUR")], complete: true, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(new InstrumentCatalog.SyncResult(2, 0, 0), first); + + var btc = await catalog.FindAsync(Venues.Okx, "BTC-EUR", CancellationToken.None).ConfigureAwait(false); + Assert.IsNotNull(btc); + Assert.AreEqual(0.00000001m, btc.Spec.LotSize, "the rules keep every decimal"); + Assert.AreEqual(Okx("BTC-EUR"), btc.Spec); + + // The next day the tick changes and ETH is gone from the list. + clock.Advance(TimeSpan.FromDays(1)); + var second = await catalog.SyncAsync(Venues.Okx, [Okx("BTC-EUR") with { TickSize = 1m }], complete: true, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(new InstrumentCatalog.SyncResult(0, 1, 1), second); + var eth = await catalog.FindAsync(Venues.Okx, "ETH-EUR", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(InstrumentCatalog.Delisted, eth!.Spec.Status); + Assert.IsFalse(eth.IsLive); + Assert.AreEqual(1m, (await catalog.GetAsync(btc.Id, CancellationToken.None).ConfigureAwait(false))!.Spec.TickSize); + + // Nothing changed: nothing is written. + Assert.AreEqual(new InstrumentCatalog.SyncResult(0, 0, 0), + await catalog.SyncAsync(Venues.Okx, [Okx("BTC-EUR") with { TickSize = 1m }], complete: true, CancellationToken.None).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DailyAndMinuteBarsRoundTripAndUpsert() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var instrument = await new InstrumentCatalog(test.Db, clock).EnsureAsync(Okx("BTC-EUR"), CancellationToken.None).ConfigureAwait(false); + var store = new BarStore(test.Db, clock); + var day = new DateOnly(2026, 11, 9); + + var bars = new[] + { + new DailyBar(day.AddDays(-1), 67000.1, 67500.25, 66000, 67082.7, 12.345678901) { QuoteVolume = 828_000.5 }, + new DailyBar(day, 67082.7, 68000, 66900.9, 67900, 10.5) { Adjusted = new Ohlc(1, 2, 0.5, 1.5) }, + }; + await store.UpsertDailyAsync(instrument.Id, bars, "okx", CancellationToken.None).ConfigureAwait(false); + var read = await store.DailyAsync(instrument.Id, day.AddDays(-5), day, CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(bars, read.ToArray()); + Assert.AreEqual(day, await store.LastDayAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false)); + Assert.AreEqual(day.AddDays(-1), await store.FirstDayAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false)); + + // A second download of the same day replaces it. + await store.UpsertDailyAsync(instrument.Id, [bars[1] with { Close = 67950, Quality = BarQuality.Confirmed }], "okx", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(2, await store.CountDailyAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false)); + var replaced = (await store.DailyAsync(instrument.Id, day, day, CancellationToken.None).ConfigureAwait(false)).Single(); + Assert.AreEqual(67950, replaced.Close); + Assert.AreEqual(BarQuality.Confirmed, replaced.Quality); + + var minute = new DateTimeOffset(2026, 11, 10, 7, 0, 0, TimeSpan.Zero); + var minutes = Enumerable.Range(0, 3).Select(i => new Bar(minute.AddMinutes(i), 1 + i, 2 + i, 0.5 + i, 1.5 + i, 3)).ToList(); + await store.UpsertMinuteAsync(instrument.Id, minutes, "okx", BarQuality.Ok, CancellationToken.None).ConfigureAwait(false); + await store.UpsertMinuteAsync(instrument.Id, minutes.Take(1), "okx", BarQuality.Ok, CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(minutes, (await store.MinuteAsync(instrument.Id, minute, minute.AddHours(1), CancellationToken.None).ConfigureAwait(false)).ToArray()); + Assert.AreEqual(minute.AddMinutes(2), await store.LastMinuteAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false)); + + // One-minute bars older than 400 days go. + clock.Set(minute.AddDays(400).AddMinutes(1).AddSeconds(30)); + Assert.AreEqual(2, await store.PruneMinutesAsync(CancellationToken.None).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task IssuesAreRecordedOnceAndBlockEntriesUntilResolved() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var instrument = await new InstrumentCatalog(test.Db, clock).EnsureAsync(Okx("SOL-EUR"), CancellationToken.None).ConfigureAwait(false); + var issues = new DataIssueStore(test.Db, clock); + var at = new DateTimeOffset(2026, 11, 9, 0, 0, 0, TimeSpan.Zero); + var jump = new QualityFinding(IssueKinds.Jump, at, at, "salto"); + + var id = await issues.RecordAsync(instrument.Id, Timeframes.Day, jump, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(id, await issues.RecordAsync(instrument.Id, Timeframes.Day, jump, CancellationToken.None).ConfigureAwait(false), "the same open finding is not added twice"); + await issues.RecordAsync(null, Timeframes.Minute, new QualityFinding(IssueKinds.Gap, at, at.AddMinutes(9), "buco"), CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEquivalent(new[] { instrument.Id }, (await issues.BlockedInstrumentsAsync(CancellationToken.None).ConfigureAwait(false)).ToArray()); + + await issues.AttemptAsync(id, CancellationToken.None).ConfigureAwait(false); + await issues.ResolveAsync(id, IssueStatus.Confirmed, null, CancellationToken.None).ConfigureAwait(false); + Assert.IsEmpty(await issues.BlockedInstrumentsAsync(CancellationToken.None).ConfigureAwait(false)); + var all = await issues.SinceAsync(at, CancellationToken.None).ConfigureAwait(false); + Assert.HasCount(2, all); + var resolved = all.Single(i => i.Id == id); + Assert.AreEqual(1, resolved.Attempts); + Assert.AreEqual(IssueStatus.Confirmed, resolved.Status); + Assert.AreEqual("salto", resolved.Detail); + } +} diff --git a/tests/Anubis.Tests/OkxTests.cs b/tests/Anubis.Tests/OkxTests.cs new file mode 100644 index 0000000..ae5210c --- /dev/null +++ b/tests/Anubis.Tests/OkxTests.cs @@ -0,0 +1,293 @@ +using System.Security.Cryptography; +using System.Text; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// The data part of the OKX Europe adapter on recorded responses (issue #18). +[TestClass] +public sealed class OkxTests +{ + private static readonly DateTimeOffset _now = new(2026, 11, 10, 13, 45, 0, TimeSpan.Zero); + + private static (OkxClient Client, FakeHttp Http) Create(Action setup, IClock? clock = null, OkxOptions? options = null) + { + var http = new FakeHttp(); + setup(http); + return (new OkxClient(http.Client(), clock ?? new FastClock(_now), options), http); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task InstrumentsAreOnlyEuroPairsWithTheirRules() + { + var (okx, http) = Create(h => h.On("/api/v5/public/instruments?instType=SPOT", Fixture.Text("okx/instruments-spot.json"))); + var list = await okx.ListInstrumentsAsync(CancellationToken.None).ConfigureAwait(false); + + // USDT is not tradable in Europe (trap 14); USDC and PLN pairs are not used (SPEC 8.1). + CollectionAssert.AreEqual(new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR" }, list.Select(i => i.Symbol).ToArray()); + var btc = list[0]; + Assert.AreEqual(new InstrumentSpec(Venues.Okx, "BTC-EUR", "BTC/EUR", AssetClasses.Crypto, "EUR") + { + BaseCurrency = "BTC", + TickSize = 0.1m, + LotSize = 0.00000001m, + MinSize = 0.0001m, + Status = "live", + ListedAt = new DateTimeOffset(2023, 11, 21, 4, 11, 0, TimeSpan.Zero), + }, btc); + Assert.IsTrue(http.Requests.All(r => r.RequestUri!.Host == "eea.okx.com"), "the European host"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task DailyCandlesCloseAtMidnightUtcAndSkipTheRunningDay() + { + var (okx, http) = Create(h => h.On("history-candles", Fixture.Text("okx/candles-1Dutc-btc-eur.json"))); + var bars = await okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2026, 11, 6), new DateOnly(2026, 11, 10), CancellationToken.None).ConfigureAwait(false); + + var request = http.Requests.Single().RequestUri!.ToString(); + StringAssert.Contains(request, "bar=1Dutc", "never 1D, which opens at 16:00 UTC (trap 23)"); + StringAssert.Contains(request, "after=" + new DateTimeOffset(2026, 11, 11, 0, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds()); + + // 10 November is still running (confirm 0) and is left out. + CollectionAssert.AreEqual( + new[] { new DateOnly(2026, 11, 6), new DateOnly(2026, 11, 7), new DateOnly(2026, 11, 8), new DateOnly(2026, 11, 9) }, + bars.Select(b => b.Day).ToArray()); + var last = bars[^1]; + Assert.AreEqual((67102.9, 67730.8, 65957.5, 67058.9, 87.03419039), (last.Open, last.High, last.Low, last.Close, last.Volume)); + Assert.AreEqual(5799147.867285542, last.QuoteVolume); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task HistoryPagesBackwardsUntilTheFirstCandle() + { + var first = new DateTimeOffset(2023, 11, 21, 0, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds(); + var (okx, http) = Create(h => h + .On("after=" + first, """{"code":"0","data":[],"msg":""}""") + .On("history-candles", Fixture.Text("okx/history-candles-1Dutc-btc-eur-first.json"))); + var bars = await okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2017, 1, 1), new DateOnly(2023, 11, 25), CancellationToken.None).ConfigureAwait(false); + + Assert.HasCount(2, http.Requests, "the second page is empty: the history starts on 21 November 2023"); + Assert.AreEqual(new DateOnly(2023, 11, 21), bars[0].Day); + Assert.AreEqual(new DateOnly(2023, 11, 25), bars[^1].Day); + Assert.HasCount(5, bars); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task ACandleThatDoesNotOpenAtMidnightIsRefused() + { + var sixteen = new DateTimeOffset(2026, 11, 8, 16, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds(); + var (okx, _) = Create(h => h.On("history-candles", $$"""{"code":"0","data":[["{{sixteen}}","1","2","0.5","1.5","3","4","4","1"]],"msg":""}""")); + var error = await Assert.ThrowsAsync(() => + okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2026, 11, 8), new DateOnly(2026, 11, 8), CancellationToken.None)).ConfigureAwait(false); + StringAssert.Contains(error.Message, "16:00"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task MinuteCandlesUseTheRecentEndpointForTheLastDay() + { + var (okx, http) = Create(h => h.On("/market/candles?", Fixture.Text("okx/candles-1m-btc-eur.json"))); + var start = DateTimeOffset.FromUnixTimeMilliseconds(1794318000000); + var bars = await okx.FetchMinuteBarsAsync("BTC-EUR", start, start.AddMinutes(5), CancellationToken.None).ConfigureAwait(false); + Assert.HasCount(4, bars, "the running minute is left out"); + Assert.AreEqual(start, bars[0].OpensAt); + StringAssert.Contains(http.Requests[0].RequestUri!.ToString(), "bar=1m"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task ErrorsArriveWithStatus200AndBusyAnswersAreRetried() + { + var calls = 0; + var clock = new FastClock(_now); + var (okx, _) = Create(h => h.On(_ => true, _ => ++calls == 1 + ? FakeHttp.Respond("""{"code":"50011","data":[],"msg":"Rate limit reached"}""") + : FakeHttp.Respond(Fixture.Text("okx/ticker-btc-eur.json"))), clock); + var quote = await okx.FetchQuoteAsync("BTC-EUR", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(2, calls); + Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(2), clock.Waited, "waits before trying again"); + Assert.AreEqual((65986.1m, 65998.6m), (quote.Bid, quote.Ask)); + Assert.AreEqual(0.02600011m, quote.BidSize); + Assert.AreEqual(DateTimeOffset.FromUnixTimeMilliseconds(1794318312368), quote.At); + Assert.AreEqual(1.894, quote.SpreadBp!.Value, 0.001); + + var (unknown, _) = Create(h => h.On("ticker", """{"code":"51001","data":[],"msg":"Instrument ID, Instrument ID code, or Spread ID doesn't exist."}""")); + var error = await Assert.ThrowsAsync(() => unknown.FetchQuoteAsync("XXX-EUR", CancellationToken.None)).ConfigureAwait(false); + Assert.IsFalse(error.Retryable); + StringAssert.Contains(error.Message, "51001"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task DemoAddsTheSimulatedTradingHeader() + { + var (okx, http) = Create(h => h.On("ticker", Fixture.Text("okx/ticker-btc-eur.json")), options: OkxOptions.ForDemo()); + await okx.FetchQuoteAsync("BTC-EUR", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("1", http.Requests[0].Headers.GetValues("x-simulated-trading").Single()); + Assert.AreEqual("wseeapap.okx.com", OkxOptions.ForDemo().BusinessStreamUrl.Host); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task FundingRateAndOpenInterestOfBitcoin() + { + var (okx, _) = Create(h => h + .On("funding-rate", Fixture.Text("okx/funding-rate-btc.json")) + .On("open-interest", Fixture.Text("okx/open-interest-btc.json"))); + var funding = await okx.FetchFundingRateAsync("BTC-USDT-SWAP", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(-0.0000009390698834, funding.Rate); + Assert.AreEqual(TimeSpan.FromHours(8), funding.Interval); + var interest = await okx.FetchOpenInterestAsync("BTC-USDT-SWAP", CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(36006.7700000001675, interest.Coins, 1e-6); + Assert.AreEqual(2659809297.869, interest.Usd, 0.01); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void SignatureIsHmacSha256OfTimestampMethodPathAndBody() + { + var at = new DateTimeOffset(2026, 11, 10, 13, 45, 1, 234, TimeSpan.Zero); + var credentials = new OkxCredentials("key-id", "secret-value", "pass-phrase"); + var headers = OkxSigner.Headers(credentials, at, "get", "/api/v5/account/balance?ccy=EUR", "", demo: true); + Assert.AreEqual("2026-11-10T13:45:01.234Z", headers["OK-ACCESS-TIMESTAMP"]); + var expected = Convert.ToBase64String(HMACSHA256.HashData(Encoding.UTF8.GetBytes("secret-value"), + Encoding.UTF8.GetBytes("2026-11-10T13:45:01.234ZGET/api/v5/account/balance?ccy=EUR"))); + Assert.AreEqual(expected, headers["OK-ACCESS-SIGN"]); + Assert.AreEqual("1", headers["x-simulated-trading"]); + Assert.AreEqual("OkxCredentials(***)", credentials.ToString(), "never printed"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task StreamSubscribesTickersAndCandlesOnTheirHostsAndPingsWhenSilent() + { + var clock = new ManualClock(_now); + var sockets = new List(); + var okx = new OkxClient(new FakeHttp().Client(), clock, sockets: () => + { + var socket = new FakeSocket(); + lock (sockets) + { + sockets.Add(socket); + } + + return socket; + }); + + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + var events = new List(); + var reading = Task.Run(async () => + { + await foreach (var item in okx.StreamAsync(["BTC-EUR", "ETH-EUR"], stop.Token).ConfigureAwait(false)) + { + lock (events) + { + events.Add(item); + } + } + }); + + await WaitForAsync(() => sockets.Count == 2 && sockets.All(s => s.Sent.Count == 1)).ConfigureAwait(false); + var publicSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/public", StringComparison.Ordinal)); + var businessSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/business", StringComparison.Ordinal)); + StringAssert.Contains(publicSocket.Sent[0], "\"channel\":\"tickers\",\"instId\":\"ETH-EUR\""); + StringAssert.Contains(businessSocket.Sent[0], "\"channel\":\"candle1m\",\"instId\":\"BTC-EUR\""); + + publicSocket.Push("""{"id":"1","event":"subscribe","arg":{"channel":"tickers","instId":"BTC-EUR"},"connId":"53efe456"}"""); + publicSocket.Push("""{"arg":{"channel":"tickers","instId":"BTC-EUR"},"data":[{"instType":"SPOT","instId":"BTC-EUR","last":"66148.9","lastSz":"0.00010133","askPx":"66134.7","askSz":"0.01847","bidPx":"66129.6","bidSz":"0.0193605","ts":"1794318514123"}]}"""); + businessSocket.Push("""{"arg":{"channel":"candle1m","instId":"BTC-EUR"},"data":[["1794318180000","65999.8","66069.8","65999.8","66050.5","0.0523422","3457.08","3457.08","1"]]}"""); + await WaitForAsync(() => events.Count == 2).ConfigureAwait(false); + var quote = events.OfType().Single().Quote; + Assert.AreEqual((66129.6m, 66134.7m), (quote.Bid, quote.Ask)); + var bar = events.OfType().Single(); + Assert.IsTrue(bar.Closed); + Assert.AreEqual(66050.5, bar.Bar.Close); + + // Twenty seconds of silence: "ping". The public side answers, the business side does not and is dropped. + await WaitForAsync(() => clock.Waiting >= 2).ConfigureAwait(false); + clock.Advance(TimeSpan.FromSeconds(21)); + await WaitForAsync(() => publicSocket.Sent.Contains("ping") && businessSocket.Sent.Contains("ping")).ConfigureAwait(false); + publicSocket.Push("pong"); + await WaitForAsync(() => clock.Waiting >= 2).ConfigureAwait(false); + clock.Advance(TimeSpan.FromSeconds(21)); + await reading.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + Assert.IsTrue(sockets.All(s => s.Disposed), "both connections are closed when the feed ends"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task OneConnectionDroppingEndsTheFeedWithoutAnError() + { + var sockets = new List(); + var okx = new OkxClient(new FakeHttp().Client(), new ManualClock(_now), sockets: () => + { + var socket = new FakeSocket(); + lock (sockets) + { + sockets.Add(socket); + } + + return socket; + }); + + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + var reading = Task.Run(async () => + { + await foreach (var item in okx.StreamAsync(["BTC-EUR"], stop.Token).ConfigureAwait(false)) + { + await Task.Delay(1).ConfigureAwait(false); // A slow reader: tickers pile up in the channel. + } + }); + + await WaitForAsync(() => sockets.Count == 2 && sockets.All(s => s.Sent.Count == 1)).ConfigureAwait(false); + var publicSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/public", StringComparison.Ordinal)); + var businessSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/business", StringComparison.Ordinal)); + const string ticker = """{"arg":{"channel":"tickers","instId":"BTC-EUR"},"data":[{"instType":"SPOT","instId":"BTC-EUR","last":"66148.9","askPx":"66134.7","askSz":"0.01847","bidPx":"66129.6","bidSz":"0.0193605","ts":"1794318514123"}]}"""; + for (var i = 0; i < 300; i++) + { + publicSocket.Push(ticker); + } + + // The candle connection drops while tickers keep arriving: the feed ends cleanly, so the collector marks it + // down and reconnects, instead of failing on a write to the closed feed. + businessSocket.Close(); + for (var i = 0; i < 300; i++) + { + publicSocket.Push(ticker); + } + + await reading.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + Assert.IsTrue(sockets.All(s => s.Disposed)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void StreamErrorsStopTheFeed() + { + var error = Assert.Throws(() => OkxClient.ParseStreamMessage( + """{"event":"error","msg":"Subscribe failed, wrong URL or channel:candle1m,instId:BTC-EUR doesn't exist.","code":"60018","connId":"53efe456","id":"2"}""")); + StringAssert.Contains(error.Message, "60018"); + Assert.IsEmpty(OkxClient.ParseStreamMessage("""{"event":"notice","msg":"WebSocket port 8443 will be retired soon.","code":"64010"}""")); + } + + internal static async Task WaitForAsync(Func condition) + { + // Generous: on a busy machine (CI, PostgreSQL in Docker) the first backfill alone can take several seconds. + var deadline = DateTime.UtcNow.AddSeconds(30); + while (!condition()) + { + if (DateTime.UtcNow > deadline) + { + Assert.Fail("Condition not reached in time."); + } + + await Task.Delay(10).ConfigureAwait(false); + } + } +} diff --git a/tests/Anubis.Tests/RealHistoryProof.cs b/tests/Anubis.Tests/RealHistoryProof.cs new file mode 100644 index 0000000..ad98a97 --- /dev/null +++ b/tests/Anubis.Tests/RealHistoryProof.cs @@ -0,0 +1,76 @@ +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The Phase 2 proof on the real public sources (no keys): the whole daily history of the main OKX EUR pairs and the +/// Binance BTCUSDT archives since 2017, then the quality report. Needs the network, so it runs only when asked: +/// ANUBIS_LIVE_PROOF=1 and dotnet test --filter FullyQualifiedName~RealHistoryProof. With ANUBIS_PROOF_OUT set, +/// the report is written there. +/// +[TestClass] +public sealed class RealHistoryProof +{ + [TestMethod] + [TestCategory(Category.LiveDemo)] + public async Task DownloadsTheRealDailyHistoryAndReportsItsQuality() + { + if (Environment.GetEnvironmentVariable("ANUBIS_LIVE_PROOF") != "1") + { + Assert.Inconclusive("Needs the network: set ANUBIS_LIVE_PROOF=1 to run it."); + } + + var clock = new SystemClock(); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + var okx = new OkxClient(http, clock); + var bus = new EventBus(); + var catalog = new InstrumentCatalog(test.Db, clock); + var sync = await catalog.SyncAsync(Venues.Okx, await okx.ListInstrumentsAsync(CancellationToken.None).ConfigureAwait(false), complete: true, + CancellationToken.None).ConfigureAwait(false); + Assert.IsTrue(sync.Added >= 20, $"OKX Europe lists {sync.Added} EUR pairs"); + + var collector = new MarketCollector(okx, test.Db, clock, bus, new FreshnessMonitor(clock, bus)); + var bars = new BarStore(test.Db, clock); + var lines = new List(); + foreach (var symbol in MarketDataService.CoreCrypto) + { + var instrument = (await catalog.FindAsync(Venues.Okx, symbol, CancellationToken.None).ConfigureAwait(false))!; + var result = await collector.BackfillDailyAsync(instrument, MarketDataService.HistoryFrom, CancellationToken.None).ConfigureAwait(false); + var first = await bars.FirstDayAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false); + var last = await bars.LastDayAsync(instrument.Id, CancellationToken.None).ConfigureAwait(false); + lines.Add($"{symbol}: {result.Stored} giorni dal {first:yyyy-MM-dd} al {last:yyyy-MM-dd}, buchi {result.Gaps}, anomalie {result.Suspect}"); + Assert.IsTrue(first <= new DateOnly(2023, 12, 31), $"{symbol} starts on {first}"); + Assert.AreEqual(DateOnly.FromDateTime(clock.UtcNow.UtcDateTime).AddDays(-1), last); + } + + var folder = TempFolder.Create("proof"); + try + { + var research = new ResearchStore(folder); + var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), research, clock); + var binance = await importer.ImportAsync("BTCUSDT", "1d", 2017, 8, CancellationToken.None).ConfigureAwait(false); + lines.Add($"Binance BTCUSDT 1d: {binance.Bars} giorni dal {binance.First:yyyy-MM-dd} al {binance.Last:yyyy-MM-dd}; {string.Join("; ", binance.Notes)}"); + Assert.AreEqual(new DateTimeOffset(2017, 8, 17, 0, 0, 0, TimeSpan.Zero), binance.First, "the first Binance day"); + Assert.IsTrue(binance.Bars > 3000); + var years = research.Years(Venues.Binance, "BTCUSDT", Timeframes.Day); + lines.Add($"File di ricerca: {years.Count} anni, {string.Join(", ", years.Select(y => new FileInfo(research.PathFor(Venues.Binance, "BTCUSDT", Timeframes.Day, y)).Length / 1024 + " KB"))}"); + } + finally + { + TempFolder.Delete(folder); + } + + var report = await QualityReport.BuildAsync(test.Db, clock, TimeSpan.FromDays(1), CancellationToken.None).ConfigureAwait(false); + var text = "## Scaricamento reale\n\n" + string.Join("\n", lines.Select(l => "- " + l)) + "\n\n" + report.ToMarkdown(); + if (Environment.GetEnvironmentVariable("ANUBIS_PROOF_OUT") is { Length: > 0 } path) + { + await File.WriteAllTextAsync(path, text).ConfigureAwait(false); + } + + Console.WriteLine(text); + } +} diff --git a/tests/Anubis.Tests/ReferenceSourcesTests.cs b/tests/Anubis.Tests/ReferenceSourcesTests.cs new file mode 100644 index 0000000..b9ad7e4 --- /dev/null +++ b/tests/Anubis.Tests/ReferenceSourcesTests.cs @@ -0,0 +1,431 @@ +using System.IO.Compression; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// Readers of the free sources on recorded responses, their stores, and the research importers (issues #21, #22, #24). +[TestClass] +public sealed class ReferenceSourcesTests +{ + private static readonly DateTimeOffset _start = new(2026, 11, 10, 8, 0, 0, TimeSpan.Zero); + + [TestMethod] + [TestCategory(Category.Unit)] + public void EcbDailyNinetyDayAndHistoryFilesGiveTheSameRates() + { + string[] wanted = ["USD", "GBP", "BGN"]; + var daily = Ecb.ParseXml(Fixture.Text("free/ecb-daily.xml"), wanted); + Assert.AreEqual(2, daily.Count, "BGN is no longer published"); + Assert.AreEqual(new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.1193m, Ecb.Source), daily.Single(r => r.Quote == "USD")); + Assert.AreEqual(0.83430m, daily.Single(r => r.Quote == "GBP").Rate); + + var ninety = Ecb.ParseXml(Fixture.Text("free/ecb-hist-90d.xml"), ["USD"]); + Assert.IsTrue(ninety.Count > 1); + Assert.AreEqual(1.1193m, ninety.Single(r => r.Date == new DateOnly(2026, 11, 9)).Rate, "the 90-day file uses double quotes"); + CollectionAssert.AreEqual(ninety.OrderBy(r => r.Date).ToList(), ninety.ToList(), "oldest first"); + + var history = Ecb.ParseHistoryCsv(Fixture.Text("free/ecb-hist.csv"), wanted); + Assert.AreEqual(4, history.Count, "N/A is skipped and the trailing comma ignored"); + Assert.AreEqual(new DateOnly(2026, 11, 6), history[0].Date); + Assert.AreEqual(1.1165m, history.Single(r => r.Quote == "USD" && r.Date == new DateOnly(2026, 11, 6)).Rate); + + using var zip = new MemoryStream(); + using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) + using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open())) + { + writer.Write(Fixture.Text("free/ecb-hist.csv")); + } + + Assert.AreEqual(Fixture.Text("free/ecb-hist.csv"), Ecb.ExtractHistoryCsv(zip.ToArray())); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ForexFactoryEventsKeepTheirTimeAndHolidaysOnlyTheDay() + { + var events = ForexFactory.Parse(Fixture.Text("free/ff-calendar.json")); + Assert.AreEqual(5, events.Count); + var cpi = events.Single(e => e.Title == "CPI m/m"); + Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 13, 30, 0, TimeSpan.Zero), cpi.OccursAt, "the offset -05:00 becomes UTC"); + Assert.AreEqual("USD", cpi.Currency); + Assert.AreEqual("High", cpi.Impact); + Assert.AreEqual("0.3%", cpi.Forecast); + Assert.AreEqual("0.6%", cpi.Previous); + Assert.IsTrue(cpi.TimeKnown); + + var holiday = events.Single(e => e.Title == "Bank Holiday"); + Assert.AreEqual(CalendarEventKinds.Holiday, holiday.Kind); + Assert.IsFalse(holiday.TimeKnown); + Assert.IsNull(holiday.Impact); + Assert.IsNull(events.Single(e => e.Title == "RBA Assist Gov Hunter Speaks").Forecast, "an empty forecast is no forecast"); + Assert.AreEqual(events.Count, events.Select(e => e.SourceKey).Distinct().Count()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void FredFinnhubAndCentralBankDatesBecomeTimedEvents() + { + var fred = Fred.Parse(Fixture.Text("free/fred-release-dates.json"), "PIL USA", new DateOnly(2010, 1, 1)); + Assert.AreEqual(4, fred.Count, "dates before the start are skipped"); + Assert.AreEqual(new DateTimeOffset(2010, 2, 11, 13, 30, 0, TimeSpan.Zero), fred[0].OccursAt, "08:30 New York in winter"); + Assert.AreEqual("fred:82:2010-02-11", fred[0].SourceKey); + Assert.AreEqual(new DateTimeOffset(2012, 10, 24, 12, 30, 0, TimeSpan.Zero), fred[2].OccursAt, "08:30 New York in summer time"); + StringAssert.Contains(Fred.ReleaseDates(10, "k", new DateOnly(2026, 11, 10)).Query, "include_release_dates_with_no_data=true"); + + var earnings = Finnhub.Parse(Fixture.Text("free/finnhub-earnings.json")); + Assert.AreEqual(2, earnings.Count); + var aapl = earnings.Single(e => e.OccursAt.Year == 2020); + Assert.AreEqual(new DateTimeOffset(2020, 1, 28, 21, 5, 0, TimeSpan.Zero), aapl.OccursAt, "amc: 16:05 New York"); + Assert.AreEqual("amc", aapl.TimeHint); + Assert.AreEqual("AAPL", aapl.Symbol); + Assert.AreEqual(0, Finnhub.Parse(Fixture.Text("free/finnhub-earnings.json"), new HashSet { "MSFT" }).Count); + + var banks = CentralBanks.Parse(CentralBanks.DefaultList); + Assert.AreEqual(18, banks.Count); + var fed = banks.Single(e => e.SourceKey == "cb:USD:2026-12-09"); + Assert.AreEqual(new DateTimeOffset(2026, 12, 9, 19, 0, 0, TimeSpan.Zero), fed.OccursAt, "14:00 New York"); + var ecb = banks.Single(e => e.SourceKey == "cb:EUR:2027-07-22"); + Assert.AreEqual(new DateTimeOffset(2027, 7, 22, 12, 15, 0, TimeSpan.Zero), ecb.OccursAt, "14:15 Frankfurt in summer time"); + + // Every decision day of the default list is in the official calendars read for the fixture. + var official = Fixture.Text("free/central-banks.md"); + foreach (var e in banks) + { + StringAssert.Contains(official, $"| {e.OccursAt:yyyy-MM-dd} |"); + } + + Assert.AreEqual(1, CentralBanks.Parse("# commento\n\nfed 2027-01-27\n").Count); + var error = Assert.ThrowsExactly(() => CentralBanks.Parse("FED 2027-01-27\nBOJ 2027-01-28")); + StringAssert.Contains(error.Message, "Riga 2"); + Assert.ThrowsExactly(() => CentralBanks.Parse("FED 27/01/2027")); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MoodReadingsCarryTheLabelsOfTheSpec() + { + var fng = FearGreed.Parse(Fixture.Text("free/fng.json")); + Assert.AreEqual(2, fng.Count); + Assert.AreEqual(32d, fng[^1].Value, "oldest first: the latest reading is last"); + Assert.AreEqual("paura", fng[^1].Label); + Assert.AreEqual(DateTimeOffset.FromUnixTimeSeconds(1794268800), fng[^1].AsOf); + + var vix = VixHistory.Parse(Fixture.Text("free/vix.csv"), new DateOnly(2026, 1, 1)); + Assert.AreEqual(2, vix.Count); + Assert.AreEqual(new DateTimeOffset(2026, 11, 9, 0, 0, 0, TimeSpan.Zero), vix[1].AsOf); + Assert.AreEqual(("nervoso", "calmo"), (vix[0].Label, vix[1].Label)); + + Assert.AreEqual("paura estrema", MoodLabels.FearGreed(24)); + Assert.AreEqual("neutro", MoodLabels.FearGreed(55)); + Assert.AreEqual("avidità estrema", MoodLabels.FearGreed(76)); + Assert.AreEqual("panico", MoodLabels.Vix(30.01)); + Assert.AreEqual("troppi al rialzo", MoodLabels.Funding(0.0003, TimeSpan.FromHours(8))); + Assert.AreEqual("troppi al rialzo", MoodLabels.Funding(0.00015, TimeSpan.FromHours(4)), "4-hour funding counts double"); + Assert.AreEqual("nella norma", MoodLabels.Funding(-0.0001, TimeSpan.FromHours(8))); + Assert.AreEqual("troppi al ribasso", MoodLabels.Funding(-0.00021, TimeSpan.FromHours(8))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NasdaqListExcludesFundsAndEverythingThatIsNotACommonShare() + { + var list = NasdaqTraded.Parse(Fixture.Text("free/nasdaqtraded.txt")); + Assert.AreEqual(12, list.Count, "header and footer skipped"); + var excluded = list.Where(s => s.IsExcluded).Select(s => s.Symbol).ToList(); + CollectionAssert.AreEquivalent(new[] { "SPY", "BULZ", "AMUB", "PDI", "ABR$D", "AACIW", "ZXIET" }, excluded); + Assert.AreEqual("TXSE", list.Single(s => s.Symbol == "CECO").Exchange); + Assert.AreEqual("NASDAQ", list.Single(s => s.Symbol == "AAPL").Exchange); + Assert.AreEqual("NYSE", list.Single(s => s.Symbol == "KO").Exchange); + Assert.AreEqual("D", list.Single(s => s.Symbol == "AACG").FinancialStatus); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void BinanceArchivesReadMillisecondsAndMicrosecondsAndCheckTheirFingerprint() + { + var old = BinanceArchive.ParseCsv(Fixture.Text("free/binance-BTCUSDT-1d-2017-08.csv")); + var recent = BinanceArchive.ParseCsv(Fixture.Text("free/binance-BTCUSDT-1d-2025-01.csv")); + Assert.AreEqual(5, old.Count); + Assert.AreEqual(new DateTimeOffset(2017, 8, 17, 0, 0, 0, TimeSpan.Zero), old[0].OpensAt); + Assert.AreEqual(4261.48m, old[0].Open); + Assert.AreEqual(3454770.05073206m, old[0].QuoteVolume); + Assert.AreEqual(3427L, old[0].Trades); + Assert.AreEqual(new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), recent[0].OpensAt, "microseconds from 2025"); + Assert.AreEqual(new DateTimeOffset(2025, 1, 5, 0, 0, 0, TimeSpan.Zero), recent[^1].OpensAt); + + var zip = Zip("BTCUSDT-1d-2017-08.csv", Fixture.Text("free/binance-BTCUSDT-1d-2017-08.csv")); + var checksum = Convert.ToHexStringLower(SHA256.HashData(zip)) + " BTCUSDT-1d-2017-08.zip\n"; + Assert.IsTrue(BinanceArchive.Verify(zip, checksum)); + Assert.IsFalse(BinanceArchive.Verify(zip, Fixture.Text("free/BTCUSDT-1d-2017-08.zip.CHECKSUM")), "the recorded checksum belongs to the real zip"); + CollectionAssert.AreEqual(old.ToList(), BinanceArchive.ReadZip(zip).ToList()); + Assert.AreEqual( + new Uri("https://data.binance.vision/data/spot/monthly/klines/BTCUSDT/1d/BTCUSDT-1d-2017-08.zip.CHECKSUM"), + BinanceArchive.ChecksumOf(BinanceArchive.Monthly("BTCUSDT", "1d", 2017, 8))); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ReferenceStoresRoundTripOnTheEngineOfThisRun() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + + var fx = new FxStore(test.Db, clock); + await fx.UpsertAsync(Ecb.ParseHistoryCsv(Fixture.Text("free/ecb-hist.csv"), ["USD"]), CancellationToken.None).ConfigureAwait(false); + await fx.UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.1194m, Ecb.Source)], CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(1.1194m, (await fx.LatestAsync("EUR", "USD", CancellationToken.None).ConfigureAwait(false))!.Rate, "a new publication replaces the old"); + Assert.AreEqual(1.1165m, (await fx.RateOnAsync("EUR", "USD", new DateOnly(2026, 11, 8), CancellationToken.None).ConfigureAwait(false))!.Rate, + "Sunday uses Friday's rate"); + Assert.IsNull(await fx.RateOnAsync("EUR", "USD", new DateOnly(2026, 11, 5), CancellationToken.None).ConfigureAwait(false)); + + var calendar = new CalendarEventStore(test.Db, clock); + var events = ForexFactory.Parse(Fixture.Text("free/ff-calendar.json")); + Assert.AreEqual(5, await calendar.UpsertAsync(events, CancellationToken.None).ConfigureAwait(false)); + var moved = events.Single(e => e.Title == "CPI m/m") with { Forecast = "0.4%" }; + await calendar.UpsertAsync([moved], CancellationToken.None).ConfigureAwait(false); + var week = await calendar.BetweenAsync(new DateTimeOffset(2026, 11, 10, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2026, 11, 17, 0, 0, 0, TimeSpan.Zero), + CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(3, week.Count); + Assert.AreEqual(moved, week[0]); + Assert.IsFalse(week.Single(e => e.Kind == CalendarEventKinds.Holiday).TimeKnown); + + var mood = new MoodStore(test.Db, clock); + await mood.UpsertAsync(FearGreed.Parse(Fixture.Text("free/fng.json")), CancellationToken.None).ConfigureAwait(false); + await mood.UpsertAsync(FearGreed.Parse(Fixture.Text("free/fng.json")), CancellationToken.None).ConfigureAwait(false); + var latest = await mood.LatestAsync(MoodIndicators.FearGreed, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(32d, latest!.Value); + Assert.AreEqual("paura", latest.Label); + Assert.IsNull(await mood.LatestAsync(MoodIndicators.Vix, CancellationToken.None).ConfigureAwait(false)); + + var states = new SourceStateStore(test.Db, clock); + await states.RecordAsync(Finnhub.Source, enabled: false, success: false, null, "manca la chiave FINNHUB_API_KEY", CancellationToken.None).ConfigureAwait(false); + await states.RecordAsync(Ecb.Source, enabled: true, success: true, null, null, CancellationToken.None).ConfigureAwait(false); + clock.Advance(TimeSpan.FromHours(1)); + await states.RecordAsync(Ecb.Source, enabled: true, success: false, "timeout", null, CancellationToken.None).ConfigureAwait(false); + var list = await states.ListAsync(CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(2, list.Count); + var ecb = list.Single(s => s.Source == Ecb.Source); + Assert.AreEqual(_start, ecb.LastSuccessAt, "a failure keeps the last success"); + Assert.AreEqual(_start.AddHours(1), ecb.LastRequestAt); + Assert.AreEqual("timeout", ecb.LastError); + Assert.IsFalse(list.Single(s => s.Source == Finnhub.Source).Enabled); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task StoredMarketCalendarKeepsOpenAndClosedDaysAcrossRestarts() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var calendar = new StoredMarketCalendar(test.Db, clock, "us_equity"); + Assert.IsNull(calendar.Coverage); + + var friday = new DateOnly(2026, 11, 13); + var monday = new DateOnly(2026, 11, 16); + MarketSession Session(DateOnly day) => new(day, Zones.At(day, new TimeOnly(9, 30), Zones.NewYork), Zones.At(day, new TimeOnly(16, 0), Zones.NewYork)); + await calendar.SaveAsync([Session(friday), Session(monday)], friday, monday, CancellationToken.None).ConfigureAwait(false); + + var reloaded = new StoredMarketCalendar(test.Db, clock, "us_equity"); + await reloaded.LoadAsync(CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual((friday, monday), reloaded.Coverage); + Assert.AreEqual(Session(friday), reloaded.SessionOn(friday)); + Assert.IsNull(reloaded.SessionOn(friday.AddDays(1)), "Saturday is closed"); + Assert.IsTrue(reloaded.Covers(friday.AddDays(1))); + Assert.IsFalse(reloaded.Covers(monday.AddDays(1)), "a day not downloaded is unknown, not closed"); + Assert.AreEqual(2, reloaded.Sessions(friday, monday).Count); + Assert.AreEqual(new DateTimeOffset(2026, 11, 13, 14, 30, 0, TimeSpan.Zero), reloaded.SessionOn(friday)!.OpenUtc); + + var other = new StoredMarketCalendar(test.Db, clock, "other"); + await other.LoadAsync(CancellationToken.None).ConfigureAwait(false); + Assert.IsNull(other.Coverage, "each market has its own calendar"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task BinanceImporterChecksEachArchiveAndStopsAtTheFirstMissingMonth() + { + var folder = TempFolder.Create("binance"); + try + { + var august = Zip("BTCUSDT-1d-2017-08.csv", Fixture.Text("free/binance-BTCUSDT-1d-2017-08.csv")); + var http = new FakeHttp() + .On("2017-08.zip.CHECKSUM", Convert.ToHexStringLower(SHA256.HashData(august)) + " BTCUSDT-1d-2017-08.zip") + .OnBytes("2017-08.zip", august) + .On(_ => true, _ => FakeHttp.Respond("NoSuchKey", HttpStatusCode.NotFound)); + var clock = new FastClock(new DateTimeOffset(2017, 10, 15, 0, 0, 0, TimeSpan.Zero)); + var store = new ResearchStore(folder); + var importer = new BinanceImporter(new ApiHttp(http.Client(), clock, "binance"), store, clock); + + var result = await importer.ImportAsync("BTCUSDT", "1d", 2017, 7, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(5, result.Bars); + Assert.AreEqual(new DateTimeOffset(2017, 8, 17, 0, 0, 0, TimeSpan.Zero), result.First); + Assert.AreEqual(1, result.Notes.Count); + StringAssert.Contains(result.Notes[0], "2017-09"); + Assert.AreEqual(4, http.Requests.Count, "July (not listed yet), August and its checksum, September (not published)"); + var stored = await store.ReadAsync(Venues.Binance, "BTCUSDT", Timeframes.Day, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false); + CollectionAssert.AreEqual(BinanceArchive.ParseCsv(Fixture.Text("free/binance-BTCUSDT-1d-2017-08.csv")).ToList(), stored); + + // A zip that does not match its fingerprint is refused. + var tampered = new FakeHttp() + .On("CHECKSUM", new string('0', 64) + " BTCUSDT-1d-2017-08.zip") + .OnBytes("2017-08.zip", august); + var refused = new BinanceImporter(new ApiHttp(tampered.Client(), clock, "binance"), new ResearchStore(Path.Combine(folder, "other")), clock); + await Assert.ThrowsExactlyAsync(() => refused.ImportAsync("BTCUSDT", "1d", 2017, 8, CancellationToken.None)).ConfigureAwait(false); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task CsvImporterFollowsTheMappingAndReportsWhatItCouldNotRead() + { + var folder = TempFolder.Create("csvimport"); + try + { + var csv = Path.Combine(folder, "ethusd_2024.csv"); + await File.WriteAllTextAsync(csv, + "Data;Apertura;Massimo;Minimo;Chiusura;Volume\n" + + "02/01/2024 01:00;2.300,50;2.310,00;2.295,25;2.305,75;12,5\n" + + "02/01/2024 01:01;2.305,75;2.306,00;2.301,00;2.302,00;3\n" + + "02/01/2024 01:02;non so;2.306,00;2.301,00;2.302,00;3\n" + + "02/01/2024 01:04;2.302,00;2.303,00;2.300,00;2.301,00;4\n").ConfigureAwait(false); + await File.WriteAllTextAsync(Path.ChangeExtension(csv, ".mapping.json"), """ + { + // Exported from a spreadsheet in Italian. + "symbol": "ETHUSD", + "delimiter": ";", + "time": "Data", + "time_format": "dd/MM/yyyy HH:mm", + "time_zone": "Europe/Rome", + "open": "Apertura", "high": "Massimo", "low": "Minimo", "close": "Chiusura", "volume": "Volume", + "decimal_separator": ",", + } + """).ConfigureAwait(false); + + var mapping = CsvImporter.MappingFor(csv); + Assert.AreEqual("ETHUSD", mapping.Symbol); + Assert.AreEqual(";", mapping.Delimiter); + var store = new ResearchStore(Path.Combine(folder, "research")); + var result = await new CsvImporter(store).ImportAsync(csv, mapping, CancellationToken.None).ConfigureAwait(false); + + Assert.AreEqual(3, result.Bars); + Assert.AreEqual(new DateTimeOffset(2024, 1, 2, 0, 0, 0, TimeSpan.Zero), result.First, "01:00 in Rome is midnight UTC in winter"); + StringAssert.Contains(result.Notes[0], "riga 4"); + Assert.IsTrue(result.Notes.Any(n => n.Contains("1 righe non lette su 5", StringComparison.Ordinal)), string.Join(" | ", result.Notes)); + Assert.IsTrue(result.Notes.Any(n => n.StartsWith(IssueKinds.Gap, StringComparison.Ordinal)), "the missing minutes are reported"); + + var stored = await store.ReadAsync("import", "ETHUSD", Timeframes.Minute, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false); + Assert.AreEqual(3, stored.Count); + Assert.AreEqual(2300.50m, stored[0].Open); + Assert.AreEqual(12.5m, stored[0].Volume); + + // Without a mapping file: Binance-like columns by number and the symbol from the file name. + var plain = Path.Combine(folder, "solusdt-1m.csv"); + await File.WriteAllTextAsync(plain, string.Join('\n', Fixture.Text("free/binance-BTCUSDT-1d-2025-01.csv").Split('\n').Take(2))).ConfigureAwait(false); + var defaults = CsvImporter.MappingFor(plain) with { HasHeader = false, Timeframe = Timeframes.Day }; + var second = await new CsvImporter(store).ImportAsync(plain, defaults, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("SOLUSDT", second.Symbol); + Assert.AreEqual(2, second.Bars); + Assert.AreEqual(new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), second.First, "microseconds recognised by size"); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DownloaderRespectsLimitsRecordsFailuresAndSaysWhatIsOff() + { + var clock = new FastClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var settings = new SettingsStore(test.Db, clock, new EventBus()); + var ecbZip = Zip("eurofxref-hist.csv", Fixture.Text("free/ecb-hist.csv")); + var fngFails = true; + var http = new FakeHttp() + .OnBytes("eurofxref-hist.zip", ecbZip) + .On("eurofxref-daily.xml", Fixture.Text("free/ecb-daily.xml")) + .On("ff_calendar_thisweek", Fixture.Text("free/ff-calendar.json")) + .On(u => u.Host == "api.alternative.me", _ => fngFails + ? FakeHttp.Respond("{}", HttpStatusCode.BadRequest) + : FakeHttp.Respond(Fixture.Text("free/fng.json"))) + .On("VIX_History.csv", Fixture.Text("free/vix.csv")); + var sources = new ReferenceSources(new ApiHttp(http.Client(), clock, "reference"), test.Db, clock, settings, (_, _) => Task.FromResult(null)); + + // Exchange rates: the whole history the first time, then the day's file. + Assert.IsTrue(await sources.RefreshFxAsync(CancellationToken.None).ConfigureAwait(false)); + clock.Advance(TimeSpan.FromHours(1)); + Assert.IsTrue(await sources.RefreshFxAsync(CancellationToken.None).ConfigureAwait(false)); + CollectionAssert.AreEqual(new[] { "eurofxref-hist.zip", "eurofxref-daily.xml" }, http.Urls.Select(u => u.Segments[^1]).ToList()); + var rate = await new FxStore(test.Db, clock).RateOnAsync("EUR", "USD", new DateOnly(2026, 11, 9), CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(1.1193m, rate!.Rate); + + // The calendar: Forex Factory at most once an hour, the central banks from the settings. + Assert.IsTrue(await sources.RefreshCalendarAsync(CancellationToken.None).ConfigureAwait(false)); + clock.Advance(TimeSpan.FromMinutes(10)); + Assert.IsTrue(await sources.RefreshCalendarAsync(CancellationToken.None).ConfigureAwait(false)); + Assert.AreEqual(1, http.Urls.Count(u => u.Host == "nfs.faireconomy.media"), "ten minutes later Forex Factory is not asked again"); + var events = await new CalendarEventStore(test.Db, clock).BetweenAsync(_start.AddDays(-7), _start.AddYears(2), CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(5 + 18, events.Count); + + // Without keys FRED and Finnhub are off and the state says why; the earnings filter is off. + Assert.IsFalse(await sources.RefreshFredAsync(CancellationToken.None).ConfigureAwait(false)); + Assert.IsFalse(await sources.RefreshEarningsAsync(null, CancellationToken.None).ConfigureAwait(false)); + Assert.IsFalse(await sources.EarningsFilterActiveAsync(CancellationToken.None).ConfigureAwait(false)); + var states = await sources.StatesAsync(CancellationToken.None).ConfigureAwait(false); + StringAssert.Contains(states.Single(s => s.Source == Finnhub.Source).Note, "filtro sulle trimestrali è disattivato"); + Assert.IsFalse(states.Single(s => s.Source == Fred.Source).Enabled); + Assert.IsFalse(http.Urls.Any(u => u.Host.Contains("finnhub", StringComparison.Ordinal) || u.Host.Contains("stlouisfed", StringComparison.Ordinal))); + + // A failing source is recorded and does not stop the others; it is tried again at its next turn. + Assert.IsFalse(await sources.RefreshMoodAsync(CancellationToken.None).ConfigureAwait(false)); + states = await sources.StatesAsync(CancellationToken.None).ConfigureAwait(false); + Assert.IsNotNull(states.Single(s => s.Source == FearGreed.Source).LastError); + Assert.IsNull(states.Single(s => s.Source == VixHistory.Source).LastError); + Assert.AreEqual("calmo", (await new MoodStore(test.Db, clock).LatestAsync(MoodIndicators.Vix, CancellationToken.None).ConfigureAwait(false))!.Label); + fngFails = false; + clock.Advance(TimeSpan.FromHours(1)); + Assert.IsTrue(await sources.RefreshMoodAsync(CancellationToken.None).ConfigureAwait(false)); + var fng = (await sources.StatesAsync(CancellationToken.None).ConfigureAwait(false)).Single(s => s.Source == FearGreed.Source); + Assert.IsNull(fng.LastError); + Assert.AreEqual(FearGreed.Attribution, fng.Note, "the source is named, as its terms ask"); + StringAssert.Contains(http.Urls.Last(u => u.Host == "api.alternative.me").Query, "limit=400", "the first success asks for the history"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task CentralBankListIsEditableAndRefusedWhenWrong() + { + var clock = new ManualClock(_start); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var settings = new SettingsStore(test.Db, clock, new EventBus()); + var key = SettingsStore.CentralBankMeetings.Key; + Assert.AreEqual(CentralBanks.DefaultList, (await settings.GetAsync(key).ConfigureAwait(false)).Value); + + var error = await Assert.ThrowsExactlyAsync(() => settings.SetAsync(key, "FED 2027-13-01", "test")).ConfigureAwait(false); + StringAssert.Contains(error.Message, "Riga 1"); + await settings.SetAsync(key, CentralBanks.DefaultList + "\nFED 2028-01-26", "test").ConfigureAwait(false); + Assert.AreEqual(19, CentralBanks.Parse((await settings.GetAsync(key).ConfigureAwait(false)).Value).Count); + } + + internal static byte[] Zip(string entryName, string content) + { + using var zip = new MemoryStream(); + using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) + using (var stream = archive.CreateEntry(entryName).Open()) + { + stream.Write(Encoding.UTF8.GetBytes(content)); + } + + return zip.ToArray(); + } +} diff --git a/tests/Anubis.Tests/SecretScanTests.cs b/tests/Anubis.Tests/SecretScanTests.cs index f0dd29a..324ac19 100644 --- a/tests/Anubis.Tests/SecretScanTests.cs +++ b/tests/Anubis.Tests/SecretScanTests.cs @@ -53,6 +53,8 @@ public sealed partial class SecretScanTests Assert.IsFalse(LooksLikeSecret("REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}")); Assert.IsFalse(LooksLikeSecret("private const string SecretKeyVariable = \"ANUBIS_SECRET_KEY\";")); Assert.IsFalse(LooksLikeSecret("OKX_API_PASSPHRASE=")); + Assert.IsFalse(LooksLikeSecret(" \"next_page_token\": \"QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg==\"")); + Assert.IsTrue(LooksLikeSecret("{\"next_page_token\": null, \"api_key\": \"AKZXCVBNMASDFGHJKLQWERTY12\"}"), "a cursor does not hide a key on the same line"); // Code that assigns a computed value is not a secret. Assert.IsFalse(LooksLikeSecret("var key = RandomNumberGenerator.GetBytes(32);")); @@ -60,9 +62,16 @@ public sealed partial class SecretScanTests Assert.IsFalse(LooksLikeSecret("?secret={Base32.Encode(secret)}&issuer=x")); } - private static bool LooksLikeSecret(string line) => - PrivateKey().IsMatch(line) || BrokerHeader().IsMatch(line) || TelegramToken().IsMatch(line) || GenericSecret().IsMatch(line) - || NamedSecret().Matches(line).Any(m => !IsPlaceholder(m.Groups["value"].Value)); + private static bool LooksLikeSecret(string line) + { + // Pagination cursors of the APIs (Alpaca's next_page_token in the recorded responses) are not credentials. + line = PageCursor().Replace(line, ""); + return PrivateKey().IsMatch(line) || BrokerHeader().IsMatch(line) || TelegramToken().IsMatch(line) || GenericSecret().IsMatch(line) + || NamedSecret().Matches(line).Any(m => !IsPlaceholder(m.Groups["value"].Value)); + } + + [GeneratedRegex("""(?i)["']?(next_)?page_token["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_\-]*["']?""")] + private static partial Regex PageCursor(); // Example values in .env.example, compose files and the CI are clearly fake. private static bool IsPlaceholder(string value) => diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index 84cc2a4..5b4b595 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable } public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null, - string[]? extraArgs = null, bool waitReady = true) + string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null) { var owns = dataDir is null; dataDir ??= TempFolder.Create("server"); @@ -86,6 +86,9 @@ internal sealed partial class ServerHarness : IAsyncDisposable Environment = environment, PasswordIterations = 1000, DatabaseCheckInterval = TimeSpan.FromMilliseconds(100), + MarketData = marketHttp is not null, + MarketHttp = marketHttp, + MarketSockets = marketHttp is null ? null : () => new FakeSocket(), }); await app.StartAsync().ConfigureAwait(false); var cookies = new CookieContainer(); diff --git a/tests/Anubis.Tests/ServerTests.cs b/tests/Anubis.Tests/ServerTests.cs index 1d08971..c5e0c3a 100644 --- a/tests/Anubis.Tests/ServerTests.cs +++ b/tests/Anubis.Tests/ServerTests.cs @@ -244,8 +244,7 @@ public sealed class ServerTests var file = new DataDirectory(server.DataDir).SqliteFile; var away = file + ".altrove"; - Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); - File.Move(file, away); + await MoveWhenFreeAsync(file, away); await server.WaitForAsync(HostMode.DatabaseUnavailable); using (var page = await server.GetAsync("/")) @@ -262,6 +261,27 @@ public sealed class ServerTests Assert.AreEqual(HttpStatusCode.OK, back.StatusCode, "Same session, no restart."); } + /// + /// Moves the database file as soon as no connection holds it: a request or a background job of the running server + /// can have one open for a moment, and Windows refuses to move an open file. + /// + private static async Task MoveWhenFreeAsync(string from, string to) + { + for (var attempt = 1; ; attempt++) + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try + { + File.Move(from, to); + return; + } + catch (IOException) when (attempt < 50) + { + await Task.Delay(100); + } + } + } + [TestMethod] public async Task EmptyDatabaseOfAKnownInstallationAsksTheUser() { diff --git a/tests/Anubis.Tests/TestSupport.cs b/tests/Anubis.Tests/TestSupport.cs index 478f59b..0749eb3 100644 --- a/tests/Anubis.Tests/TestSupport.cs +++ b/tests/Anubis.Tests/TestSupport.cs @@ -137,12 +137,23 @@ internal sealed class TestDb : IAsyncDisposable } var name = "anubis_t_" + Guid.NewGuid().ToString("N"); - await using (var admin = Anubis.Db.Database.Open(AdminSettings())) + for (var attempt = 1; ; attempt++) { - await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false); - await using var command = connection.CreateCommand(); - command.CommandText = $"CREATE DATABASE {name}"; - await command.ExecuteNonQueryAsync().ConfigureAwait(false); + try + { + await using var admin = Anubis.Db.Database.Open(AdminSettings()); + await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false); + await using var command = connection.CreateCommand(); + command.CommandText = $"CREATE DATABASE {name}"; + await command.ExecuteNonQueryAsync().ConfigureAwait(false); + break; + } + catch (Npgsql.NpgsqlException ex) when (ex.InnerException is TimeoutException && attempt < 4) + { + // Many tests create their database at once and a busy CI runner can be slow to accept even within the + // longer test timeout. That is the runner, not the code under test. + await Task.Delay(TimeSpan.FromSeconds(attempt)).ConfigureAwait(false); + } } return new TestDb(AdminSettings() with { Database = name }, null, name); @@ -159,6 +170,10 @@ internal sealed class TestDb : IAsyncDisposable Database = "anubis", User = "anubis", Password = PostgresPassword, + + // Twelve test workers open connections at once: on a busy CI runner PostgreSQL can take longer than the + // application's 5 seconds to accept one. Waiting longer here tests the same code without the runner's noise. + ConnectTimeoutSeconds = 30, }; public async ValueTask DisposeAsync() diff --git a/tests/Anubis.Tests/UniverseTests.cs b/tests/Anubis.Tests/UniverseTests.cs new file mode 100644 index 0000000..37494be --- /dev/null +++ b/tests/Anubis.Tests/UniverseTests.cs @@ -0,0 +1,237 @@ +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Tests; + +/// Universes "as of a date" (issue #24) and the corporate action store (issue #23). +[TestClass] +public sealed class UniverseTests +{ + private static readonly DateOnly[] _pastDates = [new(2019, 12, 31), new(2021, 6, 30), new(2024, 3, 28)]; + + private static readonly DateTimeOffset _now = new(2026, 11, 10, 8, 0, 0, TimeSpan.Zero); + + /// + /// The securities of the recorded nasdaqtraded.txt plus 40 common shares, a stock delisted in 2020, a cheap one + /// and one listed in 2021. Funds and ETFs trade the most, so they would lead the ranking if they got through. + /// + private static List Market() + { + var listed = NasdaqTraded.Parse(Fixture.Text("free/nasdaqtraded.txt")); + var specs = listed.Select(l => Stock(l.Symbol, l.Name, l.Exchange)).ToList(); + specs.AddRange(Enumerable.Range(1, 40).Select(i => Stock($"S{i:D3}", $"Synthetic {i} Inc. Common Stock", i % 2 == 0 ? "NYSE" : "NASDAQ"))); + specs.Add(Stock("DEAD", "Gone Corp. Common Stock", "NYSE")); + specs.Add(Stock("CHEAP", "Penny Corp. Common Stock", "NASDAQ")); + specs.Add(Stock("YOUNG", "New Listing Inc. Common Stock", "NASDAQ")); + specs.Add(Stock("NOFRAC", "Whole Shares Only Inc.", "NYSE") with { Fractionable = false }); + var marked = NasdaqTraded.MarkFunds(specs, listed); + + var candidates = new List(); + foreach (var spec in marked) + { + var symbol = spec.Symbol; + var first = symbol == "YOUNG" ? new DateOnly(2021, 1, 4) : new DateOnly(2018, 1, 2); + var last = symbol == "DEAD" ? new DateOnly(2020, 6, 30) : new DateOnly(2026, 11, 9); + var price = symbol == "CHEAP" ? 5.0 : 20.0 + (symbol.GetHashCode(StringComparison.Ordinal) & 0x3f); + var volume = spec.IsFund == true || symbol.StartsWith("ZX", StringComparison.Ordinal) ? 50_000_000.0 : 100_000.0 * (1 + (symbol.Length * 7 % 13)); + if (symbol is "DEAD" or "YOUNG") + { + volume = 10_000_000; // Large enough to rank first whenever they are eligible. + } + + candidates.Add(new UniverseCandidate(new Instrument(Guid.NewGuid(), spec, null), Sessions(first, last, price, volume))); + } + + return candidates; + } + + private static InstrumentSpec Stock(string symbol, string name, string exchange) => + new(Venues.Alpaca, symbol, name, AssetClasses.Equity, "USD") { Exchange = exchange, Fractionable = true, Status = "active" }; + + private static List Sessions(DateOnly first, DateOnly last, double price, double volume) + { + var bars = new List(); + for (var day = first; day <= last; day = day.AddDays(1)) + { + if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + bars.Add(new DailyBar(day, price, price * 1.01, price * 0.99, price, volume)); + } + } + + return bars; + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EquityUniverseAtThreePastDatesHasNoEtfsNorFunds() + { + var market = Market(); + var excluded = new HashSet { "SPY", "BULZ", "AMUB", "PDI", "ABR$D", "AACIW", "ZXIET", "CHEAP", "NOFRAC" }; + foreach (var date in _pastDates) + { + var members = EquityUniverse.Select(date, market); + var symbols = members.Select(m => m.Symbol).ToList(); + Assert.IsFalse(symbols.Any(excluded.Contains), $"{date}: {string.Join(", ", symbols.Where(excluded.Contains))}"); + Assert.IsFalse(symbols.Contains("CECO"), "Texas Stock Exchange is neither NYSE nor Nasdaq"); + CollectionAssert.IsSubsetOf(new[] { "AAPL", "KO", "AACG", "S001", "S040" }, symbols, BarStore.DayText(date)); + CollectionAssert.AreEqual(Enumerable.Range(1, members.Count).ToList(), members.Select(m => m.Rank).ToList()); + } + + // Survivorship: the stock delisted in 2020 belongs to the 2019 universe and to no later one. + Assert.AreEqual(1, EquityUniverse.Select(_pastDates[0], market)[0].Rank); + Assert.AreEqual("DEAD", EquityUniverse.Select(_pastDates[0], market)[0].Symbol); + Assert.IsFalse(EquityUniverse.Select(_pastDates[1], market).Any(m => m.Symbol == "DEAD")); + + // History: a stock listed in January 2021 has fewer than 300 sessions in June 2021, enough in 2024. + Assert.IsFalse(EquityUniverse.Select(_pastDates[1], market).Any(m => m.Symbol == "YOUNG")); + Assert.AreEqual("YOUNG", EquityUniverse.Select(_pastDates[2], market)[0].Symbol); + + // The size cut keeps the most traded. + var top = EquityUniverse.Select(_pastDates[2], market, size: 5); + Assert.AreEqual(5, top.Count); + Assert.IsTrue(top.Zip(top.Skip(1)).All(p => p.First.Measure >= p.Second.Measure)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void UniverseOnADateIgnoresEverythingAfterIt() + { + var market = Market(); + var date = _pastDates[1]; + var truncated = market.Select(c => c with { Bars = c.Bars.Where(b => b.Day <= date).ToList() }).ToList(); + + // A later crash of AAPL to 1 $ and a later volume explosion of S002 must not change the June 2021 universe. + var future = market.Select(c => c.Instrument.Symbol switch + { + "AAPL" => c with { Bars = [.. c.Bars.Select(b => b.Day > date ? b with { Close = 1, Low = 0.9, Open = 1, High = 1.1 } : b)] }, + "S002" => c with { Bars = [.. c.Bars.Select(b => b.Day > date ? b with { Volume = 1e12 } : b)] }, + _ => c, + }).ToList(); + + var expected = EquityUniverse.Select(date, truncated); + CollectionAssert.AreEqual(expected.ToList(), EquityUniverse.Select(date, market).ToList()); + CollectionAssert.AreEqual(expected.ToList(), EquityUniverse.Select(date, future).ToList()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CryptoUniverseFiltersAgeValueSpreadAndExcludedTokens() + { + var asOf = new DateOnly(2026, 11, 1); + var end = QualityChecks.Midnight(asOf.AddDays(1)); + UniverseCandidate Pair(string coin, double value, double? current, int ageDays = 900, double? sampled = null) => + new(new Instrument(Guid.NewGuid(), new InstrumentSpec(Venues.Okx, coin + "-EUR", coin + "/EUR", AssetClasses.Crypto, "EUR") + { + BaseCurrency = coin, + ListedAt = end.AddDays(-ageDays), + }, null), Sessions(asOf.AddDays(-60), asOf, 100, value / 100).Concat([]).ToList()) + { + CurrentSpreadBp = current, + Spreads = sampled is { } bp ? [.. Enumerable.Range(1, 30 * 24).Select(h => (end.AddHours(-h), bp))] : [], + }; + + // Weekends are missing from Sessions: give crypto every day. + UniverseCandidate Daily(UniverseCandidate c) => c with + { + Bars = [.. QualityChecks.EveryDay(asOf.AddDays(-60), asOf).Select(d => c.Bars[0] with { Day = d })], + }; + + var candidates = new[] + { + Pair("BTC", 50_000_000, 2), Pair("ETH", 20_000_000, 3), Pair("SOL", 5_000_000, null, sampled: 8), + Pair("XRP", 3_000_000, 50, sampled: 10), // 30 days of samples win over a wide spread right now. + Pair("ADA", 2_000_000, 25), Pair("DOT", 200_000, 5), Pair("NEW", 9_000_000, 5, ageDays: 200), + Pair("USDC", 90_000_000, 1), Pair("WBTC", 9_000_000, 5), Pair("BTC3L", 9_000_000, 5), Pair("LINK", 1_000_000, null), + }.Select(Daily).ToList(); + var members = CryptoUniverse.Select(asOf, candidates); + CollectionAssert.AreEqual(new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR", "XRP-EUR" }, members.Select(m => m.Symbol).ToList(), + "ADA spread too wide, DOT too small, NEW too young, stable/wrapped/leveraged out, LINK spread unknown"); + Assert.AreEqual(2, CryptoUniverse.Select(asOf, candidates, size: 2).Count); + Assert.IsTrue(CryptoUniverse.Excluded("ETHUP") && CryptoUniverse.Excluded("eurc") && !CryptoUniverse.Excluded("UNI")); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task UniversesAreComputedFromTheDatabaseAndKeptByDate() + { + var clock = new ManualClock(_now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var catalog = new InstrumentCatalog(test.Db, clock); + var bars = new BarStore(test.Db, clock); + var listed = NasdaqTraded.Parse(Fixture.Text("free/nasdaqtraded.txt")); + var specs = NasdaqTraded.MarkFunds( + [Stock("AAPL", "Apple Inc. - Common Stock", "NASDAQ"), Stock("SPY", "SPDR S&P 500 ETF Trust", "ARCA") with { Exchange = "NYSE" }, + Stock("PDI", "PIMCO Dynamic Income Fund", "NYSE"), Stock("KO", "Coca-Cola Company (The) Common Stock", "NYSE")], listed); + await catalog.SyncAsync(Venues.Alpaca, specs, complete: true, CancellationToken.None).ConfigureAwait(false); + foreach (var instrument in await catalog.ListAsync(Venues.Alpaca, CancellationToken.None).ConfigureAwait(false)) + { + var volume = instrument.Symbol == "SPY" ? 1e9 : instrument.Symbol == "AAPL" ? 2e6 : 1e6; + await bars.UpsertDailyAsync(instrument.Id, Sessions(new DateOnly(2024, 1, 2), new DateOnly(2026, 11, 6), 50, volume), Venues.Alpaca, CancellationToken.None) + .ConfigureAwait(false); + } + + var builder = new UniverseBuilder(test.Db, clock); + var equity = await builder.EquityAsync(new DateOnly(2026, 11, 6), CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { "AAPL", "KO" }, equity.Select(m => m.Symbol).ToList(), "SPY is an ETF even when listed on NYSE; PDI a fund"); + await builder.EquityAsync(new DateOnly(2025, 3, 3), CancellationToken.None).ConfigureAwait(false); + + var store = new UniverseStore(test.Db, clock); + Assert.AreEqual(2, (await store.AsOfAsync(Universes.Equity, new DateOnly(2026, 11, 9), CancellationToken.None).ConfigureAwait(false)).Count); + Assert.AreEqual(2, (await store.AsOfAsync(Universes.Equity, new DateOnly(2025, 6, 1), CancellationToken.None).ConfigureAwait(false)).Count); + Assert.AreEqual(0, (await store.AsOfAsync(Universes.Equity, new DateOnly(2025, 1, 1), CancellationToken.None).ConfigureAwait(false)).Count, + "before the first computation there is no universe"); + + // Crypto: spread samples come from the hourly job; without 30 days of them the current spread decides. + var btc = await catalog.EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = _now.AddYears(-3) }, CancellationToken.None).ConfigureAwait(false); + var eth = await catalog.EnsureAsync(MarketDataStoreTests.Okx("ETH-EUR") with { ListedAt = _now.AddYears(-3) }, CancellationToken.None).ConfigureAwait(false); + foreach (var pair in new[] { btc, eth }) + { + await bars.UpsertDailyAsync(pair.Id, [.. QualityChecks.EveryDay(new DateOnly(2026, 9, 1), new DateOnly(2026, 11, 9)) + .Select(d => new DailyBar(d, 60_000, 61_000, 59_000, 60_000, 100) { QuoteVolume = 6_000_000 })], Venues.Okx, CancellationToken.None).ConfigureAwait(false); + } + + for (var h = 1; h <= 30 * 24; h++) + { + await store.AddSpreadAsync(eth.Id, QualityChecks.Midnight(new DateOnly(2026, 11, 10)).AddHours(-h), 30, CancellationToken.None).ConfigureAwait(false); + } + + var asked = new List(); + var crypto = await builder.CryptoAsync(new DateOnly(2026, 11, 9), i => + { + asked.Add(i.Symbol); + return Task.FromResult(1.5); + }, CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { "BTC-EUR" }, crypto.Select(m => m.Symbol).ToList(), "ETH's 30-day median spread is 30 bp"); + CollectionAssert.AreEqual(new[] { "BTC-EUR" }, asked, "the current spread is asked only where samples are missing"); + Assert.AreEqual(0, await store.PruneSpreadsAsync(CancellationToken.None).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task CorporateActionsAreKeptOnceAndFoundByDay() + { + var clock = new ManualClock(_now); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var aapl = await new InstrumentCatalog(test.Db, clock).EnsureAsync(Stock("AAPL", "Apple Inc.", "NASDAQ"), CancellationToken.None).ConfigureAwait(false); + var store = new CorporateActionStore(test.Db, clock); + var split = new CorporateAction("AAPL", CorporateActionKinds.Split, new DateOnly(2020, 8, 31), Venues.Alpaca, "alpaca:split:1") { Ratio = 4m }; + var dividend = new CorporateAction("AAPL", CorporateActionKinds.CashDividend, new DateOnly(2026, 11, 10), Venues.Alpaca, "alpaca:div:2") + { + CashAmount = 0.26m, + Currency = "USD", + }; + var other = new CorporateAction("ZZZ", CorporateActionKinds.SymbolChange, new DateOnly(2026, 11, 10), Venues.Alpaca, "alpaca:sc:3") { NewSymbol = "ZZY" }; + + Assert.AreEqual(3, await store.UpsertAsync([split, dividend, other, split], CancellationToken.None).ConfigureAwait(false)); + await store.UpsertAsync([dividend with { CashAmount = 0.27m }], CancellationToken.None).ConfigureAwait(false); + var forApple = await store.ForSymbolAsync("AAPL", CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { split, dividend with { CashAmount = 0.27m } }, forApple.ToList()); + var today = await store.OnAsync(new DateOnly(2026, 11, 10), CancellationToken.None).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { "AAPL", "ZZZ" }, today.Select(a => a.Symbol).ToList()); + + var linked = await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM corporate_actions WHERE instrument_id = @i", ("i", aapl.Id)), CancellationToken.None) + .ConfigureAwait(false); + Assert.AreEqual(2L, linked, "actions of a known symbol point to its instrument"); + } +}