diff --git a/Encelado/docs/DATA_SOURCES.md b/Encelado/docs/DATA_SOURCES.md index db4b3a0..c177f8e 100644 --- a/Encelado/docs/DATA_SOURCES.md +++ b/Encelado/docs/DATA_SOURCES.md @@ -1,6 +1,6 @@ # Fonti dei dati -Aggiornato: 2026-09-16. Ogni fonte è stata verificata alla data indicata; se un feed cambia o sparisce, la voce va aggiornata e la decisione annotata in `docs/QUESTIONS.md`. +Aggiornato: 2026-09-30 (rotte di chiusura e storico delle posizioni chiuse, §1.1). Ogni fonte è stata verificata alla data indicata; se un feed cambia o sparisce, la voce va aggiornata e la decisione annotata in `docs/QUESTIONS.md`. ## 1. Mercato @@ -25,7 +25,9 @@ Qualità (`data/market/data_quality.csv`, generato da `backtest ticks`, e `repor | `GET api/v1/trading/info/{demo/}orders/{orderId}` | ripiego per `orderId` con la risposta v1 (`statusID`, `errorCode`, `positions[] {positionID, rate, units, occurred, isOpen}`) | verificato con l'ordine 381739181. | | `DELETE api/v2/trading/execution/{demo/}orders/{orderId}` | cancellazione di un ordine non ancora eseguito (kill-switch) | 200 = richiesta accettata, non annullamento avvenuto: confermare con il lookup (7 o 9 = annullato, 6 = in corso). Idempotente su ordini già chiusi. | | `GET api/v1/trading/info/{demo/}pnl` | conto e posizioni in una chiamata: `clientPortfolio.credit`, `bonusCredit`, `unrealizedPnL`, `positions[] {positionID, instrumentID, isBuy, units, openRate, openDateTime, amount (margine), leverage, unrealizedPnL.pnL, totalFees}` | `equity = credit + bonus + Σ amount + unrealized`; `available = credit + bonus`; `usedMargin = Σ amount`. Il conto demo **non compare** in `api/v1/balances` (solo i conti reali). | -| `GET api/v1/trading/info/trade/{demo/}history?minDate=…&page=…&pageSize=200` | posizioni chiuse: `positionId`, `orderId`, `openRate`, `closeRate`, `openTime`, `closeTime`, `netProfit`, `fees`, `investment` | `netProfit` **non** include `fees`. Fonte del realizzato della scheda Storico e della distinzione fra chiusure e movimenti di cassa. | +| `POST api/v1/trading/execution/{demo/}market-close-orders/positions/{positionId}` | chiusura di una posizione (corpo `{"InstrumentID": …}`) | risponde con `orderForClose.orderID`: l'esito si legge sulla rotta seguente. Quota 20/min condivisa con gli ordini. | +| `GET api/v1/trading/info/{demo/}close-orders/{orderId}` | esito della chiusura: `statusID`, `errorCode`, `proceeds`, `positions[] {positionID, occurred, rate, units, conversionRate, amount}` | schema verificato il 2026-09-30 (API v1.383.0). **Non ha alcun campo di profitto.** `proceeds` è, per la specifica, il totale restituito dalla chiusura sulle posizioni coinvolte: margine liberato più profitto (una posizione con `amount` 7 210,02 chiusa a +32,00 restituisce 7 242,02). I numeri della 5.0.0 lo confermano: «P&L oggi» di circa 47 000 USD su 139 000 di equity, in linea con la somma di investimento + profitto delle chiusure del giorno. **Non è mai il P&L**. Dalla 4.0.0 alla 5.0.0 il bot lo registrava come realizzato (vedi `docs/LEDGER_SCHEMA.md`, correzioni `pnl_realizzato`); dalla 5.1 resta solo come diagnostica (`CloseOutcome.Proceeds`). `rate` e `conversionRate` (valuta quotata → USD, 1 per le coppie in USD) servono alla **stima provvisoria**: `unità × Δprezzo × conversionRate − fee`, che coincide al centesimo con lo storico su NZDUSD, EURNZD e USDCAD. L'`orderId` della chiusura non è quello dello storico. Quota Lookup (60/min). | +| `GET api/v1/trading/info/trade/{demo/}history?minDate=…&page=…&pageSize=200` | posizioni chiuse: `positionId`, `orderId`, `instrumentId`, `isBuy`, `units`, `openRate`, `closeRate`, `openTimestamp`, `closeTimestamp`, `netProfit`, `fees`, `investment` | **Il P&L di record** di ogni posizione chiusa (dalla 5.1): `netProfit − fees`. `netProfit` **non** include `fees` (nello storico demo del 2026-09 le fee sono sempre 0). `minDate` filtra sull'**ora di chiusura** a partire dalla mezzanotte UTC di quel giorno (verificato il 2026-09-30: `minDate=2026-09-29` comprende le posizioni aperte il 28 e chiuse il 29, esclude quelle chiuse il 28 alle 22:45 UTC); le righe arrivano dalla più recente; lo sguardo all'indietro dev'essere inferiore a un anno. L'`orderId` è l'ordine di **apertura** (`orders/{id}` risponde 200, `close-orders/{id}` 404): lo storico si unisce ai file del bot **per `positionId`**. Quota Default (60/min, budget locale 55): il motore lo legge circa ogni 5 minuti, ogni 5 s nel minuto dopo una chiusura e ogni 30 s finché una chiusura attende. Una pagina che non si legge è un **errore** (`BrokerException`), mai una lista vuota. Fonte del realizzato della scheda Storico, di «P&L oggi», delle righe di `baskets.csv` e della distinzione fra chiusure e movimenti di cassa. | **Stati dell'ordine** (`status.id` / `statusID`): 1 Received, 2 Placed, 3 Filled, 4 Rejected, 5 PartiallyFilled, 6 PendingCancel, 7 Canceled, 8 Expired, 9 CanceledPartiallyFilled, 10 RejectedPartiallyFilled, 11 WaitingForMarket, 12 PendingTriggeredRate. Il bot tratta 3 e 5 come eseguito, 4, 7, 8, 9, 10 come rifiutato/annullato, 1, 2, 6, 11, 12 come in corso; in assenza di risposta lo stato è `Unknown` e l'ordine resta nel registro. Esiste anche `POST api/v3/trading/execution/{demo/}orders` (202, stessa semantica, `settlementType` obbligatorio): non usato, annotato per il futuro. diff --git a/Encelado/docs/LEDGER_SCHEMA.md b/Encelado/docs/LEDGER_SCHEMA.md index 5e375c6..6510409 100644 --- a/Encelado/docs/LEDGER_SCHEMA.md +++ b/Encelado/docs/LEDGER_SCHEMA.md @@ -16,7 +16,7 @@ Una riga per **ogni** valutazione di ogni basket alla chiusura di ogni barra M15 | `cross` | testo | cross sintetico (`EURCHF`) | | `mode` (`Paper` | `Demo` | `Live`; i file scritti prima del 2026-09-16 pomeriggio portano i nomi precedenti `DemoApprove`/`DemoAuto`) | testo | `Paper`, `Demo`, `Live` | | `preset` | testo | `CONSERVATIVE`, `MODERATE`, `AGGRESSIVE` | -| `evento` | testo | `skip`, `segnale_ingresso`, `ingresso`, `rifiuto`, `leg_risk_unwind`, `posizione`, `segnale_aggiunta`, `aggiunta`, `segnale_uscita`, `uscita`, `correzione`; dalla 5.0 anche le righe di evento (senza feature, solo `ts`, `run_id`, `evento`, `basket_id`, campi propri e `motivazione`): `pending` (gamba senza esito, con `leg`, `client_ref`, `order_id`), `pending_risolto` (con `esito`, `fonte`, `position_id`), `orfana_adottata` e `orfana_chiusa` (con `position_id`, `strumento`, `pnl`, `exit_reason`), `movimento_di_cassa` (con `importo`, `saldo_prima`, `saldo_dopo`, `chiusure_nel_frattempo`, `cassa_cumulata`), `margin_guard` (con `equity`, `margine_usato`), `kill_switch_avviato`, `kill_switch_concluso` (con `stato` = `Halted` o `Halted-Residuo`, `chiuse`, `residuo`, `annullati`, `pnl`), `residuo_chiuso`, `reset_rifiutato`, `reset_concluso`, `recupero_avviato` (con `inattivita_min`, `barre`), `recupero_concluso` (con `inattivita_min`, `barre`, `chiusi`, `tenuti`), `comando` (ogni comando dalla finestra, dalla console o da Telegram: `comando`, `argomento`, `ok`; la motivazione porta l'origine e la prima riga dell'esito) | +| `evento` | testo | `skip`, `segnale_ingresso`, `ingresso`, `rifiuto`, `leg_risk_unwind`, `posizione`, `segnale_aggiunta`, `aggiunta`, `segnale_uscita`, `uscita`, `correzione`; dalla 5.0 anche le righe di evento (senza feature, solo `ts`, `run_id`, `evento`, `basket_id`, campi propri e `motivazione`): `pending` (gamba senza esito, con `leg`, `client_ref`, `order_id`), `pending_risolto` (con `esito`, `fonte`, `position_id`), `orfana_adottata` e `orfana_chiusa` (con `position_id`, `strumento`, `exit_reason` e, fino alla 5.0.0, `pnl` = il `proceeds` della chiusura; dalla 5.1 `stima`), `movimento_di_cassa` (con `importo`, `saldo_prima`, `saldo_dopo`, `chiusure_nel_frattempo`, `cassa_cumulata`), `margin_guard` (con `equity`, `margine_usato`), `kill_switch_avviato`, `kill_switch_concluso` (con `stato` = `Halted` o `Halted-Residuo`, `chiuse`, `residuo`, `annullati` e, fino alla 5.0.0, `pnl` = somma dei `proceeds`; dalla 5.1 `pnl_bot` e `pnl_esterne` — stime dai prezzi di chiusura, le posizioni del bot separate da quelle esterne —, `pnl_bot_sconosciuti`, `pnl_esterne_sconosciuti`, `pnl_fonte`), `residuo_chiuso`, `reset_rifiutato`, `reset_concluso`, `recupero_avviato` (con `inattivita_min`, `barre`), `recupero_concluso` (con `inattivita_min`, `barre`, `chiusi`, `tenuti`), `comando` (ogni comando dalla finestra, dalla console o da Telegram: `comando`, `argomento`, `ok`; la motivazione porta l'origine e la prima riga dell'esito); la nota `leg_risk_unwind` (gamba A eseguita in ritardo e richiusa) porta `position_id` e fino alla 5.0.0 `pnl` (proceeds), dalla 5.1 `stima`. Dalla 5.1: `realizzato` (una chiusura regolata sullo storico eToro: `basket`, `exit_reason`, `fonte` = `storico eToro` / `stima dai prezzi di chiusura` / `simulatore`, `position_ids`, `pnl_lordo`, `pnl_netto`, `stima` = il valore stimato alla chiusura) e `verifica_realizzato` (la verifica del realizzato all'avvio: `fino_a` = ora di chiusura dell'ultima riga verificata, `righe`, `concordi`, `corrette`, `non_verificabili`). I testi «netto … USD» delle righe `uscita` e `residuo_chiuso` fino alla 5.0.0 sono proceeds; dalla 5.1 dicono «stima … in attesa dello storico eToro» | | `decision` | testo | `Skip`, `Enter`, `Add`, `Exit`, `Hold` | | `buy_cross` | bool | verso deciso (compra il cross = compra entrambe le gambe nei cinque basket) | | `z`, `z_in_eff` | numero | z-score del cross e soglia effettiva (scalata dalla vol prevista) | @@ -41,15 +41,31 @@ Una riga per **ogni** valutazione di ogni basket alla chiusura di ogni barra M15 | `reasonCodes` | array | codici: `no_signal`, `rho_low`, `rho_short_low`, `half_life`, `blackout_before`, `blackout_after`, `weekend`, `just_opened`, `session`, `max_baskets`, `same_cross`, `ml_gate`, `cost_gate`, `sizing`, `kill_switch`, `equity_stop`, `daily_loss`, `entries_blocked`, `data_quality`, `warmup`, `not_bar_close`, `enter`, `add`, `hold`, `tp_pips`, `tp_z`, `stop_z`, `stop_max_loss`, `spread_anomaly`, `time_stop`, `rho_break`; dalla 5.0 `margin` (nessun margine per un nuovo basket), `margin_guard` (equity / margine usato sotto la soglia), `min_exposure` (la size a margine non raggiunge l'esposizione minima) | | `motivazione` | testo | la frase, in italiano, con i numeri | +### Correzioni (`evento = correzione`) + +Una correzione è sempre una riga nuova: `baskets.csv` e le righe già scritte non cambiano mai. Oltre alle correzioni libere (motivazione del reset, equity stop, cambio di preset), dalla 5.1 esistono tre `tipo`: + +| `tipo` | Campi | Significato | +|---|---|---| +| `pnl_realizzato` | `riga` (chiave della riga di `baskets.csv`: `basket_id` + `|` + `closed_utc` nel formato `O`, così si distinguono anche le gambe singole con `basket_id` vuoto), `basket`, `exit_reason`, `pnl_net_registrato`, `pnl_gross_corretto`, `pnl_net_corretto`, `label_corretta`, `verificata`, `position_ids`, `fonte` | il realizzato vero di una riga, dallo storico eToro (`netProfit − fees` delle sue posizioni). Con `verificata = false` (posizioni non ritrovate) i tre campi corretti sono `null`: la riga non ha etichetta, non addestra niente ed è esclusa dai riepiloghi. La scrive la verifica del realizzato all'avvio (`verifica_realizzato`), idempotente: una riga verificata non viene più controllata | +| `feature_inaffidabile` | `feature` (`lastNOutcomes`), `indice` (26), `fino_a` | la feature è inaffidabile in ogni riga di valutazione scritta prima di `fino_a`: era calcolata sulle etichette sbagliate. Nel dataset vale il suo valore neutro 0,5; mai ricostruita a posteriori | +| `pnl_note_proceeds` | `da`, `a` | nelle righe scritte in quell'intervallo i campi `pnl` delle note (`leg_risk_unwind`, `orfana_chiusa`, `kill_switch_concluso`) e i testi «netto … USD» sono i `proceeds` della chiusura, non il P&L. Nessun codice li legge | + +**Lettore corretto** (`Ledger.ReadBasketsCorrected`): legge `baskets.csv` e applica a ogni riga la correzione `pnl_realizzato` più recente della sua chiave, cercandola in tutti i `decisions*.jsonl` (mesi ruotati compresi); marca non verificata (`Unverified`, niente etichetta) una riga con correzione non verificata, con P&L sconosciuto o scritta come stima dopo il timeout (`P&L: stima` nella motivazione). Lo usano il dataset di addestramento, il seme di `lastNOutcomes`, il riepilogo giornaliero e `/storico` di Telegram, la scheda Storico. Il file non viene mai toccato. + +**Cosa non si può correggere**: i messaggi Telegram e le righe di log già emessi dalla 4.0.0 alla 5.0.0 mostravano i proceeds come «netto» e «P&L oggi»; restano come sono. + ## `data/ledger/baskets.csv` -Una riga per basket chiuso. `label = 1` se `pnl_net_usd > 0`, altrimenti 0: è l'etichetta dei livelli 1-3. +Una riga per basket chiuso (e per gamba singola). `label = 1` se `pnl_net_usd > 0`, altrimenti 0: è l'etichetta dei livelli 1-3; vuota quando il P&L è sconosciuto. ``` basket_id;run_id;basket;mode;preset;opened_utc;closed_utc;buy_cross;entry_z;exit_z;pnl_gross_usd;pnl_net_usd;pips_gross;cost_pips;cost_usd;slippage_pips;adds;bars_held;exit_reason;equity_at_entry;p_ml_at_entry;label;durata_min;motivazione ``` -`pips_gross` è la somma dei pip delle due gambe ai prezzi di esecuzione (la colonna "Pips" della UI), `cost_pips` il costo stimato all'ingresso, `slippage_pips` la differenza fra quotazione vista e prezzo eseguito sommata sulle gambe, `exit_reason` uno dei codici sopra più `manual`, `closed_by_broker`, `leg_closed_by_broker`, `end_of_data`, e dalla 5.0 `leg_risk_unwind` (gamba A eseguita in ritardo e richiusa, o B non coperta dal margine), `margin_guard` (chiuso dalla guardia del margine), `orphan_closed` (gamba orfana del bot adottata e chiusa alla riconciliazione), `bonifica_orfana` (chiusa dalla bonifica con conferma), `kill_switch`/`equity_stop` anche per le gambe singole. Le righe di una gamba singola hanno `entry_z`, `exit_z`, `pips_gross` e `cost_*` vuoti e `buy_cross` = verso della gamba. +**Da dove viene il P&L (dalla 5.1).** eToro non dice il realizzato nella risposta di chiusura. La riga non viene scritta alla chiusura: resta nella coda di regolamento (`pendingSettlements` dello stato) con la **stima** dai prezzi di chiusura e viene scritta quando lo storico eToro mostra tutte le sue posizioni, con `pnl_net_usd = Σ (netProfit − fees)` e `pnl_gross_usd = Σ netProfit`; la motivazione finisce con `| P&L: storico eToro (netProfit − fees)`. Se dopo 30 minuti lo storico non le mostra ancora, la riga viene scritta con la stima e la motivazione finisce con `| P&L: stima dai prezzi di chiusura…`: non addestra niente e la verifica all'avvio la ricontrolla finché lo storico non la conferma. In un simulatore (backtest) il numero è quello finale del simulatore (`| P&L: simulatore`). La motivazione porta anche `posizioni: …`, le posizioni eToro della riga. **Fino alla 5.0.0** `pnl_net_usd` era la somma dei `proceeds` delle chiusure (margine restituito + profitto) meno l'overnight maturato, e `label` quasi sempre 1: quelle righe si leggono solo con il lettore corretto. + +`pips_gross` è la somma dei pip delle due gambe ai prezzi di esecuzione (la colonna "Pips" della UI), `cost_pips` il costo stimato all'ingresso, `slippage_pips` la differenza fra quotazione vista e prezzo eseguito sommata sulle gambe, `exit_reason` uno dei codici sopra più `manual`, `closed_by_broker`, `leg_closed_by_broker`, `end_of_data`, e dalla 5.0 `leg_risk_unwind` (gamba A eseguita in ritardo e richiusa, o B non coperta dal margine; dalla 5.1 anche la gamba A di un'aggiunta richiusa, con il `basket_id` del basket), `margin_guard` (chiuso dalla guardia del margine), `orphan_closed` (gamba orfana del bot adottata e chiusa alla riconciliazione), `bonifica_orfana` (chiusa dalla bonifica con conferma), `kill_switch`/`equity_stop` anche per le gambe singole. Le righe di una gamba singola hanno `entry_z`, `exit_z`, `pips_gross` e `cost_*` vuoti e `buy_cross` = verso della gamba. ## `data/ledger/orders.jsonl` (dalla 5.0) @@ -65,7 +81,7 @@ Una riga per **ogni ordine inviato** e per **ogni cambio del suo stato** (append | `prezzo_richiesto`, `prezzo_eseguito`, `slippage_pip` | quotazione vista all'invio, prezzo del server, differenza in pip con il segno del costo | | `stato`, `stato_id` | l'ultima parola del server (`Submitted`, `Received`, `Placed`, `Filled`, `Rejected`, …, `Unknown` quando non ha risposto), con l'id numerico di eToro | | `esito` | `Pending`, `Filled`, `Rejected`, `Cancelled` | -| `order_id`, `position_id`, `client_ref` | le tre chiavi | +| `order_id`, `position_id`, `client_ref` | le tre chiavi; dalla 5.1 anche le righe di chiusura (`Close`, `Unwind`) portano il `position_id` della posizione chiusa, la chiave dello storico eToro | | `fee` | commissioni riportate dal server all'esecuzione | | `evento` | `inviato`, `stato`, `risolto` | | `motivazione` | la motivazione della decisione o l'errore del server | @@ -76,7 +92,9 @@ Il registro degli ordini: `savedUtc` e l'array `orders` con gli stessi campi di ## `data/state/baskets_state.json` (campi aggiunti dalla 5.0) -`peakNetEquity` (picco dell'equity al netto dei movimenti di cassa), `cumulativeCashFlow`, `lastBalance` e `lastBalanceUtc` (per riconoscere un deposito avvenuto a bot spento), `pendingEntries` (un elemento per basket in `PendingA`/`PendingB`: `name`, `state`, `basketId` e il piano `pending` con unità, TP, stop, riferimenti cliente e la gamba A eseguita), `haltResidue` (le posizioni del bot rimaste sul conto dopo un kill-switch: `positionId`, `symbol`, `isBuy`, `units`, `openedUtc`, `origin`, `basket`, `reason`). `peakEquity` resta per compatibilità e vale `peakNetEquity + cumulativeCashFlow`. +`peakNetEquity` (picco dell'equity al netto dei movimenti di cassa), `cumulativeCashFlow`, `lastBalance` e `lastBalanceUtc` (per riconoscere un deposito avvenuto a bot spento), `pendingEntries` (un elemento per basket in `PendingA`/`PendingB`: `name`, `state`, `basketId` e il piano `pending` con unità, TP, stop, riferimenti cliente e la gamba A eseguita), `haltResidue` (le posizioni del bot rimaste sul conto dopo un kill-switch: `positionId`, `symbol`, `isBuy`, `units`, `openedUtc`, `origin`, `basket`, `reason`). `peakEquity` resta per compatibilità e vale `peakNetEquity + cumulativeCashFlow`. `dayStartEquity` è l'equity **netta** (al netto dei movimenti di cassa) alla prima lettura del conto del giorno UTC: la base della perdita giornaliera. + +Dalla 5.1 **`pendingSettlements` sostituisce `todayRealized`**: `todayRealized` (5.0) conteneva la somma dei proceeds e non viene più né scritto né letto; «P&L oggi» si ricalcola dallo storico eToro. `pendingSettlements` è la coda delle chiusure che aspettano lo storico, un elemento per chiusura: `key` (la chiave della riga), `rowCsv` (la riga di `baskets.csv` come verrà scritta, con la stima nei campi P&L), `ids` (le posizioni eToro), `estimate` (null se sconosciuta), `closedUtc`, `learn` (se il regolamento istruisce i modelli: solo i basket, mai le stime), `volContext` (il terzile di volatilità alla chiusura, per il bandit), `title` e `detail` (il messaggio). Un riavvio non perde niente: la coda riparte dallo stato. ## `data/state/heartbeat.json` e `data/state/instance.lock` (dalla 5.0) diff --git a/Encelado/docs/RISK_RULES.md b/Encelado/docs/RISK_RULES.md index 5618fdd..e0cb711 100644 --- a/Encelado/docs/RISK_RULES.md +++ b/Encelado/docs/RISK_RULES.md @@ -7,7 +7,7 @@ Tutte le regole di §10 della specifica, con il valore di fabbrica, dove sta e c | Modalità di esecuzione | `Demo` | `encelado.json` → `run.executionMode` (`Paper`, `Demo`, `Live`) | operatore; `Live` richiede `run.allowLive = true` **e** la frase `CONFERMO LIVE` scritta all'avvio (o `--confirm-live "CONFERMO LIVE"` in headless) | | Approvazione dei singoli ordini | nessuna, in nessuna modalità (D-20, ADR-0005) | codice | nessuno. Il bot apre, aggiunge e chiude da solo; i gate umani sono l'avvio del reale, il kill-switch, il reset dopo un equity stop e il cambio di preset | | Equity stop | 9 % dal picco di equity | `strategy.json` → `equityStopPct` | operatore; scatta → chiude tutto, blocca, richiede reset con motivazione scritta (finestra o `reset ` in headless), che finisce nel ledger; il picco riparte dall'equity del reset | -| Perdita giornaliera massima | 3 % dell'equity di inizio giornata (UTC) | `strategy.json` → `dailyLossPct` | operatore; blocca le nuove entrate fino al giorno dopo, non chiude | +| Perdita giornaliera massima | 3 % dell'equity di inizio giornata (UTC). Formula (la stessa nel motore e nel backtest, `DailyLoss.IsHit`): `E₀ − E ≥ E₀ × dailyLossPct / 100`, dove `E = equity − cassa cumulata` è l'**equity netta** attuale (realizzato e aperto insieme, depositi e prelievi esclusi) ed `E₀` l'equity netta alla prima lettura del conto dopo le 00:00 UTC. Un deposito non nasconde una perdita, un prelievo non la inventa; finché una chiusura non è spiegata dallo storico eToro il saldo non viene giudicato come movimento di cassa. «P&L oggi» è un'altra cosa: il realizzato netto (`netProfit − fees`) delle posizioni del bot chiuse oggi, dallo storico eToro; accanto c'è la «variazione dell'equity netta da mezzanotte» `E − E₀`, che è ciò che la regola guarda. Fino alla 5.0.0 la regola sommava i proceeds delle chiusure e non scattava mai dopo la prima chiusura del giorno | `strategy.json` → `dailyLossPct` | operatore; blocca le nuove entrate finché la perdita resta oltre la soglia e al più fino alle 00:00 UTC (si rivaluta a ogni decisione, come nel backtest: se l'equity netta risale sopra la soglia le entrate riprendono), non chiude | | Rischio per basket | 0,25 / 0,50 / 1,00 % (preset) | `strategy.json` → preset o `riskPerBasketPct` | operatore; il cambio di preset a caldo non tocca i basket aperti | | Perdita massima per basket | 1,5 % dell'equity all'ingresso | `strategy.json` → `maxLossPerBasketPct` | operatore; mai disattivabile | | Stop di basket su z | 3,0 / 3,5 / 4,0 (preset) | `strategy.json` → preset o `zStop` | operatore; mai disattivabile (solo il backtest lo spegne, nel test di falsificazione 3) | diff --git a/Encelado/src/Encelado.Core/Baskets/Backtest/BacktestBroker.cs b/Encelado/src/Encelado.Core/Baskets/Backtest/BacktestBroker.cs index 9a2a4b2..71e0ef4 100644 --- a/Encelado/src/Encelado.Core/Baskets/Backtest/BacktestBroker.cs +++ b/Encelado/src/Encelado.Core/Baskets/Backtest/BacktestBroker.cs @@ -210,15 +210,19 @@ public sealed class BacktestBroker : IBroker { if (!_positions.Remove(positionId, out Position? p)) { - return Task.FromResult(new CloseOutcome(false, true, 0, 0, 0, _now, 0, "posizione inesistente")); + return Task.FromResult(new CloseOutcome(false, true, 0, 0, 0, _now, double.NaN, "posizione inesistente") { PositionId = positionId }); } double exit = Exit(p, withSlippage: true); double pnl = PipMath.LegPnlUsd(p.Instrument.Symbol, p.IsBuy, p.Units, p.Open, exit, MidOf); - pnl = (double.IsNaN(pnl) ? 0 : pnl) - p.Fees; - _balance += pnl; + pnl = double.IsNaN(pnl) ? 0 : pnl; + double net = pnl - p.Fees; + _balance += net; + + // The history keeps eToro's meaning (profit before fees, fees apart); the close answer + // carries the final net result of the position, fees included. _closed.Add(new ClosedTrade(p.Id, p.Instrument.Id, p.IsBuy, p.Units, p.Open, exit, p.OpenedUtc, _now, pnl, p.Fees)); - return Task.FromResult(new CloseOutcome(true, false, _nextId++, exit, p.Units, _now, pnl, string.Empty)); + return Task.FromResult(new CloseOutcome(true, false, _nextId++, exit, p.Units, _now, net, string.Empty) { PositionId = p.Id }); } public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true); diff --git a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs index beb6668..216c5ff 100644 --- a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs +++ b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs @@ -314,7 +314,8 @@ public static class BasketBacktest dayStartEquity = equityNow; } - bool dailyLoss = dayStartEquity > 0 && (dayStartEquity - equityNow) / dayStartEquity >= config.DailyLossPct / 100.0; + // The same rule as the live engine: the replay has no cash movements, so its equity is net equity. + bool dailyLoss = DailyLoss.IsHit(dayStartEquity, equityNow, config.DailyLossPct); foreach (Slot slot in slots) { diff --git a/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs b/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs index 4f56dc5..6592f90 100644 --- a/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs +++ b/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs @@ -30,9 +30,20 @@ public sealed record EntryOutcome( public TrackedOrder? PendingOrder { get; init; } public bool IsPending => PendingLeg != PendingLeg.None; + + /// When a leg was undone (leg_risk_unwind): the close of that leg, whose realised result is settled like any other. + public CloseOutcome? UnwindClose { get; init; } + + /// The leg that was undone, as it was filled. + public BasketLeg? UnwoundLeg { get; init; } } -/// What closing a basket produced. +/// +/// What closing a basket produced. is the venue's final number +/// when every close carried one (, the simulators), otherwise the +/// estimate from the exit prices (entry fees and accrued overnight subtracted) that the +/// venue's history settles later; NaN when not even the estimate is possible. +/// public sealed record ExitOutcome( bool Ok, double ExitPriceA, @@ -43,7 +54,14 @@ public sealed record ExitOutcome( double SlippagePipsB, string Error, DateTime ClosedUtc, - IReadOnlyList StuckPositionIds); + IReadOnlyList StuckPositionIds) +{ + /// True when every close carried a final result (simulators); false: is an estimate to settle on the venue's history. + public bool PnlFinal { get; init; } + + /// Every close that went through, each with its position id. + public IReadOnlyList Closes { get; init; } = []; +} /// /// The two-leg execution protocol of §5.7, over any , with the @@ -237,7 +255,11 @@ public sealed class BasketExecutor { CloseOutcome undo = await CloseLegAsync(legA.PositionId, legA.InstrumentId, TrackClose(legA, ctx.Name, plan.BasketId, OrderLeg.Unwind, "leg_risk_unwind: " + why), ct).ConfigureAwait(false); string error = $"{why}; gamba A {(undo.Closed ? "richiusa" : "NON richiusa: " + undo.Error)}"; - return new EntryOutcome(false, null, undo.Closed, error, SlipPips(ctx.A, legA.IsBuy, plan.QuoteA, legA.EntryPrice), 0, Environment.TickCount64 - t0); + return new EntryOutcome(false, null, undo.Closed, error, SlipPips(ctx.A, legA.IsBuy, plan.QuoteA, legA.EntryPrice), 0, Environment.TickCount64 - t0) + { + UnwindClose = undo, + UnwoundLeg = legA, + }; } /// Closes a lone leg (a pending A whose signal decayed, an orphan): three attempts, verified on the position list. @@ -264,6 +286,7 @@ public sealed class BasketExecutor SentUtc = DateTime.UtcNow, Mode = _mode, Motivazione = reason, + PositionId = position.PositionId, }; return CloseLegAsync(position.PositionId, position.InstrumentId, track, ct); } @@ -347,9 +370,26 @@ public sealed class BasketExecutor SentUtc = DateTime.UtcNow, Mode = _mode, Motivazione = "leg_risk_unwind dell'aggiunta", + PositionId = a.PositionId, }; CloseOutcome undo = await CloseLegAsync(a.PositionId, ctx.A.Instrument.Id, undoTrack, ct).ConfigureAwait(false); - return new EntryOutcome(false, p, undo.Closed, $"aggiunta su B non eseguita: {Describe(b)}", 0, 0, Environment.TickCount64 - t0); + BasketLeg added = new() + { + Symbol = ctx.A.Symbol, + InstrumentId = ctx.A.Instrument.Id, + IsBuy = p.A.IsBuy, + Units = a.Units > 0 ? a.Units : sizing.UnitsA, + EntryPrice = a.FillRate > 0 ? a.FillRate : quoteA, + PositionId = a.PositionId, + ClientRef = reqA.ClientRef, + OpenedUtc = a.TimeUtc == default ? DateTime.UtcNow : a.TimeUtc, + EntryFeesUsd = a.Fees, + }; + return new EntryOutcome(false, p, undo.Closed, $"aggiunta su B non eseguita: {Describe(b)}", 0, 0, Environment.TickCount64 - t0) + { + UnwindClose = undo, + UnwoundLeg = added, + }; } Merge(p.A, a, sizing.UnitsA, quoteA, reqA.ClientRef); @@ -378,26 +418,36 @@ public sealed class BasketExecutor double quoteA = p.A.IsBuy ? ctx.A.Quote.Bid : ctx.A.Quote.Ask; double quoteB = p.B.IsBuy ? ctx.B.Quote.Bid : ctx.B.Quote.Ask; List stuck = []; + List closes = []; DateTime closedUtc = DateTime.UtcNow; - (double priceA, double pnlA, bool okA) = await CloseLegAllAsync(p.A, ctx.A.Instrument.Id, ctx.Name, p.BasketId, reason, stuck, ct).ConfigureAwait(false); - (double priceB, double pnlB, bool okB) = await CloseLegAllAsync(p.B, ctx.B.Instrument.Id, ctx.Name, p.BasketId, reason, stuck, ct).ConfigureAwait(false); + (double priceA, double pnlA, bool okA) = await CloseLegAllAsync(p.A, ctx.A.Instrument.Id, ctx.Name, p.BasketId, reason, stuck, closes, ct).ConfigureAwait(false); + (double priceB, double pnlB, bool okB) = await CloseLegAllAsync(p.B, ctx.B.Instrument.Id, ctx.Name, p.BasketId, reason, stuck, closes, ct).ConfigureAwait(false); double exitA = priceA > 0 ? priceA : quoteA; double exitB = priceB > 0 ? priceB : quoteB; - // Realised P&L: the venue's number when it reports one, our own otherwise. - double own = p.NetPnlUsd(exitA, exitB, _mid); - double pnl = okA && okB && (pnlA != 0 || pnlB != 0) ? pnlA + pnlB - p.AccruedFeesUsd : (double.IsNaN(own) ? 0 : own); + // Realised P&L. A simulator gives the final net result of every position (its fees + // included): that is the number, and nothing is subtracted again. eToro gives none + // (NaN): the number here is the estimate from the exit prices — entry fees and + // accrued overnight already subtracted — and the trade history settles it later. + // NaN stays NaN: an unknown result is never read as zero. + double estimate = p.NetPnlUsd(exitA, exitB, _mid); + bool final = okA && okB && double.IsFinite(pnlA) && double.IsFinite(pnlB); + double pnl = final ? pnlA + pnlB : estimate; double pips = p.PipsTotal(exitA, exitB, ctx.A.Instrument.Pip, ctx.B.Instrument.Pip); bool ok = okA && okB; return new ExitOutcome(ok, exitA, exitB, pnl, pips, SlipPips(ctx.A, !p.A.IsBuy, quoteA, exitA), SlipPips(ctx.B, !p.B.IsBuy, quoteB, exitB), - ok ? string.Empty : $"gambe non chiuse: {string.Join(", ", stuck)}", closedUtc, stuck); + ok ? string.Empty : $"gambe non chiuse: {string.Join(", ", stuck)}", closedUtc, stuck) + { + PnlFinal = final, + Closes = closes, + }; } - private async Task<(double Price, double Pnl, bool Ok)> CloseLegAllAsync(BasketLeg leg, long instrumentId, string basket, string basketId, string reason, List stuck, CancellationToken ct) + private async Task<(double Price, double Pnl, bool Ok)> CloseLegAllAsync(BasketLeg leg, long instrumentId, string basket, string basketId, string reason, List stuck, List closes, CancellationToken ct) { double weighted = 0, units = 0, pnl = 0; bool ok = true; @@ -407,9 +457,18 @@ public sealed class BasketExecutor CloseOutcome c = await CloseLegAsync(id, instrumentId, TrackClose(leg, basket, basketId, OrderLeg.Close, reason, id, expected), ct).ConfigureAwait(false); if (c.Closed) { + closes.Add(c); double u = c.Units > 0 ? c.Units : expected; - weighted += c.CloseRate * u; - units += u; + + // A close seen only on the position list has no rate: it must not drag the + // leg's average exit towards zero. Only the closes with a price make the price. + if (c.CloseRate > 0) + { + weighted += c.CloseRate * u; + units += u; + } + + // NaN (unknown) makes the leg's sum unknown on purpose. pnl += c.RealizedPnl; } else @@ -422,7 +481,7 @@ public sealed class BasketExecutor return (units > 0 ? weighted / units : 0, pnl, ok); } - /// Three attempts with backoff; a pending outcome is re-checked against the position list. + /// Three attempts with backoff; a pending outcome is re-checked against the position list. The outcome always names the position. private async Task CloseLegAsync(long positionId, long instrumentId, TrackedOrder? track, CancellationToken ct) { if (track is not null) @@ -430,7 +489,7 @@ public sealed class BasketExecutor _tracker?.Register(track); } - CloseOutcome last = new(false, false, 0, 0, 0, DateTime.UtcNow, 0, "non tentata"); + CloseOutcome last = new(false, false, 0, 0, 0, DateTime.UtcNow, double.NaN, "non tentata") { PositionId = positionId }; for (int attempt = 0; attempt < 3; attempt++) { try @@ -439,9 +498,10 @@ public sealed class BasketExecutor } catch (BrokerException ex) { - last = new CloseOutcome(false, false, 0, 0, 0, DateTime.UtcNow, 0, ex.Message); + last = new CloseOutcome(false, false, 0, 0, 0, DateTime.UtcNow, double.NaN, ex.Message); } + last = last.PositionId > 0 ? last : last with { PositionId = positionId }; if (last.Closed) { ApplyClose(track, last); @@ -463,7 +523,8 @@ public sealed class BasketExecutor if (positions.All(x => x.PositionId != positionId)) { // Gone from the account: closed by the venue (our order, or a native stop). - last = new CloseOutcome(true, false, last.OrderId, last.CloseRate, last.Units, DateTime.UtcNow, last.RealizedPnl, string.Empty); + // Whatever rate and result the last answer lacked stay unknown. + last = last with { Closed = true, Rejected = false, TimeUtc = DateTime.UtcNow, Error = string.Empty }; ApplyClose(track, last); return last; } @@ -480,7 +541,8 @@ public sealed class BasketExecutor return; } - OrderOutcome o = new(c.Closed, c.Rejected, c.OrderId, 0, c.CloseRate, c.Units, c.TimeUtc, 0, c.Closed ? "Closed" : c.Rejected ? "Rejected" : "Unknown", c.Error) + // The close line of orders.jsonl names the position it closed (the key of the venue's history). + OrderOutcome o = new(c.Closed, c.Rejected, c.OrderId, track.PositionId > 0 ? track.PositionId : c.PositionId, c.CloseRate, c.Units, c.TimeUtc, 0, c.Closed ? "Closed" : c.Rejected ? "Rejected" : "Unknown", c.Error) { RequestedUnits = track.RequestedUnits, Source = "venue", @@ -599,6 +661,7 @@ public sealed class BasketExecutor SentUtc = DateTime.UtcNow, Mode = _mode, Motivazione = (positionId > 0 ? string.Create(CultureInfo.InvariantCulture, $"posizione {positionId}: ") : string.Empty) + (reason.Length > 160 ? reason[..160] : reason), + PositionId = positionId > 0 ? positionId : leg.PositionId, }; private OrderRequest Request(SymbolSeries s, bool isBuy, double units, double quote, string reason) diff --git a/Encelado/src/Encelado.Core/Baskets/DailyLoss.cs b/Encelado/src/Encelado.Core/Baskets/DailyLoss.cs new file mode 100644 index 0000000..cb71558 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/DailyLoss.cs @@ -0,0 +1,27 @@ +namespace Encelado.Core.Baskets; + +/// +/// The daily-loss rule of docs/RISK_RULES.md, one formula for the live engine and +/// the backtest: the net equity (cash movements excluded) lost since 00:00 UTC reaches +/// dailyLossPct % of the net equity the day started with. It looks at equity, so +/// realised and unrealised results both count and a deposit cannot hide a loss. +/// +public static class DailyLoss +{ + /// dayStart − now ≥ dayStart × dailyLossPct / 100; false while either number is unknown. + public static bool IsHit(double dayStartNetEquity, double netEquityNow, double dailyLossPct) => + dayStartNetEquity > 0 && double.IsFinite(netEquityNow) && dailyLossPct > 0 && + dayStartNetEquity - netEquityNow >= dayStartNetEquity * dailyLossPct / 100.0; + + /// How much of the day's loss budget is used, between 0 and 1; NaN while unknown. + public static double UsedFraction(double dayStartNetEquity, double netEquityNow, double dailyLossPct) + { + if (!(dayStartNetEquity > 0) || !double.IsFinite(netEquityNow) || !(dailyLossPct > 0)) + { + return double.NaN; + } + + double budget = dayStartNetEquity * dailyLossPct / 100.0; + return Math.Clamp((dayStartNetEquity - netEquityNow) / budget, 0, 1); + } +} diff --git a/Encelado/src/Encelado.Core/Baskets/EquityTracker.cs b/Encelado/src/Encelado.Core/Baskets/EquityTracker.cs index 4f498f0..83a9dfd 100644 --- a/Encelado/src/Encelado.Core/Baskets/EquityTracker.cs +++ b/Encelado/src/Encelado.Core/Baskets/EquityTracker.cs @@ -47,10 +47,18 @@ public sealed class EquityTracker /// /// Records an account reading. is the realised /// net result (profit minus fees) of the positions closed since the previous reading, - /// which is the only legitimate reason for the cash balance to move. + /// which is the only legitimate reason for the cash balance to move. NaN means the + /// venue has not explained those closes yet (its history lags): no verdict is given, + /// the previous balance stays the reference so the next explained reading judges the + /// whole difference, and the peak does not move (an unbooked deposit must not raise it). /// public CashMovement? Observe(DateTime now, double balance, double equity, double closedNetSinceLast) { + if (!double.IsFinite(closedNetSinceLast)) + { + return null; + } + CashMovement? movement = null; if (double.IsFinite(LastBalance)) { @@ -78,6 +86,22 @@ public sealed class EquityTracker /// After a reset the peak restarts from the current equity. public void ResetPeak(double equity) => PeakNetEquity = NetEquity(equity); + /// + /// Takes the balance as the new reference without judging the difference: used at + /// startup when the history of the closes made while the bot was off cannot be read, + /// so their result is never booked as a deposit or a withdrawal. + /// + public void Rebase(DateTime now, double balance, double equity) + { + LastBalance = balance; + LastObservedUtc = now; + double net = NetEquity(equity); + if (net > PeakNetEquity) + { + PeakNetEquity = net; + } + } + /// Restores the persisted state; a peak saved by a version that knew no cash flows is taken as a net peak. public void Restore(double peakNetEquity, double cumulativeCashFlow, double lastBalance, DateTime lastObservedUtc) { diff --git a/Encelado/src/Encelado.Core/Baskets/FlattenProcedure.cs b/Encelado/src/Encelado.Core/Baskets/FlattenProcedure.cs index 9cf9e21..00dc9fb 100644 --- a/Encelado/src/Encelado.Core/Baskets/FlattenProcedure.cs +++ b/Encelado/src/Encelado.Core/Baskets/FlattenProcedure.cs @@ -6,7 +6,7 @@ namespace Encelado.Core.Baskets; /// A position the kill-switch must close, with what it is for the report. public sealed record FlattenTarget(long PositionId, long InstrumentId, string Symbol, bool IsBuy, double Units, string Basket, string Kind); -/// What the kill-switch did and what is left. +/// What the kill-switch did and what is left. sums only the closes whose result the venue gave; counts the others (eToro: all of them, settled later from the history). public sealed record FlattenReport( IReadOnlyList CancelledOrders, IReadOnlyList OrdersFilledMeanwhile, @@ -18,6 +18,21 @@ public sealed record FlattenReport( { /// The engine's state after the procedure: Halted when flat, Halted-Residuo otherwise. public string State => Flat ? "Halted" : "Halted-Residuo"; + + /// Closes whose realised result is not known yet. + public int UnknownPnl { get; init; } +} + +/// +/// What closing the targets did: the ids closed and refused, the realised result of the +/// closes that carried one (never a NaN read as zero), how many carried none, and every +/// close as the venue answered it. +/// +public sealed record FlattenCloses(List Closed, List Failed, double RealizedKnown, int UnknownPnl, IReadOnlyList<(FlattenTarget Target, CloseOutcome Close)> Outcomes) +{ + /// The realised part as text: the known sum, and how many wait for the venue's history. + public string Describe() => string.Create(CultureInfo.InvariantCulture, + $"{RealizedKnown:+0.00;-0.00} USD noti{(UnknownPnl > 0 ? $", {UnknownPnl} da confermare con lo storico eToro" : string.Empty)}"); } /// @@ -116,8 +131,12 @@ public sealed class FlattenProcedure(IBroker broker, OrderTracker tracker, Actio return (cancelled, filled); } - /// Step 2. Closes every target through ; returns the ids closed, the ids that refused, and the realised result. - public static async Task<(List Closed, List Failed, double Realized)> CloseTargetsAsync( + /// + /// Step 2. Closes every target through . The realised result + /// sums only the closes that carried one; a close without it (eToro's, always) is + /// counted apart and settled later from the venue's history. + /// + public static async Task CloseTargetsAsync( IReadOnlyList targets, Func> closer, Action log, CancellationToken ct) { ArgumentNullException.ThrowIfNull(targets); @@ -125,7 +144,9 @@ public sealed class FlattenProcedure(IBroker broker, OrderTracker tracker, Actio ArgumentNullException.ThrowIfNull(log); List closed = []; List failed = []; + List<(FlattenTarget, CloseOutcome)> outcomes = []; double realized = 0; + int unknown = 0; foreach (FlattenTarget t in targets) { CloseOutcome c; @@ -135,14 +156,26 @@ public sealed class FlattenProcedure(IBroker broker, OrderTracker tracker, Actio } catch (BrokerException ex) { - c = new CloseOutcome(false, false, 0, 0, 0, DateTime.UtcNow, 0, ex.Message); + c = new CloseOutcome(false, false, 0, 0, 0, DateTime.UtcNow, double.NaN, ex.Message); } + outcomes.Add((t, c.PositionId > 0 ? c : c with { PositionId = t.PositionId })); if (c.Closed) { closed.Add(t.PositionId); - realized += c.RealizedPnl; - log(string.Create(CultureInfo.InvariantCulture, $"kill-switch: chiusa {t.Kind} {t.PositionId} {t.Symbol} {(t.IsBuy ? "long" : "short")} {t.Units:0.##} ({c.RealizedPnl:+0.00;-0.00} USD)")); + string pnl; + if (double.IsFinite(c.RealizedPnl)) + { + realized += c.RealizedPnl; + pnl = c.RealizedPnl.ToString("+0.00;-0.00", CultureInfo.InvariantCulture) + " USD"; + } + else + { + unknown++; + pnl = "P&L dallo storico eToro"; + } + + log(string.Create(CultureInfo.InvariantCulture, $"kill-switch: chiusa {t.Kind} {t.PositionId} {t.Symbol} {(t.IsBuy ? "long" : "short")} {t.Units:0.##} ({pnl})")); } else { @@ -151,7 +184,7 @@ public sealed class FlattenProcedure(IBroker broker, OrderTracker tracker, Actio } } - return (closed, failed, realized); + return new FlattenCloses(closed, failed, realized, unknown, outcomes); } /// Step 3. Re-reads the positions until none of is there, or the timeout passes. Returns what is left. @@ -197,12 +230,12 @@ public sealed class FlattenProcedure(IBroker broker, OrderTracker tracker, Actio } } - (List closed, List failed, double realized) = await CloseTargetsAsync(all, closer, _log, ct).ConfigureAwait(false); + FlattenCloses closes = await CloseTargetsAsync(all, closer, _log, ct).ConfigureAwait(false); List residue = await VerifyFlatAsync([.. all.Select(static t => t.PositionId)], ct).ConfigureAwait(false); bool flat = residue.Count == 0; string summary = string.Create(CultureInfo.InvariantCulture, - $"{closed.Count} posizioni chiuse su {all.Count} ({realized:+0.00;-0.00} USD), {cancelled.Count} ordini annullati, {filledMeanwhile.Count} eseguiti nel frattempo, {_tracker.PendingCount} ancora senza esito; {(flat ? "conto piatto per le posizioni del bot" : $"RESIDUO: {string.Join(", ", residue)}")}"); - return new FlattenReport(cancelled, [.. filledMeanwhile.Select(static p => p.PositionId)], closed, residue, realized, flat, summary); + $"{closes.Closed.Count} posizioni chiuse su {all.Count} ({closes.Describe()}), {cancelled.Count} ordini annullati, {filledMeanwhile.Count} eseguiti nel frattempo, {_tracker.PendingCount} ancora senza esito; {(flat ? "conto piatto per le posizioni del bot" : $"RESIDUO: {string.Join(", ", residue)}")}"); + return new FlattenReport(cancelled, [.. filledMeanwhile.Select(static p => p.PositionId)], closes.Closed, residue, closes.RealizedKnown, flat, summary) { UnknownPnl = closes.UnknownPnl }; } /// The reset's first gate: a written reason of at least ten characters. diff --git a/Encelado/src/Encelado.Core/Baskets/History/BasketOutcomeRow.cs b/Encelado/src/Encelado.Core/Baskets/History/BasketOutcomeRow.cs index fc1a272..d724491 100644 --- a/Encelado/src/Encelado.Core/Baskets/History/BasketOutcomeRow.cs +++ b/Encelado/src/Encelado.Core/Baskets/History/BasketOutcomeRow.cs @@ -2,7 +2,13 @@ using System.Globalization; namespace Encelado.Core.Baskets.History; -/// One closed basket as baskets.csv records it. +/// +/// One closed basket (or lone leg) as baskets.csv records it. From 5.1 the P&L +/// columns hold the venue's history (netProfit − fees of the row's positions), or an +/// estimate flagged P&L: stima in the motivation when the history did not show +/// them in time. Rows are never edited: and +/// are set by the corrected reader from the correction lines of decisions.jsonl. +/// public sealed record BasketOutcomeRow( string BasketId, string RunId, @@ -29,6 +35,18 @@ public sealed record BasketOutcomeRow( { public int Label => PnlNetUsd > 0 ? 1 : 0; + /// The P&L was not established from the venue (an estimate, or positions the history does not show): no label, out of training and of the reports. Never written to the file. + public bool Unverified { get; init; } + + /// A correction line was applied by the corrected reader. Never written to the file. + public bool Corrected { get; init; } + + /// The row may teach and be summed: its P&L is known and verified. + public bool HasLabel => !Unverified && double.IsFinite(PnlNetUsd); + + /// A lone leg (an unwind, an orphan): no entry z, not a basket. + public bool IsLoneLeg => !double.IsFinite(EntryZ); + public const string Header = "basket_id;run_id;basket;mode;preset;opened_utc;closed_utc;buy_cross;entry_z;exit_z;pnl_gross_usd;pnl_net_usd;pips_gross;cost_pips;cost_usd;slippage_pips;adds;bars_held;exit_reason;equity_at_entry;p_ml_at_entry;label;durata_min;motivazione"; @@ -38,7 +56,7 @@ public sealed record BasketOutcomeRow( OpenedUtc.ToString("O", CultureInfo.InvariantCulture), ClosedUtc.ToString("O", CultureInfo.InvariantCulture), BuyCross ? "1" : "0", N(EntryZ), N(ExitZ), N(PnlGrossUsd), N(PnlNetUsd), N(PipsGross), N(CostPips), N(CostUsd), N(SlippagePips), Adds.ToString(CultureInfo.InvariantCulture), BarsHeld.ToString(CultureInfo.InvariantCulture), ExitReason, N(EquityAtEntry), N(PMlAtEntry), - Label.ToString(CultureInfo.InvariantCulture), ((ClosedUtc - OpenedUtc).TotalMinutes).ToString("0", CultureInfo.InvariantCulture), + double.IsFinite(PnlNetUsd) ? Label.ToString(CultureInfo.InvariantCulture) : string.Empty, ((ClosedUtc - OpenedUtc).TotalMinutes).ToString("0", CultureInfo.InvariantCulture), Motivazione.Replace(';', ',').Replace('\n', ' ').Replace('\r', ' '), ]); diff --git a/Encelado/src/Encelado.Core/Baskets/History/HistoryBuilder.cs b/Encelado/src/Encelado.Core/Baskets/History/HistoryBuilder.cs index 381b457..111c4e8 100644 --- a/Encelado/src/Encelado.Core/Baskets/History/HistoryBuilder.cs +++ b/Encelado/src/Encelado.Core/Baskets/History/HistoryBuilder.cs @@ -96,48 +96,43 @@ public static class HistoryBuilder Func pipOf, DateTime nowUtc) { - ArgumentNullException.ThrowIfNull(closed); - ArgumentNullException.ThrowIfNull(open); ArgumentNullException.ThrowIfNull(baskets); ArgumentNullException.ThrowIfNull(orders); + return Positions(closed, open, new PositionOrigins(orders, baskets), cash, symbolOf, pipOf, nowUtc); + } + + /// The same, with the owner of each position decided by an index the caller already holds. + public static List Positions( + IReadOnlyList closed, + IReadOnlyList open, + PositionOrigins origins, + IReadOnlyList cash, + Func symbolOf, + Func pipOf, + DateTime nowUtc) + { + ArgumentNullException.ThrowIfNull(closed); + ArgumentNullException.ThrowIfNull(open); + ArgumentNullException.ThrowIfNull(origins); ArgumentNullException.ThrowIfNull(cash); ArgumentNullException.ThrowIfNull(symbolOf); ArgumentNullException.ThrowIfNull(pipOf); - // Whose is each position id: the last order line that produced it. - Dictionary byPosition = []; - foreach (OrderRecord o in orders) - { - if (o.PositionId > 0 && o.Leg is not (OrderLeg.Close or OrderLeg.Unwind)) - { - byPosition[o.PositionId] = o; - } - } - - Dictionary byBasketId = new(StringComparer.Ordinal); - foreach (BasketOutcomeRow b in baskets) - { - if (b.BasketId.Length > 0) - { - byBasketId[b.BasketId] = b; - } - } - List rows = []; foreach (ClosedTrade t in closed) { string symbol = symbolOf(t.InstrumentId); - (string origin, string basketId, string basket, string exit) = Classify(t.PositionId, t.OpenedUtc, byPosition, byBasketId, baskets); + (string origin, string basketId, string basket, string exit) = origins.Classify(t.PositionId); double pip = pipOf(symbol); double pips = pip > 0 ? (t.IsBuy ? t.CloseRate - t.OpenRate : t.OpenRate - t.CloseRate) / pip : double.NaN; rows.Add(new PositionRecord(t.PositionId, symbol, t.IsBuy, t.Units, t.OpenRate, t.CloseRate, t.OpenedUtc, t.ClosedUtc, - t.NetProfit, t.Fees, t.NetProfit - t.Fees, pips, origin, basketId, basket, exit, false, origin == "esterna" ? "posizione non aperta dal bot" : string.Empty)); + t.NetProfit, t.Fees, t.NetUsd, pips, origin, basketId, basket, exit, false, origin == PositionOwner.ForeignOrigin ? "posizione non aperta dal bot" : string.Empty)); } foreach (BrokerPosition p in open) { string symbol = symbolOf(p.InstrumentId); - (string origin, string basketId, string basket, _) = Classify(p.PositionId, p.OpenedUtc, byPosition, byBasketId, baskets); + (string origin, string basketId, string basket, _) = origins.Classify(p.PositionId); double pip = pipOf(symbol); double pips = pip > 0 && p.CurrentRate > 0 ? (p.IsBuy ? p.CurrentRate - p.OpenRate : p.OpenRate - p.CurrentRate) / pip : double.NaN; rows.Add(new PositionRecord(p.PositionId, symbol, p.IsBuy, p.Units, p.OpenRate, p.CurrentRate, p.OpenedUtc, null, @@ -154,31 +149,6 @@ public static class HistoryBuilder return rows; } - private static (string Origin, string BasketId, string Basket, string Exit) Classify(long positionId, DateTime openedUtc, Dictionary byPosition, Dictionary byBasketId, IReadOnlyList baskets) - { - if (byPosition.TryGetValue(positionId, out OrderRecord? o)) - { - if (o.BasketId.Length > 0 && byBasketId.TryGetValue(o.BasketId, out BasketOutcomeRow? b)) - { - bool lone = b.ExitReason is "leg_risk_unwind" or "orphan_closed" or "bonifica_orfana" || !double.IsFinite(b.EntryZ); - return (lone ? "orfana-bot" : "basket", o.BasketId, o.Basket, b.ExitReason); - } - - return ("orfana-bot", o.BasketId, o.Basket, string.Empty); - } - - // Before orders.jsonl existed (4.0.0) the only trace is a lone-leg row in baskets.csv whose motivation carries the position id. - foreach (BasketOutcomeRow b in baskets) - { - if (b.Motivazione.Contains(positionId.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal)) - { - return ("orfana-bot", b.BasketId, b.Basket, b.ExitReason); - } - } - - return ("esterna", string.Empty, string.Empty, string.Empty); - } - /// The standard periods of the Storico page, computed on the closed positions of the bot (cash movements apart). public static List Periods(IReadOnlyList positions, DateTime nowUtc, (DateTime From, DateTime To)? custom = null) { diff --git a/Encelado/src/Encelado.Core/Baskets/History/PnlCorrections.cs b/Encelado/src/Encelado.Core/Baskets/History/PnlCorrections.cs new file mode 100644 index 0000000..8e09976 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/History/PnlCorrections.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Text.Json; + +namespace Encelado.Core.Baskets.History; + +/// +/// One correzione line of decisions.jsonl with tipo = pnl_realizzato: +/// the realised result of one row of baskets.csv, established from the venue's +/// history, or the admission that it could not be ( false). The row +/// itself is never edited; the corrected reader applies the newest line for its key. +/// +public sealed record PnlCorrectionRecord(DateTime Ts, string RowKey, double PnlGrossUsd, double PnlNetUsd, bool Verified) +{ + public const string Evento = "correzione"; + + public const string Kind = "pnl_realizzato"; + + /// The key of a row: basket id and closing time (round-trip format), so lone legs with an empty basket id are told apart too. + public static string KeyOf(BasketOutcomeRow row) + { + ArgumentNullException.ThrowIfNull(row); + return row.BasketId + "|" + Utc(row.ClosedUtc).ToString("O", CultureInfo.InvariantCulture); + } + + /// Reads a ledger line; null when it is not a P&L correction (or is damaged). + public static PnlCorrectionRecord? TryParse(string line) + { + if (string.IsNullOrEmpty(line) || !line.Contains(Kind, StringComparison.Ordinal)) + { + return null; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + if (Str(r, "evento") != Evento || Str(r, "tipo") != Kind) + { + return null; + } + + string key = Str(r, "riga"); + if (key.Length == 0) + { + return null; + } + + bool verified = r.TryGetProperty("verificata", out JsonElement v) && v.ValueKind == JsonValueKind.True; + return new PnlCorrectionRecord(LedgerTime(r, "ts"), key, Num(r, "pnl_gross_corretto"), Num(r, "pnl_net_corretto"), verified); + } + catch (JsonException) + { + return null; + } + } + + internal static DateTime Utc(DateTime t) => t.Kind switch + { + DateTimeKind.Local => t.ToUniversalTime(), + DateTimeKind.Unspecified => DateTime.SpecifyKind(t, DateTimeKind.Utc), + _ => t, + }; + + internal static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + internal static double Num(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : double.NaN; + + internal static DateTime LedgerTime(JsonElement e, string name) => + DateTime.TryParse(Str(e, name), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : default; +} + +/// +/// The corrected reading of baskets.csv: the file never changes; the newest P&L +/// correction of each row is applied on the way out, and a row whose P&L the venue could +/// not confirm — an unverified correction, or an estimate written after the settlement +/// timeout (P&L: stima in the motivation) — is marked : +/// it has no label, teaches nothing and is left out of the sums. +/// +public static class BasketCorrections +{ + /// The words the settlement writes in the motivation of a row whose P&L is an estimate. + public const string EstimateMarker = "P&L: stima"; + + /// The words of a row settled on the venue's history. + public const string VenueMarker = "P&L: storico eToro"; + + public static List Apply(IReadOnlyList rows, IEnumerable corrections) + { + ArgumentNullException.ThrowIfNull(rows); + Dictionary newest = Newest(corrections); + List result = new(rows.Count); + foreach (BasketOutcomeRow r in rows) + { + if (newest.TryGetValue(PnlCorrectionRecord.KeyOf(r), out PnlCorrectionRecord? c)) + { + result.Add(c.Verified && double.IsFinite(c.PnlNetUsd) + ? r with { PnlGrossUsd = double.IsFinite(c.PnlGrossUsd) ? c.PnlGrossUsd : c.PnlNetUsd, PnlNetUsd = c.PnlNetUsd, Corrected = true, Unverified = false } + : r with { PnlNetUsd = double.NaN, PnlGrossUsd = double.NaN, Corrected = true, Unverified = true }); + } + else if (r.Motivazione.Contains(EstimateMarker, StringComparison.Ordinal) || !double.IsFinite(r.PnlNetUsd)) + { + result.Add(r with { Unverified = true }); + } + else + { + result.Add(r); + } + } + + return result; + } + + /// The newest correction of every row key. + public static Dictionary Newest(IEnumerable corrections) + { + ArgumentNullException.ThrowIfNull(corrections); + Dictionary newest = new(StringComparer.Ordinal); + foreach (PnlCorrectionRecord c in corrections.OrderBy(static c => c.Ts)) + { + newest[c.RowKey] = c; + } + + return newest; + } +} + +/// The one-off correzione lines that are not about a single row: an unreliable feature, the range of notes whose P&L fields are proceeds. +public static class LedgerMarkers +{ + public const string FeatureUnreliable = "feature_inaffidabile"; + + public const string ProceedsNotes = "pnl_note_proceeds"; + + public const string BackfillEvento = "verifica_realizzato"; + + /// Reads a feature_inaffidabile line: the feature and the time until which it is unreliable. + public static bool TryParseFeatureMask(string line, out string feature, out DateTime untilUtc) + { + feature = string.Empty; + untilUtc = default; + if (string.IsNullOrEmpty(line) || !line.Contains(FeatureUnreliable, StringComparison.Ordinal)) + { + return false; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + if (PnlCorrectionRecord.Str(r, "evento") != PnlCorrectionRecord.Evento || PnlCorrectionRecord.Str(r, "tipo") != FeatureUnreliable) + { + return false; + } + + feature = PnlCorrectionRecord.Str(r, "feature"); + untilUtc = PnlCorrectionRecord.LedgerTime(r, "fino_a"); + return feature.Length > 0 && untilUtc != default; + } + catch (JsonException) + { + return false; + } + } + + /// True for a correzione line of the given tipo. + public static bool IsCorrectionOfKind(string line, string kind) + { + if (string.IsNullOrEmpty(line) || !line.Contains(kind, StringComparison.Ordinal)) + { + return false; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + return PnlCorrectionRecord.Str(r, "evento") == PnlCorrectionRecord.Evento && PnlCorrectionRecord.Str(r, "tipo") == kind; + } + catch (JsonException) + { + return false; + } + } + + /// Reads a verifica_realizzato line: the closing time of the last row it checked. + public static bool TryParseBackfill(string line, out DateTime untilUtc) + { + untilUtc = default; + if (string.IsNullOrEmpty(line) || !line.Contains(BackfillEvento, StringComparison.Ordinal)) + { + return false; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + if (PnlCorrectionRecord.Str(r, "evento") != BackfillEvento) + { + return false; + } + + untilUtc = PnlCorrectionRecord.LedgerTime(r, "fino_a"); + return untilUtc != default; + } + catch (JsonException) + { + return false; + } + } +} diff --git a/Encelado/src/Encelado.Core/Baskets/History/PositionMap.cs b/Encelado/src/Encelado.Core/Baskets/History/PositionMap.cs new file mode 100644 index 0000000..6693fb9 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/History/PositionMap.cs @@ -0,0 +1,283 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Encelado.Core.Broker; + +namespace Encelado.Core.Baskets.History; + +/// A leg_risk_unwind or orfana_chiusa note of decisions.jsonl that names the position it closed. +public sealed record LoneLegNote(DateTime Ts, string Evento, string BasketId, long PositionId, string Symbol, string ExitReason); + +/// The fill prices of a basket's two legs as its ingresso line wrote them (eseguito: A @ …, B @ …). +public sealed record EntryFill(string BasketId, DateTime Ts, double PriceA, double PriceB); + +/// +/// Which eToro positions a row of baskets.csv accounts for, from the bot's own files +/// only — so its realised result can be looked up in the venue's history by position id. +/// +/// A row written from 5.1 names its positions in the motivation (| posizioni: …). +/// A basket: every filled order of orders.jsonl for its basket id on legs A, B +/// and adds — except an add that was unwound at once (an Unwind order on the same +/// position, or, in older lines without the position, the leg_risk_unwind dell'aggiunta +/// of the same symbol within two minutes). Before orders.jsonl (4.0.x): the two fill +/// prices of its ingresso line matched on the history (same instrument, side and +/// opening rate, opened and closed at the row's times), when the basket had no adds. +/// A lone leg: the note that closed it (same exit reason and symbol, within two +/// minutes); else leg A of its basket id; else its motivation (gamba singola …) +/// matched on the history by instrument, side, units and rates. +/// +/// Nothing is guessed: when a step is ambiguous the row stays without positions and its +/// P&L is declared unverifiable. +/// +public sealed partial class PositionMap +{ + private static readonly TimeSpan NoteWindow = TimeSpan.FromSeconds(120); + private static readonly TimeSpan AddUnwindWindow = TimeSpan.FromSeconds(120); + + private readonly Dictionary> _byBasket = new(StringComparer.Ordinal); + private readonly List _notes; + private readonly Dictionary _fills = new(StringComparer.Ordinal); + + private PositionMap(List notes) + { + _notes = notes; + } + + public static PositionMap Build(IReadOnlyList orders, IReadOnlyList notes, IReadOnlyList fills) + { + ArgumentNullException.ThrowIfNull(orders); + ArgumentNullException.ThrowIfNull(notes); + ArgumentNullException.ThrowIfNull(fills); + PositionMap map = new([.. notes]); + + // The last line of every order is its state; the first says when it was sent. + Dictionary last = new(StringComparer.Ordinal); + Dictionary sent = new(StringComparer.Ordinal); + foreach (OrderRecord o in orders) + { + if (o.ClientRef.Length == 0) + { + continue; + } + + sent.TryAdd(o.ClientRef, o.Ts); + last[o.ClientRef] = o; + } + + foreach ((string clientRef, OrderRecord o) in last) + { + if (o.BasketId.Length == 0) + { + continue; + } + + if (!map._byBasket.TryGetValue(o.BasketId, out List<(OrderRecord, DateTime)>? list)) + { + list = []; + map._byBasket[o.BasketId] = list; + } + + list.Add((o, sent[clientRef])); + } + + foreach (EntryFill f in fills) + { + if (f.BasketId.Length > 0) + { + map._fills[f.BasketId] = f; + } + } + + return map; + } + + /// The positions of ; empty when the bot's files cannot establish them without guessing. + public IReadOnlyList IdsOf(BasketOutcomeRow row, IReadOnlyList history, Func instrumentOf) + { + ArgumentNullException.ThrowIfNull(row); + ArgumentNullException.ThrowIfNull(history); + ArgumentNullException.ThrowIfNull(instrumentOf); + + List named = NamedPositions(row.Motivazione); + if (named.Count > 0) + { + return named; + } + + return row.IsLoneLeg ? LoneLeg(row, history, instrumentOf) : Basket(row, history, instrumentOf); + } + + /// The ids a motivation names after posizioni: (rows written from 5.1). + public static List NamedPositions(string motivazione) + { + List ids = []; + if (string.IsNullOrEmpty(motivazione)) + { + return ids; + } + + foreach (Match m in NamedRegex().Matches(motivazione)) + { + foreach (string part in m.Groups[1].Value.Split([' ', ','], StringSplitOptions.RemoveEmptyEntries)) + { + if (long.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) && id > 0 && !ids.Contains(id)) + { + ids.Add(id); + } + } + } + + return ids; + } + + /// The marker a row's motivation carries so its positions can be found again: posizioni: 1 2 3. + public static string Mark(IEnumerable ids) + { + ArgumentNullException.ThrowIfNull(ids); + return "posizioni: " + string.Join(' ', ids.Where(static i => i > 0).Distinct().Select(static i => i.ToString(CultureInfo.InvariantCulture))); + } + + private List Basket(BasketOutcomeRow row, IReadOnlyList history, Func instrumentOf) + { + List ids = []; + if (row.BasketId.Length > 0 && _byBasket.TryGetValue(row.BasketId, out List<(OrderRecord Last, DateTime SentUtc)>? orders)) + { + List<(OrderRecord Last, DateTime SentUtc)> unwinds = [.. orders.Where(static o => o.Last.Leg == OrderLeg.Unwind)]; + foreach ((OrderRecord o, DateTime sentUtc) in orders) + { + if (o.Leg is not (OrderLeg.A or OrderLeg.B or OrderLeg.Add) || o.Resolution != OrderResolution.Filled || o.PositionId <= 0) + { + continue; + } + + if (o.Leg == OrderLeg.Add && IsUnwound(o, sentUtc, unwinds)) + { + continue; + } + + if (!ids.Contains(o.PositionId)) + { + ids.Add(o.PositionId); + } + } + + if (ids.Count > 0) + { + return ids; + } + } + + // 4.0.x: no order register. The fill prices of the ingresso line, only without adds + // (the adds' positions are not written anywhere) and only when unambiguous. + if (row.Adds > 0 || !_fills.TryGetValue(row.BasketId, out EntryFill? fill)) + { + return []; + } + + string[] pair = row.Basket.Split('/'); + if (pair.Length != 2 || !SyntheticCross.TryDerive(pair[0], pair[1], out SyntheticCross? cross) || cross is null) + { + return []; + } + + (bool buyA, bool buyB) = cross.Legs(row.BuyCross); + long a = Unique(history, instrumentOf(pair[0]), buyA, fill.PriceA, row); + long b = Unique(history, instrumentOf(pair[1]), buyB, fill.PriceB, row); + return a > 0 && b > 0 && a != b ? [a, b] : []; + } + + private static bool IsUnwound(OrderRecord add, DateTime addSentUtc, List<(OrderRecord Last, DateTime SentUtc)> unwinds) + { + foreach ((OrderRecord u, DateTime sentUtc) in unwinds) + { + if (u.PositionId > 0) + { + if (u.PositionId == add.PositionId) + { + return true; + } + + continue; + } + + // Lines written before 5.1 carry no position on the unwind: the add of the same + // symbol undone within two minutes by the "leg_risk_unwind dell'aggiunta". + if (u.Symbol.Equals(add.Symbol, StringComparison.OrdinalIgnoreCase) && + u.Motivazione.Contains("aggiunta", StringComparison.OrdinalIgnoreCase) && + sentUtc >= addSentUtc && sentUtc - addSentUtc <= AddUnwindWindow) + { + return true; + } + } + + return false; + } + + private static long Unique(IReadOnlyList history, long instrumentId, bool isBuy, double openRate, BasketOutcomeRow row) + { + if (instrumentId <= 0 || !(openRate > 0)) + { + return 0; + } + + List hits = [.. history.Where(t => t.InstrumentId == instrumentId && t.IsBuy == isBuy && Near(t.OpenRate, openRate) && + (t.OpenedUtc - row.OpenedUtc).Duration() <= TimeSpan.FromMinutes(10) && (t.ClosedUtc - row.ClosedUtc).Duration() <= TimeSpan.FromMinutes(15))]; + return hits.Count == 1 ? hits[0].PositionId : 0; + } + + private List LoneLeg(BasketOutcomeRow row, IReadOnlyList history, Func instrumentOf) + { + Match described = LoneRegex().Match(row.Motivazione); + string symbol = described.Success ? described.Groups[3].Value : string.Empty; + + // 1. The note written when the leg was closed. + LoneLegNote? note = _notes + .Where(n => n.PositionId > 0 && (n.ExitReason.Length == 0 || n.ExitReason == row.ExitReason) && + (n.Symbol.Length == 0 || symbol.Length == 0 || n.Symbol.Equals(symbol, StringComparison.OrdinalIgnoreCase)) && + (n.Ts - row.ClosedUtc).Duration() <= NoteWindow) + .OrderBy(n => (n.Ts - row.ClosedUtc).Duration()) + .FirstOrDefault(); + if (note is not null) + { + return [note.PositionId]; + } + + // 2. Leg A of the basket attempt it belonged to (a pending entry unwound). + if (row.BasketId.Length > 0 && _byBasket.TryGetValue(row.BasketId, out List<(OrderRecord Last, DateTime SentUtc)>? orders)) + { + List legA = [.. orders.Where(static o => o.Last.Leg == OrderLeg.A && o.Last.Resolution == OrderResolution.Filled && o.Last.PositionId > 0) + .Select(static o => o.Last.PositionId).Distinct()]; + if (legA.Count == 1) + { + return legA; + } + } + + // 3. What the motivation says: instrument, side, units, entry and exit rate. + if (!described.Success) + { + return []; + } + + bool isBuy = described.Groups[1].Value == "long"; + double units = double.Parse(described.Groups[2].Value, CultureInfo.InvariantCulture); + double entry = double.Parse(described.Groups[4].Value, CultureInfo.InvariantCulture); + double exit = double.Parse(described.Groups[5].Value, CultureInfo.InvariantCulture); + long instrumentId = instrumentOf(symbol); + if (instrumentId <= 0) + { + return []; + } + + List hits = [.. history.Where(t => t.InstrumentId == instrumentId && t.IsBuy == isBuy && Math.Abs(t.Units - units) <= 0.01 && + Near(t.OpenRate, entry) && (exit <= 0 || Near(t.CloseRate, exit)) && (t.ClosedUtc - row.ClosedUtc).Duration() <= TimeSpan.FromDays(1))]; + return hits.Count == 1 ? [hits[0].PositionId] : []; + } + + private static bool Near(double a, double b) => Math.Abs(a - b) <= 1e-6 * Math.Max(1, Math.Abs(b)); + + [GeneratedRegex(@"posizioni: ([0-9][0-9 ,]*)", RegexOptions.CultureInvariant)] + private static partial Regex NamedRegex(); + + [GeneratedRegex(@"gamba singola (long|short) ([0-9]+(?:\.[0-9]+)?) ([A-Z]{6}) @ ([0-9]+(?:\.[0-9]+)?) chiusa @ ([0-9]+(?:\.[0-9]+)?)", RegexOptions.CultureInvariant)] + private static partial Regex LoneRegex(); +} diff --git a/Encelado/src/Encelado.Core/Baskets/History/PositionOrigins.cs b/Encelado/src/Encelado.Core/Baskets/History/PositionOrigins.cs new file mode 100644 index 0000000..0273c5b --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/History/PositionOrigins.cs @@ -0,0 +1,107 @@ +using System.Globalization; + +namespace Encelado.Core.Baskets.History; + +/// Whose a position is, as the Storico page tells it: basket, orfana-bot or esterna. +public readonly record struct PositionOwner(string Origin, string BasketId, string Basket, string ExitReason) +{ + public const string BasketOrigin = "basket"; + + public const string OrphanOrigin = "orfana-bot"; + + public const string ForeignOrigin = "esterna"; + + public static readonly PositionOwner Foreign = new(ForeignOrigin, string.Empty, string.Empty, string.Empty); + + /// A position of the bot: a basket leg or a lone leg of its own. + public bool IsBot => Origin is BasketOrigin or OrphanOrigin; + + /// The unit a win or a loss is counted on: the basket instance for its legs, the position itself for a lone leg. + public string UnitKey(long positionId) => + Origin == BasketOrigin && BasketId.Length > 0 ? BasketId : "#" + positionId.ToString(CultureInfo.InvariantCulture); +} + +/// +/// The one rule that says whose a position is, shared by the Storico page and by the +/// engine's "P&L oggi" so the two can never disagree. A position is the bot's when an +/// order line of orders.jsonl produced it (legs A, B and adds, never the closes); +/// it is a basket leg when that basket instance has a row in baskets.csv that is not +/// a lone leg, a lone leg (orfana-bot) otherwise. Before orders.jsonl existed +/// the only trace is a row of baskets.csv whose motivation carries the position id. +/// Everything else is esterna. Pure: fed with the ledger's lines, no I/O. +/// +public sealed class PositionOrigins +{ + private readonly Dictionary _byPosition = []; + private readonly Dictionary _byBasketId = new(StringComparer.Ordinal); + private readonly List _rows = []; + + public PositionOrigins() + { + } + + public PositionOrigins(IEnumerable orders, IEnumerable baskets) + { + ArgumentNullException.ThrowIfNull(orders); + ArgumentNullException.ThrowIfNull(baskets); + foreach (OrderRecord o in orders) + { + Add(o); + } + + foreach (BasketOutcomeRow b in baskets) + { + Add(b); + } + } + + /// An order line: the last line that produced a position id says whose it is. + public void Add(OrderRecord order) + { + ArgumentNullException.ThrowIfNull(order); + if (order.PositionId > 0 && order.Leg is not (OrderLeg.Close or OrderLeg.Unwind)) + { + _byPosition[order.PositionId] = order; + } + } + + /// A row of baskets.csv: the last row of a basket instance gives its exit reason. + public void Add(BasketOutcomeRow row) + { + ArgumentNullException.ThrowIfNull(row); + _rows.Add(row); + if (row.BasketId.Length > 0) + { + _byBasketId[row.BasketId] = row; + } + } + + public PositionOwner Classify(long positionId) + { + if (_byPosition.TryGetValue(positionId, out OrderRecord? o)) + { + if (o.BasketId.Length > 0 && _byBasketId.TryGetValue(o.BasketId, out BasketOutcomeRow? b)) + { + bool lone = b.ExitReason is "leg_risk_unwind" or "orphan_closed" or "bonifica_orfana" || !double.IsFinite(b.EntryZ); + return new PositionOwner(lone ? PositionOwner.OrphanOrigin : PositionOwner.BasketOrigin, o.BasketId, o.Basket, b.ExitReason); + } + + return new PositionOwner(PositionOwner.OrphanOrigin, o.BasketId, o.Basket, string.Empty); + } + + // Before orders.jsonl existed (4.0.0), and for an orphan adopted without an order of + // its own, the only trace is a lone-leg row whose motivation carries the position id. + string id = positionId.ToString(CultureInfo.InvariantCulture); + foreach (BasketOutcomeRow b in _rows) + { + if (b.Motivazione.Contains(id, StringComparison.Ordinal)) + { + return new PositionOwner(PositionOwner.OrphanOrigin, b.BasketId, b.Basket, b.ExitReason); + } + } + + return PositionOwner.Foreign; + } + + public bool IsBot(long positionId) => Classify(positionId).IsBot; +} diff --git a/Encelado/src/Encelado.Core/Baskets/History/RealizedToday.cs b/Encelado/src/Encelado.Core/Baskets/History/RealizedToday.cs new file mode 100644 index 0000000..a79fdd5 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/History/RealizedToday.cs @@ -0,0 +1,219 @@ +using Encelado.Core.Broker; + +namespace Encelado.Core.Baskets.History; + +/// What the venue's history says about a set of positions: their result, or which of them it does not show yet. +public sealed record Settlement(double NetUsd, double GrossUsd, double FeesUsd, IReadOnlyList Missing) +{ + /// Every position was found: is the P&L of record (zero is a result, not "unknown"). + public bool Complete => Missing.Count == 0; +} + +/// +/// The realised result of closed positions. The P&L of record is the venue's trade +/// history joined by position id: netProfit − fees. The only other number is a +/// provisional estimate from the close prices, used until the history confirms. +/// +public static class RealizedSettlement +{ + public static Settlement Of(IEnumerable ids, IReadOnlyList history) + { + ArgumentNullException.ThrowIfNull(ids); + ArgumentNullException.ThrowIfNull(history); + Dictionary byId = []; + foreach (ClosedTrade t in history) + { + byId[t.PositionId] = t; + } + + double gross = 0, fees = 0; + List missing = []; + foreach (long id in ids.Distinct()) + { + if (byId.TryGetValue(id, out ClosedTrade? t)) + { + gross += t.NetProfit; + fees += t.Fees; + } + else + { + missing.Add(id); + } + } + + return new Settlement(gross - fees, gross, fees, missing); + } + + /// + /// eToro's netProfit as it computes it — units × Δrate × (quote → USD) — minus the fees: + /// matches the history to the cent on NZDUSD, EURNZD and USDCAD (2026-09-29). NaN when + /// any input is missing: an estimate is never made up. + /// + public static double Estimate(bool isBuy, double units, double openRate, double closeRate, double conversionRate, double feesUsd) => + units > 0 && openRate > 0 && closeRate > 0 && double.IsFinite(conversionRate) && conversionRate > 0 && double.IsFinite(feesUsd) + ? ((isBuy ? closeRate - openRate : openRate - closeRate) * units * conversionRate) - feesUsd + : double.NaN; +} + +/// The closed units of the day: baskets, lone legs, and how many ended above zero. +public sealed record TodayClosedStats(int Baskets, int Won, int Lost, int LoneLegs) +{ + public static readonly TodayClosedStats Empty = new(0, 0, 0, 0); +} + + +/// +/// "P&L oggi": the realised net result (netProfit − fees) of the bot's positions +/// — basket legs and lone legs, classified as the Storico page does — closed in the +/// current UTC day, recomputed from the venue's history on every reading, plus the +/// provisional estimates of closes the history does not show yet. It equals the Storico's +/// "oggi" period by construction. Unknown (NaN) until the history of the day has been read +/// once; reset at UTC midnight. Foreign positions, cash movements and the unrealised +/// result never enter it. Pure: the engine feeds it from its own thread; what the other +/// threads read is one immutable picture, replaced whole after every change. +/// +public sealed class RealizedToday +{ + private sealed record View(double Settled, double ProvisionalSum, int ProvisionalCount, TodayClosedStats Closed); + + private readonly Dictionary _provisional = new(StringComparer.Ordinal); + private TodayClosedStats _settledStats = TodayClosedStats.Empty; + private double _settled = double.NaN; + private View _view = new(double.NaN, 0, 0, TodayClosedStats.Empty); + + public DateOnly Day { get; private set; } + + /// The day's result from the history alone; NaN before the first reading of the day. + public double Settled => Volatile.Read(ref _view).Settled; + + public bool IsKnown => double.IsFinite(Settled); + + /// The settled result plus the estimates still waiting for the history; NaN while the day is unknown. + public double Value + { + get + { + View v = Volatile.Read(ref _view); + return double.IsFinite(v.Settled) ? v.Settled + v.ProvisionalSum : double.NaN; + } + } + + /// True while contains estimates the history has not confirmed yet. + public bool IsProvisional => Volatile.Read(ref _view).ProvisionalCount > 0; + + public int ProvisionalCount => Volatile.Read(ref _view).ProvisionalCount; + + /// The day's closed units from the history, plus the provisional ones. + public TodayClosedStats Closed => Volatile.Read(ref _view).Closed; + + /// Moves to the day of ; everything restarts unknown. True when the day changed. + public bool Roll(DateTime nowUtc) + { + DateOnly d = DateOnly.FromDateTime(nowUtc); + if (d == Day) + { + return false; + } + + Day = d; + _settled = double.NaN; + _settledStats = TodayClosedStats.Empty; + _provisional.Clear(); + Publish(); + return true; + } + + /// A close the history does not show yet: its estimate counts until every one of its positions appears. + public void AddProvisional(string key, IReadOnlyCollection ids, double estimate, DateTime closedUtc, bool lone = false) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(ids); + if (DateOnly.FromDateTime(closedUtc) == Day) + { + _provisional[key] = ([.. ids], estimate, lone); + Publish(); + } + } + + /// + /// Recomputes the day from a fresh reading of the history. A provisional close whose + /// positions all appear is replaced by them, never added to them; while only some of + /// them appear, those are held back and the estimate still stands for the whole close. + /// + public void Apply(IReadOnlyList history, Func owner) + { + ArgumentNullException.ThrowIfNull(history); + ArgumentNullException.ThrowIfNull(owner); + DateTime from = Day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + DateTime to = from.AddDays(1); + HashSet inHistory = [.. history.Select(static t => t.PositionId)]; + foreach (string k in _provisional.Where(p => p.Value.Ids.Length > 0 && p.Value.Ids.All(inHistory.Contains)).Select(static p => p.Key).ToList()) + { + _provisional.Remove(k); + } + + HashSet heldBack = [.. _provisional.Values.SelectMany(static p => p.Ids)]; + HashSet seen = []; + Dictionary units = new(StringComparer.Ordinal); + double sum = 0; + foreach (ClosedTrade t in history) + { + if (t.ClosedUtc < from || t.ClosedUtc >= to || heldBack.Contains(t.PositionId) || !seen.Add(t.PositionId)) + { + continue; + } + + PositionOwner o = owner(t.PositionId); + if (!o.IsBot) + { + continue; + } + + sum += t.NetUsd; + string key = o.UnitKey(t.PositionId); + (double net, _) = units.GetValueOrDefault(key); + units[key] = (net + t.NetUsd, o.Origin != PositionOwner.BasketOrigin || o.BasketId.Length == 0); + } + + _settled = sum; + _settledStats = new TodayClosedStats( + units.Values.Count(static u => !u.Lone), + units.Values.Count(static u => u.Net > 0), + units.Values.Count(static u => u.Net <= 0), + units.Values.Count(static u => u.Lone)); + Publish(); + } + + /// The picture the readers see: the settled part, the estimates, the units — replaced whole. + private void Publish() + { + int baskets = _settledStats.Baskets, won = _settledStats.Won, lost = _settledStats.Lost, lone = _settledStats.LoneLegs; + double provisional = 0; + foreach ((_, double estimate, bool isLone) in _provisional.Values) + { + if (isLone) + { + lone++; + } + else + { + baskets++; + } + + if (double.IsFinite(estimate)) + { + provisional += estimate; + if (estimate > 0) + { + won++; + } + else + { + lost++; + } + } + } + + Volatile.Write(ref _view, new View(_settled, provisional, _provisional.Count, new TodayClosedStats(baskets, won, lost, lone))); + } +} diff --git a/Encelado/src/Encelado.Core/Baskets/History/SettlementQueue.cs b/Encelado/src/Encelado.Core/Baskets/History/SettlementQueue.cs new file mode 100644 index 0000000..78413d4 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/History/SettlementQueue.cs @@ -0,0 +1,233 @@ +using System.Globalization; +using System.Text.Json; +using Encelado.Core.Broker; + +namespace Encelado.Core.Baskets.History; + +/// Where the P&L of a settled close came from. +public enum SettlementSource +{ + /// The venue's trade history: netProfit − fees of every position. The P&L of record. + Venue = 0, + + /// The estimate from the close prices, written when the history did not show the positions in time. Never teaches. + Estimate, + + /// A simulator's own final number (backtest). + Simulator, +} + +/// +/// A close waiting for the venue's history: the baskets.csv row as it will be +/// written (its P&L columns hold the estimate until then), the positions to look up, +/// and what the learning needs at settlement time (the volatility context of the close, +/// captured when it happened). +/// +public sealed record PendingSettlement( + string Key, + BasketOutcomeRow Row, + long[] Ids, + double Estimate, + DateTime ClosedUtc, + bool Learn, + int VolContext, + string Title, + string Detail) +{ + /// A lone leg (unwind, orphan): no entry z. + public bool IsLoneLeg => Row.IsLoneLeg; + + public void Write(Utf8JsonWriter w) + { + ArgumentNullException.ThrowIfNull(w); + w.WriteStartObject(); + w.WriteString("key", Key); + w.WriteString("rowCsv", Row.ToCsv()); + w.WriteStartArray("ids"); + foreach (long id in Ids) + { + w.WriteNumberValue(id); + } + + w.WriteEndArray(); + if (double.IsFinite(Estimate)) + { + w.WriteNumber("estimate", Estimate); + } + else + { + w.WriteNull("estimate"); + } + + w.WriteString("closedUtc", ClosedUtc.ToString("O", CultureInfo.InvariantCulture)); + w.WriteBoolean("learn", Learn); + w.WriteNumber("volContext", VolContext); + w.WriteString("title", Title); + w.WriteString("detail", Detail); + w.WriteEndObject(); + } + + /// Reads one item of pendingSettlements; null when it is damaged. + public static PendingSettlement? Read(JsonElement e) + { + try + { + string csv = PnlCorrectionRecord.Str(e, "rowCsv"); + if (BasketOutcomeRow.Parse(csv) is not { } row) + { + return null; + } + + List ids = []; + if (e.TryGetProperty("ids", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement x in arr.EnumerateArray()) + { + if (x.ValueKind == JsonValueKind.Number && x.TryGetInt64(out long id) && id > 0) + { + ids.Add(id); + } + } + } + + DateTime closed = PnlCorrectionRecord.LedgerTime(e, "closedUtc"); + return new PendingSettlement( + PnlCorrectionRecord.Str(e, "key"), row, [.. ids], PnlCorrectionRecord.Num(e, "estimate"), + closed == default ? row.ClosedUtc : closed, + e.TryGetProperty("learn", out JsonElement l) && l.ValueKind == JsonValueKind.True, + e.TryGetProperty("volContext", out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetInt32() : 0, + PnlCorrectionRecord.Str(e, "title"), PnlCorrectionRecord.Str(e, "detail")); + } + catch (Exception ex) when (ex is InvalidOperationException or FormatException) + { + return null; + } + } +} + +/// A close settled: the row to write, the numbers, where they came from. +public sealed record SettledOutcome(PendingSettlement Pending, BasketOutcomeRow Row, double GrossUsd, double NetUsd, SettlementSource Source) +{ + /// A final number (venue or simulator): the only kind that may teach the models. + public bool IsFinal => Source != SettlementSource.Estimate; +} + +/// +/// The settlement queue (decision P2 of 5.1). A close is not a P&L until the venue's +/// history shows its positions: then the row is written with netProfit − fees. A +/// close the history does not show within is written with the +/// estimate, flagged P&L: stima, and never teaches. The queue is part of the +/// engine's state on disk (pendingSettlements), so a restart loses nothing. +/// +public sealed class SettlementQueue +{ + public static readonly TimeSpan Timeout = TimeSpan.FromMinutes(30); + + private readonly List _items = []; + + public IReadOnlyList Items => _items; + + public int Count => _items.Count; + + /// The oldest close still waiting, or null. + public DateTime? OldestClosedUtc => _items.Count == 0 ? null : _items.Min(static s => s.ClosedUtc); + + public bool Contains(long positionId) => _items.Any(s => s.Ids.Contains(positionId)); + + /// Adds a close; a second one with the same key is ignored. + public bool Add(PendingSettlement settlement) + { + ArgumentNullException.ThrowIfNull(settlement); + if (_items.Any(s => s.Key == settlement.Key)) + { + return false; + } + + _items.Add(settlement); + return true; + } + + public void Clear() => _items.Clear(); + + /// Drops the items whose row is already written (a stop between the row and the state): returns how many. + public int RemoveWritten(IReadOnlySet writtenKeys) + { + ArgumentNullException.ThrowIfNull(writtenKeys); + return _items.RemoveAll(s => writtenKeys.Contains(s.Key)); + } + + /// Settles what the history confirms, and — past the timeout — what it does not, with the estimate. + public List Resolve(IReadOnlyList history, DateTime nowUtc) + { + ArgumentNullException.ThrowIfNull(history); + List done = []; + foreach (PendingSettlement s in _items.ToList()) + { + Settlement r = RealizedSettlement.Of(s.Ids, history); + if (s.Ids.Length > 0 && r.Complete) + { + done.Add(Settle(s, r.GrossUsd, r.NetUsd, SettlementSource.Venue)); + _items.Remove(s); + } + else if (nowUtc - s.ClosedUtc >= Timeout) + { + done.Add(Settle(s, s.Row.PnlGrossUsd, s.Estimate, SettlementSource.Estimate)); + _items.Remove(s); + } + } + + return done; + } + + /// The row as written: the numbers, and in the motivation where they came from. + public static SettledOutcome Settle(PendingSettlement s, double gross, double net, SettlementSource source) + { + ArgumentNullException.ThrowIfNull(s); + string note = source switch + { + SettlementSource.Venue => BasketCorrections.VenueMarker + " (netProfit − fees)", + SettlementSource.Estimate => BasketCorrections.EstimateMarker + " dai prezzi di chiusura: lo storico eToro non mostrava le posizioni dopo 30 min", + _ => "P&L: simulatore", + }; + BasketOutcomeRow row = s.Row with { PnlGrossUsd = gross, PnlNetUsd = net, Motivazione = $"{s.Row.Motivazione} | {note}" }; + return new SettledOutcome(s, row, gross, net, source); + } + + /// When to read the history again: every 5 s in the first minute after a close, every 30 s while anything waits, every 5 min otherwise. + public TimeSpan NextCheckIn(DateTime nowUtc) => + _items.Count == 0 ? TimeSpan.FromMinutes(5) + : _items.Any(s => nowUtc - s.ClosedUtc < TimeSpan.FromMinutes(1)) ? TimeSpan.FromSeconds(5) + : TimeSpan.FromSeconds(30); + + public void Write(Utf8JsonWriter w, string propertyName) + { + ArgumentNullException.ThrowIfNull(w); + w.WriteStartArray(propertyName); + foreach (PendingSettlement s in _items) + { + s.Write(w); + } + + w.WriteEndArray(); + } + + /// Replaces the content with the items of a saved array; damaged items are skipped. Returns how many were read. + public int Load(JsonElement array) + { + _items.Clear(); + if (array.ValueKind != JsonValueKind.Array) + { + return 0; + } + + foreach (JsonElement e in array.EnumerateArray()) + { + if (PendingSettlement.Read(e) is { } s && s.Key.Length > 0) + { + Add(s); + } + } + + return _items.Count; + } +} diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/LearningFeatures.cs b/Encelado/src/Encelado.Core/Baskets/Learning/LearningFeatures.cs index 74606a5..585889f 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/LearningFeatures.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/LearningFeatures.cs @@ -22,6 +22,12 @@ public static class LearningFeatures public static int Count => Names.Length; + /// Position of volRatio in the vector. + public static readonly int VolRatioIndex = Array.IndexOf(Names, "volRatio"); + + /// Position of lastNOutcomes in the vector (26): the mean of the last ten labels, masked to 0.5 where the labels were proceeds-based. + public static readonly int LastOutcomesIndex = Array.IndexOf(Names, "lastNOutcomes"); + public static double[] From(BasketContext ctx, BasketEvaluation e, bool buyCross) { ArgumentNullException.ThrowIfNull(ctx); diff --git a/Encelado/src/Encelado.Core/Broker/Broker.cs b/Encelado/src/Encelado.Core/Broker/Broker.cs index 7085b29..e29a84f 100644 --- a/Encelado/src/Encelado.Core/Broker/Broker.cs +++ b/Encelado/src/Encelado.Core/Broker/Broker.cs @@ -128,6 +128,13 @@ public sealed record OrderOutcome( new(false, false, orderId, 0, 0, 0, DateTime.UtcNow, 0, "Unknown", error) { RequestedUnits = requestedUnits }; } +/// +/// What became of a close request. is the net realised result of +/// the closed position in account currency (its profit minus its own fees), or NaN when +/// the venue has not said it: eToro never says it in the close answer, and the trade +/// history settles it later (netProfit − fees). It is never the cash the close returned to +/// the account, and NaN is never read as zero. +/// public sealed record CloseOutcome( bool Closed, bool Rejected, @@ -139,6 +146,15 @@ public sealed record CloseOutcome( string Error) { public bool Pending => !Closed && !Rejected; + + /// The position the close is about; zero when not known. + public long PositionId { get; init; } + + /// Cash the close returned to the account (margin released plus profit), as eToro's proceeds. Diagnostics only: never a P&L. + public double Proceeds { get; init; } = double.NaN; + + /// Quote currency → account currency rate the venue applied at the close (1 for USD-quoted pairs); NaN when not given. + public double ConversionRate { get; init; } = double.NaN; } /// What the broker says the order would cost right now, in account currency. @@ -152,7 +168,11 @@ public sealed record CostEstimate( { } -/// A closed trade from the broker's history, for realised P&L and slippage. +/// +/// A closed trade from the broker's history: the P&L of record. +/// has eToro's meaning — the result of the trade before , which are +/// kept apart — and every simulator follows it. +/// public sealed record ClosedTrade( long PositionId, long InstrumentId, @@ -163,7 +183,11 @@ public sealed record ClosedTrade( DateTime OpenedUtc, DateTime ClosedUtc, double NetProfit, - double Fees); + double Fees) +{ + /// The realised result the bot records: netProfit minus fees. + public double NetUsd => NetProfit - Fees; +} /// /// Everything the engine asks of a venue. Three implementations: the real eToro API, @@ -210,6 +234,7 @@ public interface IBroker : IAsyncDisposable Task GetCostAsync(OrderRequest request, CancellationToken ct); + /// The positions closed since (the venue filters on the closing day, UTC). Throws when the history cannot be read: an unreadable history is never an empty one. Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct); } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs index 92df0f5..d71a2d9 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs @@ -112,7 +112,7 @@ public sealed partial class BasketEngine { int days = c.Argument.Trim().TrimEnd('d', 'D', 'g', 'G') is { Length: > 0 } n && int.TryParse(n, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? Math.Clamp(parsed, 1, 365) : 7; DateTime since = DateTime.UtcNow.AddDays(-days); - List rows = _ledger.ReadBaskets().Where(r => r.ClosedUtc >= since).ToList(); + List rows = _ledger.ReadBasketsCorrected().Where(r => r.ClosedUtc >= since).ToList(); return new CommandResult(true, TelegramReports.Period($"ultimi {days} giorni", rows, _equity.Drawdown(_account.Equity))) { Payload = rows }; } @@ -204,7 +204,7 @@ public sealed partial class BasketEngine { IReadOnlyList closed = await _broker.GetClosedTradesAsync(DateTime.UtcNow.AddDays(-30), ct).ConfigureAwait(false); ClosedTrade? t = closed.FirstOrDefault(x => x.PositionId == positionId); - return t is null ? fallback : t.NetProfit - t.Fees; + return t is null ? fallback : t.NetUsd; } catch (Exception ex) when (ex is not OperationCanceledException) { diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs index dee4ac4..f115faa 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Kill.cs @@ -3,6 +3,7 @@ using System.Text; using Encelado.Engine; using Encelado.Engine.Logging; using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; using Encelado.Core.Broker; using Encelado.Core.Notifications; @@ -42,6 +43,19 @@ public sealed partial class BasketEngine /// Halted-Residuo. /// private async Task KillAsync(string reason, bool includeForeign, CancellationToken ct) + { + _collect = []; + try + { + return await KillCoreAsync(reason, includeForeign, ct).ConfigureAwait(false); + } + finally + { + _collect = null; + } + } + + private async Task KillCoreAsync(string reason, bool includeForeign, CancellationToken ct) { _killSwitched = true; _haltReason = $"kill-switch ({reason})"; @@ -88,16 +102,13 @@ public sealed partial class BasketEngine } } - (List closed, List failed, double realized) = await FlattenProcedure.CloseTargetsAsync( + FlattenCloses closes = await FlattenProcedure.CloseTargetsAsync( targets.Where(static t => t.InstrumentId > 0).ToList(), (t, token) => _executor.ClosePositionAsync(new BrokerPosition(t.PositionId, t.InstrumentId, t.IsBuy, t.Units, 0, DateTime.UtcNow, 0, 0, 1, 0, 0, 0, 0), t.Symbol, t.Basket, $"kill-switch: {reason}", token), static m => Log.Warn(m), ct).ConfigureAwait(false); - _todayRealized += realized; - foreach (long id in closed) - { - _knownPositions.Remove(id); - _orphanAttempts.Remove(id); - } + List closed = closes.Closed; + List failed = closes.Failed; + (double foreignEstimate, int foreignCount, int foreignUnknown) = SettleFlattened(closes, "kill_switch", $"kill-switch: {reason}"); // 3. Flatness: every position the bot owns must be gone from the account. HashSet mustBeGone = [.. targets.Select(static t => t.PositionId)]; @@ -125,9 +136,14 @@ public sealed partial class BasketEngine })]; bool flat = residue.Count == 0; + List bot = _collect ?? []; + (double botEstimate, int botUnknown) = Sum(bot); + string foreignText = foreignCount > 0 + ? string.Create(CultureInfo.InvariantCulture, $"; esterne chiuse {foreignCount}: stima {Signed(foreignEstimate)} USD{(foreignUnknown > 0 ? $" ({foreignUnknown} senza stima)" : string.Empty)}, fuori dal P&L del bot") + : string.Empty; string summary = string.Create(CultureInfo.InvariantCulture, - $"{closed.Count + failed.Count} posizioni trattate oltre ai basket ({realized:+0.00;-0.00} USD), {cancelled.Count} ordini annullati, {filledMeanwhile.Count} eseguiti nel frattempo, {_tracker.PendingCount} ancora senza esito; {(flat ? "conto piatto per le posizioni del bot" : $"RESIDUO: {string.Join(", ", residue)}")}"); - FlattenReport report = new(cancelled, [.. filledMeanwhile.Select(static p => p.PositionId)], closed, residue, realized, flat, summary); + $"{closed.Count + failed.Count} posizioni trattate oltre ai basket; P&L del bot: {Describe(botEstimate, bot.Count, botUnknown)}{foreignText}; {cancelled.Count} ordini annullati, {filledMeanwhile.Count} eseguiti nel frattempo, {_tracker.PendingCount} ancora senza esito; {(flat ? "conto piatto per le posizioni del bot" : $"RESIDUO: {string.Join(", ", residue)}")}"); + FlattenReport report = new(cancelled, [.. filledMeanwhile.Select(static p => p.PositionId)], closed, residue, closes.RealizedKnown, flat, summary) { UnknownPnl = closes.UnknownPnl }; if (!flat) { @@ -145,10 +161,17 @@ public sealed partial class BasketEngine w.WriteNumber("chiuse", closed.Count); w.WriteNumber("residuo", residue.Count); w.WriteNumber("annullati", cancelled.Count); - w.WriteNumber("pnl", Math.Round(realized, 2)); + + // Estimates from the close prices (the venue's history settles them later), the + // bot's apart from the foreign positions'; the unknown ones counted, never summed as 0. + w.WriteNumber("pnl_bot", Math.Round(botEstimate, 2)); + w.WriteNumber("pnl_bot_sconosciuti", botUnknown); + w.WriteNumber("pnl_esterne", Math.Round(foreignEstimate, 2)); + w.WriteNumber("pnl_esterne_sconosciuti", foreignUnknown); + w.WriteString("pnl_fonte", "stima dai prezzi di chiusura; il realizzato è nelle righe realizzato e in baskets.csv"); }); SaveState(); - _notifier.Notify(NotificationKind.Alert, "Kill-switch", $"{_haltReason}\n{summary}"); + _notifier.Notify(NotificationKind.Alert, "Kill-switch", TelegramEscape($"{_haltReason}\n{summary}")); return report; } @@ -169,7 +192,6 @@ public sealed partial class BasketEngine CloseOutcome undo = await _executor.UnwindLegAsync(legA, slot.Name, slot.Pending.BasketId, reason, ct).ConfigureAwait(false); if (undo.Closed) { - _todayRealized += undo.RealizedPnl; _knownPositions.Remove(legA.PositionId); RecordLoneLegClose(slot.Name, slot.Pending.BasketId, legA, undo, code, reason); slot.Pending = null; @@ -213,28 +235,96 @@ public sealed partial class BasketEngine } } - (List closed, List failed, double realized) = await FlattenProcedure.CloseTargetsAsync(targets, - (t, token) => _executor.ClosePositionAsync(new BrokerPosition(t.PositionId, t.InstrumentId, t.IsBuy, t.Units, 0, DateTime.UtcNow, 0, 0, 1, 0, 0, 0, 0), t.Symbol, t.Basket, "chiusura del residuo dopo il kill-switch", token), - static m => Log.Warn(m), ct).ConfigureAwait(false); - _todayRealized += realized; + _collect = []; + FlattenCloses closes; + (double foreignEstimate, int foreignCount, int foreignUnknown) foreign; + List bot; + try + { + closes = await FlattenProcedure.CloseTargetsAsync(targets, + (t, token) => _executor.ClosePositionAsync(new BrokerPosition(t.PositionId, t.InstrumentId, t.IsBuy, t.Units, 0, DateTime.UtcNow, 0, 0, 1, 0, 0, 0, 0), t.Symbol, t.Basket, "chiusura del residuo dopo il kill-switch", token), + static m => Log.Warn(m), ct).ConfigureAwait(false); + foreign = SettleFlattened(closes, "kill_switch", "chiusura del residuo dopo il kill-switch"); + bot = _collect; + } + finally + { + _collect = null; + } + + List closed = closes.Closed; + List failed = closes.Failed; FlattenProcedure procedure = new(_broker, _tracker, static m => Log.Warn(m)) { FlatnessTimeout = TimeSpan.FromSeconds(30) }; List residue = await procedure.VerifyFlatAsync([.. _haltResidue.Select(static r => r.PositionId)], ct).ConfigureAwait(false); _haltResidue = [.. _haltResidue.Where(r => residue.Contains(r.PositionId))]; - foreach (long id in closed) - { - _knownPositions.Remove(id); - } if (_haltResidue.Count == 0) { _haltReason = _haltReason?.Replace(" con RESIDUO", string.Empty, StringComparison.Ordinal); } - _ledger.Note(_runId, "residuo_chiuso", string.Empty, string.Create(CultureInfo.InvariantCulture, $"{closed.Count} chiuse, {failed.Count} fallite, {residue.Count} ancora sul conto ({realized:+0.00;-0.00} USD)")); + (double botEstimate, int botUnknown) = Sum(bot); + _ledger.Note(_runId, "residuo_chiuso", string.Empty, string.Create(CultureInfo.InvariantCulture, + $"{closed.Count} chiuse, {failed.Count} fallite, {residue.Count} ancora sul conto; P&L del bot: {Describe(botEstimate, bot.Count, botUnknown)}{(foreign.foreignCount > 0 ? $"; esterne: stima {Signed(foreign.foreignEstimate)} USD" : string.Empty)}")); SaveState(); return new CommandResult(failed.Count == 0 && residue.Count == 0, string.Create(CultureInfo.InvariantCulture, $"{closed.Count} chiuse, {residue.Count} residui")); } + /// + /// After the flatten step: every position of the bot it closed waits in the settlement + /// queue as a lone leg (unless a basket or orphan close already queued it); the foreign + /// ones only get an estimate for the report — they are not the bot's P&L. + /// + private (double ForeignEstimate, int ForeignCount, int ForeignUnknown) SettleFlattened(FlattenCloses closes, string exitReason, string why) + { + double foreignEstimate = 0; + int foreignCount = 0, foreignUnknown = 0; + foreach ((FlattenTarget t, CloseOutcome c) in closes.Outcomes) + { + if (!c.Closed) + { + continue; + } + + _knownPositions.Remove(t.PositionId); + _orphanAttempts.Remove(t.PositionId); + BrokerPosition? bp = _classified.FirstOrDefault(x => x.Position.PositionId == t.PositionId)?.Position; + BasketLeg leg = new() + { + Symbol = t.Symbol, + InstrumentId = t.InstrumentId, + IsBuy = t.IsBuy, + Units = t.Units > 0 ? t.Units : bp?.Units ?? 0, + EntryPrice = bp?.OpenRate ?? 0, + PositionId = t.PositionId, + OpenedUtc = bp?.OpenedUtc ?? DateTime.UtcNow, + }; + if (t.Kind == "esterna") + { + double e = EstimateLegClose(leg.Symbol, leg.IsBuy, leg.Units, leg.EntryPrice, bp?.Fees ?? 0, c); + e = double.IsFinite(e) ? e : bp?.UnrealizedPnl ?? double.NaN; + foreignCount++; + if (double.IsFinite(e)) + { + foreignEstimate += e; + } + else + { + foreignUnknown++; + } + + continue; + } + + if (!_settlements.Queue.Contains(t.PositionId)) + { + RecordLoneLegClose(t.Basket.Length > 0 ? t.Basket : t.Symbol, string.Empty, leg, c, exitReason, why, bp?.Fees ?? double.NaN, bp?.UnrealizedPnl ?? double.NaN); + } + } + + return (foreignEstimate, foreignCount, foreignUnknown); + } + /// /// The guided reset (§9): (1) the state, (2) the STOP file, (3) the written reason, /// (4) reconciliation, warm-up and the peak of equity, (5) restart with entries diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Pending.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Pending.cs index dabcc46..2e6cde0 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Pending.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Pending.cs @@ -103,7 +103,8 @@ public sealed partial class BasketEngine await HandleLegBResolvedAsync(slot, plan, outcome, ct).ConfigureAwait(false); break; default: - if (outcome.Filled && outcome.PositionId > 0 && !_knownPositions.Contains(outcome.PositionId)) + // Only an opening order can leave a position behind; a close that resolves late names the position it closed. + if ((order.Leg is OrderLeg.A or OrderLeg.B or OrderLeg.Add) && outcome.Filled && outcome.PositionId > 0 && !_knownPositions.Contains(outcome.PositionId)) { Log.Warn($"registro ordini: {order.Describe()} è stato eseguito ma nessun basket lo aspettava: la posizione {outcome.PositionId} è una gamba orfana del bot e verrà chiusa alla riconciliazione"); _lastReconcileUtc = DateTime.MinValue; @@ -162,17 +163,23 @@ public sealed partial class BasketEngine Log.Warn($"[{slot.Name}] gamba A eseguita in ritardo ma {why}: la richiudo subito (leg_risk_unwind)"); BasketLeg legA = LegFromOutcome(slot, plan, outcome); CloseOutcome undo = await _executor.UnwindLegAsync(legA, slot.Name, plan.BasketId, "leg_risk_unwind: " + why, ct).ConfigureAwait(false); - _ledger.Note(_runId, "leg_risk_unwind", plan.BasketId, $"gamba A eseguita in ritardo, {why}; {(undo.Closed ? "richiusa" : "NON richiusa: " + undo.Error)}", w => + double estimate = undo.Closed ? RecordLoneLegClose(slot.Name, plan.BasketId, legA, undo, "leg_risk_unwind", why) : double.NaN; + _ledger.Note(_runId, "leg_risk_unwind", plan.BasketId, $"gamba A eseguita in ritardo, {why}; {(undo.Closed ? $"richiusa (stima {Signed(estimate)} USD, il realizzato arriva dallo storico eToro)" : "NON richiusa: " + undo.Error)}", w => { w.WriteString("basket", slot.Name); w.WriteNumber("position_id", legA.PositionId); - w.WriteNumber("pnl", undo.RealizedPnl); + if (double.IsFinite(estimate)) + { + w.WriteNumber("stima", Math.Round(estimate, 2)); + } + else + { + w.WriteNull("stima"); + } }); if (undo.Closed) { - _todayRealized += undo.RealizedPnl; _knownPositions.Remove(legA.PositionId); - RecordLoneLegClose(slot.Name, plan.BasketId, legA, undo, "leg_risk_unwind", why); slot.Pending = null; slot.PositionBasketId = string.Empty; Transition(slot, BasketState.Idle); @@ -240,13 +247,27 @@ public sealed partial class BasketEngine }; } - /// A lone leg closed (unwind, orphan): one row in baskets.csv so the realised result is in the ledger. - private void RecordLoneLegClose(string basket, string basketId, BasketLeg leg, CloseOutcome close, string exitReason, string why) + /// + /// A lone leg closed (unwind, orphan, residue): one row for baskets.csv, which + /// waits in the settlement queue for the venue's history. Returns the estimate from the + /// close price (units × Δrate × quote→USD − fees), or + /// when the close carried no price. + /// + private double RecordLoneLegClose(string basket, string basketId, BasketLeg leg, CloseOutcome close, string exitReason, string why, double feesUsd = double.NaN, double fallbackEstimate = double.NaN) { - double pnl = close.RealizedPnl; - BasketOutcomeRow row = new(basketId, _runId, basket, ModeLabel, PresetLabel, leg.OpenedUtc, close.TimeUtc == default ? DateTime.UtcNow : close.TimeUtc, - leg.IsBuy, double.NaN, double.NaN, pnl, pnl, double.NaN, double.NaN, double.NaN, double.NaN, 0, 0, exitReason, _account.Equity, double.NaN, - string.Create(CultureInfo.InvariantCulture, $"gamba singola {(leg.IsBuy ? "long" : "short")} {leg.Units:0.##} {leg.Symbol} @ {leg.EntryPrice} chiusa @ {close.CloseRate}: {why}")); - _ledger.Basket(row); + DateTime closedUtc = close.TimeUtc == default ? DateTime.UtcNow : close.TimeUtc; + double estimate = EstimateLegClose(leg.Symbol, leg.IsBuy, leg.TotalUnits, leg.EntryPrice, double.IsFinite(feesUsd) ? feesUsd : leg.EntryFeesUsd, close); + if (!double.IsFinite(estimate)) + { + estimate = fallbackEstimate; + } + + long id = close.PositionId > 0 ? close.PositionId : leg.PositionId; + long[] ids = id > 0 ? [id] : []; + BasketOutcomeRow row = new(basketId, _runId, basket, ModeLabel, PresetLabel, leg.OpenedUtc, closedUtc, + leg.IsBuy, double.NaN, double.NaN, estimate, estimate, double.NaN, double.NaN, double.NaN, double.NaN, 0, 0, exitReason, _account.Equity, double.NaN, + string.Create(CultureInfo.InvariantCulture, $"gamba singola {(leg.IsBuy ? "long" : "short")} {leg.TotalUnits:0.##} {leg.Symbol} @ {leg.EntryPrice} chiusa @ {close.CloseRate}: {why} | {PositionMap.Mark(ids)}")); + EnqueueSettlement(new PendingSettlement(PnlCorrectionRecord.KeyOf(row), row, ids, estimate, closedUtc, false, 0, string.Empty, string.Empty)); + return estimate; } } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs new file mode 100644 index 0000000..64b3d63 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs @@ -0,0 +1,201 @@ +using System.Globalization; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; +using Encelado.Core.Baskets.Learning; +using Encelado.Core.Broker; +using Encelado.Engine.Logging; + +namespace Encelado.Engine.Baskets; + +/// +/// The realised result (decisions P1-P5 of 5.1). The P&L of record of every closed +/// position is the venue's trade history, joined by position id: netProfit − fees. +/// One reading of the history (Default quota, about one call every five minutes, every +/// few seconds right after a close) settles the closes waiting in the queue, recomputes +/// "P&L oggi" and explains the balance to the cash-movement check. The close proceeds +/// are never a P&L; an estimate from the close prices stands in, flagged, until the +/// history confirms. +/// +public sealed partial class BasketEngine +{ + private DateTime _nextHistoryUtc; + private DateTime _lastHistoryWarnUtc; + private (DateTime At, DateTime From, IReadOnlyList Trades)? _historyCache; + + /// While a kill-switch runs: the closes it enqueued, for its summary. + private List? _collect; + + /// + /// The venue's history from yesterday (or from the oldest close still waiting): one + /// reading shared by the settlement, today's result and the cash-movement check within + /// the same few seconds. Throws when it cannot be read. + /// + private async Task> ReadHistoryAsync(CancellationToken ct) + { + DateTime now = DateTime.UtcNow; + DateTime from = now.Date.AddDays(-1); + if (_settlements.Queue.OldestClosedUtc is { } oldest && oldest.Date < from) + { + from = oldest.Date > now.Date.AddDays(-364) ? oldest.Date : now.Date.AddDays(-364); + } + + if (_historyCache is { } cached && now - cached.At < TimeSpan.FromSeconds(3) && cached.From <= from) + { + return cached.Trades; + } + + IReadOnlyList trades = await _broker.GetClosedTradesAsync(from, ct).ConfigureAwait(false); + _historyCache = (now, from, trades); + return trades; + } + + /// + /// Settles the closes the history shows (or that waited past 30 minutes), then + /// recomputes today's realised result. Runs when due (see ); + /// a history that cannot be read leaves today's number as it was and is asked again in 30 s. + /// + private async Task RefreshRealizedAsync(DateTime now, CancellationToken ct, bool force = false) + { + if (!force && now < _nextHistoryUtc) + { + return; + } + + IReadOnlyList history; + try + { + history = await ReadHistoryAsync(ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _nextHistoryUtc = now.AddSeconds(30); + if (now - _lastHistoryWarnUtc > TimeSpan.FromMinutes(10)) + { + _lastHistoryWarnUtc = now; + Log.Warn($"storico delle chiusure non letto: {ex.Message}; P&L di oggi invariato{(_today.IsKnown ? string.Empty : " (sconosciuto)")}, {_settlements.Queue.Count} chiusure in attesa; riprovo fra 30 s"); + } + + return; + } + + // First the settlements (a row written now also tells whose a lone leg was), then today. + _nextHistoryUtc = now.AddSeconds(30); + try + { + List settled = _settlements.Apply(history, now); + _today.Apply(history, _origins.Classify); + _nextHistoryUtc = now + _settlements.Queue.NextCheckIn(now); + if (settled.Count > 0) + { + SaveState(); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Error("regolamento delle chiusure o P&L di oggi non aggiornati", ex); + } + } + + /// + /// At startup, on the Demo or Live account: the rows written by 4.0.0–5.0.0 are checked + /// against the venue's history and corrected with new lines (). + /// When rows of those versions were wrong, once: the lastNOutcomes feature is + /// declared unreliable up to now, the notes' proceeds range is recorded, and the models + /// that learnt from the wrong labels are retired and rebuilt. A failure is retried at + /// the next start. + /// + private async Task BackfillRealizedAsync(CancellationToken ct) + { + if (_mode == ExecutionMode.Paper) + { + return; + } + + try + { + RealizedBackfill backfill = new(_ledger, (from, token) => _broker.GetClosedTradesAsync(from, token), _runId, ModeLabel, + symbol => _series.TryGetValue(symbol, out SymbolSeries? s) ? s.Instrument.Id : 0, static m => Log.Info(m)); + BackfillReport report = await backfill.RunAsync(DateTime.UtcNow, ct).ConfigureAwait(false); + if (report.Corrected + report.Unverifiable > 0) + { + Log.Warn($"verifica del realizzato: {report.Describe()} (righe di baskets.csv corrette con righe «correzione» in decisions.jsonl; il file non viene toccato)"); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warn($"verifica del realizzato non eseguita ({ex.Message}): riprovo al prossimo avvio"); + return; + } + + try + { + if (_learning.LabelsFixed || !RealizedBackfill.LegacyRowsWereCorrected(_ledger)) + { + return; + } + + // The mark goes first: the replay below must already see the feature masked. + DateTime now = DateTime.UtcNow; + string feature = LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]; + if (_ledger.ReadFeatureMaskUntil(feature) == DateTime.MinValue) + { + _ledger.FeatureUnreliable(_runId, feature, LearningFeatures.LastOutcomesIndex, now, + "lastNOutcomes calcolata da etichette sbagliate (P&L = proceeds della chiusura) in ogni riga di valutazione fino a questo momento: nel dataset vale 0,5, il valore neutro"); + } + + if (!_ledger.HasCorrectionOfKind(LedgerMarkers.ProceedsNotes)) + { + _ledger.ProceedsNotesRange(_runId, new DateTime(2026, 9, 16, 0, 0, 0, DateTimeKind.Utc), now, + "fino a qui i campi pnl delle note leg_risk_unwind, orfana_chiusa e kill_switch_concluso e i testi «netto … USD» delle righe uscita e residuo_chiuso sono i proceeds della chiusura (margine restituito + profitto), non il P&L: il realizzato vero è nelle correzioni pnl_realizzato"); + } + + _learning.RetireAndReplay(now, "etichette dei basket 4.0.0-5.0.0 calcolate sui proceeds della chiusura: modelli ritirati, logistica rifatta sulle etichette corrette dallo storico eToro, bandit dal prior"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warn($"ritiro dei modelli addestrati sulle etichette sbagliate non riuscito ({ex.Message}): riprovo al prossimo avvio"); + } + } + + /// + /// The estimate of a lone leg's realised result from its close: units × Δrate × + /// quote→USD − fees, with the venue's conversion rate when the close carried it and the + /// polled quotes otherwise; the current quote stands in for a close seen only on the + /// position list. NaN when something is missing. + /// + private double EstimateLegClose(string symbol, bool isBuy, double units, double openRate, double feesUsd, CloseOutcome close) + { + double rate = close.CloseRate > 0 ? close.CloseRate : ExitQuote(symbol, isBuy); + double conversion = double.IsFinite(close.ConversionRate) && close.ConversionRate > 0 + ? close.ConversionRate + : symbol.Length >= 6 ? PipMath.QuoteToUsd(PipMath.QuoteCurrency(symbol), MidOf) ?? double.NaN : double.NaN; + return RealizedSettlement.Estimate(isBuy, close.Units > 0 ? close.Units : units, openRate, rate, conversion, double.IsFinite(feesUsd) ? feesUsd : 0); + } + + /// The price a close would get now: the bid for a long, the ask for a short. + private double ExitQuote(string symbol, bool isBuy) => + _series.TryGetValue(symbol, out SymbolSeries? s) && s.HasQuote ? (isBuy ? s.Quote.Bid : s.Quote.Ask) : double.NaN; + + /// The bot's part of a kill-switch: the estimate of the closes it enqueued, and how many have none. + private static (double Estimate, int Unknown) Sum(IEnumerable settlements) + { + double sum = 0; + int unknown = 0; + foreach (PendingSettlement s in settlements) + { + if (double.IsFinite(s.Estimate)) + { + sum += s.Estimate; + } + else + { + unknown++; + } + } + + return (sum, unknown); + } + + private static string Describe(double estimate, int count, int unknown) => string.Create(CultureInfo.InvariantCulture, + $"stima {Signed(estimate)} USD su {count} chiusure{(unknown > 0 ? $" ({unknown} senza stima)" : string.Empty)}, il realizzato arriva dallo storico eToro"); +} diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs index a82c608..76d4f9b 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs @@ -31,8 +31,14 @@ public sealed partial class BasketEngine private int _orphanCount; private int _foreignCount; - /// Reads the account; feeds the equity tracker with the realised result of the positions closed since the last reading. - private async Task RefreshAccountAsync(double closedNetSinceLast, CancellationToken ct) + /// + /// Reads the account; feeds the equity tracker with the realised result of the positions + /// closed since the last reading. NaN means "not explained yet": no verdict on cash + /// movements (the tracker keeps its reference), or — with at + /// startup — the balance becomes the new reference without a verdict. The first reading + /// of a UTC day fixes the day's starting net equity. + /// + private async Task RefreshAccountAsync(double closedNetSinceLast, CancellationToken ct, bool rebase = false) { try { @@ -44,7 +50,22 @@ public sealed partial class BasketEngine return; } - CashMovement? movement = _equity.Observe(DateTime.UtcNow, _account.Balance, _account.Equity, closedNetSinceLast); + CashMovement? movement = null; + if (rebase && !double.IsFinite(closedNetSinceLast)) + { + _equity.Rebase(DateTime.UtcNow, _account.Balance, _account.Equity); + } + else + { + movement = _equity.Observe(DateTime.UtcNow, _account.Balance, _account.Equity, closedNetSinceLast); + } + + if (!(_dayStartEquity > 0)) + { + _dayStartEquity = _equity.NetEquity(_account.Equity); + Log.Info(string.Create(CultureInfo.InvariantCulture, $"equity netta di inizio giornata {_dayStartEquity:F2} (al netto dei movimenti di cassa): base della perdita giornaliera")); + } + if (movement is not null) { Log.Warn($"MOVIMENTO DI CASSA: {movement.Motivazione}"); @@ -72,35 +93,68 @@ public sealed partial class BasketEngine try { IReadOnlyList closed = await _broker.GetClosedTradesAsync(_equity.LastObservedUtc.AddDays(-1), ct).ConfigureAwait(false); - closedNet = closed.Where(c => c.ClosedUtc > _equity.LastObservedUtc).Sum(static c => c.NetProfit - c.Fees); + closedNet = closed.Where(c => c.ClosedUtc > _equity.LastObservedUtc).Sum(static c => c.NetUsd); } catch (Exception ex) when (ex is not OperationCanceledException) { - Log.Warn($"storico delle chiusure non letto all'avvio: {ex.Message}; un eventuale movimento di cassa verrà stimato senza le chiusure"); + // Without the closes made while the bot was off, the balance cannot be judged: + // it becomes the new reference, and nothing is booked as a deposit or a withdrawal. + Log.Warn($"storico delle chiusure non letto all'avvio: {ex.Message}; il saldo attuale diventa il riferimento, senza giudicare i movimenti di cassa"); + closedNet = double.NaN; } } - await RefreshAccountAsync(closedNet, ct).ConfigureAwait(false); + await RefreshAccountAsync(closedNet, ct, rebase: true).ConfigureAwait(false); } - /// The realised net result of positions that vanished since the last reconciliation, from the venue's history. + /// Positions that vanished from the account and the venue's history does not show yet. + private readonly HashSet _vanishedUnsettled = []; + private DateTime _vanishedSinceUtc; + + /// + /// The realised net result of the positions that vanished since the last verdict, from + /// the venue's history. NaN — no verdict on cash movements — while the history does not + /// show all of them yet (it lags a close by seconds to minutes) or cannot be read; the + /// balance is then judged at a later reconciliation, with every close explained. After + /// an hour the positions still missing are given up and the verdict is taken without them. + /// private async Task ClosedNetAsync(IReadOnlyCollection vanished, CancellationToken ct) { - if (vanished.Count == 0) + if (vanished.Count == 0 && _vanishedUnsettled.Count == 0) { return 0; } + if (_vanishedUnsettled.Count == 0) + { + _vanishedSinceUtc = DateTime.UtcNow; + } + + _vanishedUnsettled.UnionWith(vanished); + IReadOnlyList closed; try { - IReadOnlyList closed = await _broker.GetClosedTradesAsync(DateTime.UtcNow.AddDays(-3), ct).ConfigureAwait(false); - return closed.Where(c => vanished.Contains(c.PositionId)).Sum(static c => c.NetProfit - c.Fees); + closed = await ReadHistoryAsync(ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { - Log.Warn($"storico delle chiusure non letto: {ex.Message}"); - return 0; + Log.Warn($"storico delle chiusure non letto: {ex.Message}; nessun giudizio sui movimenti di cassa finché non risponde"); + return double.NaN; } + + Settlement s = RealizedSettlement.Of(_vanishedUnsettled, closed); + if (!s.Complete) + { + if (DateTime.UtcNow - _vanishedSinceUtc < TimeSpan.FromHours(1)) + { + return double.NaN; + } + + Log.Warn($"lo storico eToro non mostra da oltre un'ora le posizioni {string.Join(", ", s.Missing)} sparite dal conto: il saldo viene giudicato senza il loro risultato"); + } + + _vanishedUnsettled.Clear(); + return s.NetUsd; } /// @@ -160,7 +214,7 @@ public sealed partial class BasketEngine if (!aAlive && !bAlive) { Log.Warn($"[{slot.Name}] entrambe le gambe sono sparite dal conto (chiuse dal broker o a mano): registro la chiusura"); - await RecordExternalCloseAsync(slot, p, "chiuso dal broker", ct).ConfigureAwait(false); + RecordExternalClose(slot, p, "chiuso dal broker"); continue; } @@ -397,18 +451,8 @@ public sealed partial class BasketEngine return false; } - _todayRealized += close.RealizedPnl; _orphanAttempts.Remove(bp.PositionId); _knownPositions.Remove(bp.PositionId); - Log.Warn(string.Create(CultureInfo.InvariantCulture, $"gamba orfana {bp.PositionId} su {symbol} chiusa @ {close.CloseRate}: {close.RealizedPnl:+0.00;-0.00} USD")); - _ledger.Note(_runId, "orfana_chiusa", string.Empty, $"{why}: {close.RealizedPnl.ToString("+0.00;-0.00", CultureInfo.InvariantCulture)} USD", w => - { - w.WriteString("basket", c.Basket); - w.WriteNumber("position_id", bp.PositionId); - w.WriteString("strumento", symbol); - w.WriteNumber("pnl", Math.Round(close.RealizedPnl, 2)); - w.WriteString("exit_reason", exitReason); - }); BasketLeg leg = new() { Symbol = symbol, @@ -419,30 +463,43 @@ public sealed partial class BasketEngine PositionId = bp.PositionId, OpenedUtc = bp.OpenedUtc, }; - RecordLoneLegClose(c.Basket.Length > 0 ? c.Basket : symbol, string.Empty, leg, close, exitReason, why); + double estimate = RecordLoneLegClose(c.Basket.Length > 0 ? c.Basket : symbol, string.Empty, leg, close, exitReason, why, bp.Fees, bp.UnrealizedPnl); + Log.Warn(string.Create(CultureInfo.InvariantCulture, $"gamba orfana {bp.PositionId} su {symbol} chiusa @ {close.CloseRate}: stima {Signed(estimate)} USD, il realizzato arriva dallo storico eToro")); + _ledger.Note(_runId, "orfana_chiusa", string.Empty, $"{why}: stima {Signed(estimate)} USD, in attesa dello storico eToro", w => + { + w.WriteString("basket", c.Basket); + w.WriteNumber("position_id", bp.PositionId); + w.WriteString("strumento", symbol); + if (double.IsFinite(estimate)) + { + w.WriteNumber("stima", Math.Round(estimate, 2)); + } + else + { + w.WriteNull("stima"); + } + + w.WriteString("exit_reason", exitReason); + }); _lastReconcileUtc = DateTime.MinValue; // re-read the account soon: the balance moved return true; } - private async Task RecordExternalCloseAsync(BasketSlot slot, BasketPosition p, string reason, CancellationToken ct) + /// + /// Both legs of a basket vanished from the account (native stops, a manual close, the + /// broker): the basket is closed in the engine and its row waits for the venue's history + /// like any other close, with the last open P&L seen as the estimate. + /// + private void RecordExternalClose(BasketSlot slot, BasketPosition p, string reason) { - double pnl = 0; - try - { - IReadOnlyList closed = await _broker.GetClosedTradesAsync(p.OpenedUtc.AddDays(-1), ct).ConfigureAwait(false); - HashSet ids = [.. p.A.AllPositionIds.Concat(p.B.AllPositionIds)]; - pnl = closed.Where(c => ids.Contains(c.PositionId)).Sum(static c => c.NetProfit - c.Fees); - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - Log.Warn($"[{slot.Name}] storico chiusure non letto: {ex.Message}"); - } - - BasketOutcomeRow row = new(slot.PositionBasketId, _runId, slot.Name, ModeLabel, PresetLabel, p.OpenedUtc, DateTime.UtcNow, p.BuyCross, p.EntryZ, slot.LastEvaluation.Z, - pnl, pnl, double.NaN, p.EntryCostPips, double.NaN, double.NaN, p.Adds, p.BarsHeld, "closed_by_broker", p.EquityAtEntry, slot.PMl, reason); - _ledger.Basket(row); - _todayRealized += pnl; - foreach (long id in p.A.AllPositionIds.Concat(p.B.AllPositionIds)) + long[] ids = [.. p.A.AllPositionIds.Concat(p.B.AllPositionIds).Where(static id => id > 0).Distinct()]; + double estimate = slot.LastEvaluation.PnlOpenUsd; + estimate = double.IsFinite(estimate) ? estimate : double.NaN; + DateTime closedUtc = DateTime.UtcNow; + BasketOutcomeRow row = new(slot.PositionBasketId, _runId, slot.Name, ModeLabel, PresetLabel, p.OpenedUtc, closedUtc, p.BuyCross, p.EntryZ, slot.LastEvaluation.Z, + estimate, estimate, double.NaN, p.EntryCostPips, double.NaN, double.NaN, p.Adds, p.BarsHeld, "closed_by_broker", p.EquityAtEntry, slot.PMl, $"{reason} | {PositionMap.Mark(ids)}"); + EnqueueSettlement(new PendingSettlement(PnlCorrectionRecord.KeyOf(row), row, ids, estimate, closedUtc, false, 0, $"Basket chiuso dal broker: {slot.Name}", reason)); + foreach (long id in ids) { _knownPositions.Remove(id); } @@ -450,7 +507,7 @@ public sealed partial class BasketEngine slot.Position = null; slot.PositionBasketId = string.Empty; slot.State = BasketState.Idle; - slot.Intent = $"chiuso dal broker: {pnl:+0.00;-0.00} USD"; + slot.Intent = $"chiuso dal broker: stima {Signed(estimate)} USD, in attesa dello storico eToro"; SaveState(); } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs index 24d0066..bf24f4e 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs @@ -69,8 +69,15 @@ public sealed partial class BasketEngine DrawdownPct = dd, EquityStopPct = _strategy.EquityStopPct / 100.0, DailyLossPct = _strategy.DailyLossPct / 100.0, - TodayPnl = _todayRealized, - TodayPnlPct = _dayStartEquity > 0 ? _todayRealized / _dayStartEquity : 0, + TodayPnl = _today.Value, + TodayPnlPct = _dayStartEquity > 0 && _today.IsKnown ? _today.Value / _dayStartEquity : double.NaN, + TodayPnlProvisional = _today.IsProvisional, + TodayEquityChange = TodayEquityChange, + DayStartEquity = _dayStartEquity > 0 ? _dayStartEquity : double.NaN, + TodayClosed = _today.Closed, + DailyLossUsedPct = DailyLoss.UsedFraction(_dayStartEquity, NetEquityNow, _strategy.DailyLossPct), + DailyLossHit = DailyLoss.IsHit(_dayStartEquity, NetEquityNow, _strategy.DailyLossPct), + PendingSettlements = _settlements.Queue.Count, OpenPnl = openPnl, OpenPnlPct = equity > 0 ? openPnl / equity : 0, OpenBaskets = _slots.Count(static s => s.Position is not null), diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index 532a481..28ee76c 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -3,6 +3,7 @@ using System.Text.Json; using Encelado.Engine; using Encelado.Engine.Logging; using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; namespace Encelado.Engine.Baskets; @@ -13,8 +14,20 @@ namespace Encelado.Engine.Baskets; /// public sealed partial class BasketEngine { + /// + /// False until the saved state has been read: a start that fails earlier (no keys, the + /// venue unreachable) must not overwrite it with an empty one — the equity peak, the + /// open baskets and the closes waiting for the history would be lost. + /// + private bool _stateLoaded; + private void SaveState() { + if (!_stateLoaded) + { + return; + } + try { using MemoryStream ms = new(); @@ -30,8 +43,11 @@ public sealed partial class BasketEngine w.WriteNumber("lastBalance", double.IsFinite(_equity.LastBalance) ? _equity.LastBalance : 0); w.WriteString("lastBalanceUtc", _equity.LastObservedUtc == default ? string.Empty : _equity.LastObservedUtc.ToString("O", CultureInfo.InvariantCulture)); w.WriteString("sessionDate", _sessionDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); - w.WriteNumber("dayStartEquity", _dayStartEquity); - w.WriteNumber("todayRealized", _todayRealized); + w.WriteNumber("dayStartEquity", _dayStartEquity > 0 ? _dayStartEquity : 0); + + // Today's realised result is not saved: it is recomputed from the venue's + // history. What is saved is every close still waiting for it. + _settlements.Queue.Write(w, "pendingSettlements"); w.WriteBoolean("killSwitched", _killSwitched); w.WriteBoolean("equityStopped", _equityStopped); w.WriteString("haltReason", _haltReason ?? string.Empty); @@ -112,6 +128,7 @@ public sealed partial class BasketEngine private void LoadState() { + _stateLoaded = true; if (!File.Exists(_statePath)) { return; @@ -137,10 +154,19 @@ public sealed partial class BasketEngine _killSwitched = root.TryGetProperty("killSwitched", out JsonElement ks) && ks.GetBoolean(); _equityStopped = root.TryGetProperty("equityStopped", out JsonElement es) && es.GetBoolean(); _haltReason = root.TryGetProperty("haltReason", out JsonElement hr) && hr.GetString() is { Length: > 0 } h ? h : null; - if (root.TryGetProperty("sessionDate", out JsonElement sd) && DateOnly.TryParse(sd.GetString(), CultureInfo.InvariantCulture, out DateOnly day) && day == DateOnly.FromDateTime(DateTime.UtcNow)) + if (root.TryGetProperty("sessionDate", out JsonElement sd) && DateOnly.TryParse(sd.GetString(), CultureInfo.InvariantCulture, out DateOnly day) && day == DateOnly.FromDateTime(DateTime.UtcNow) && + root.TryGetProperty("dayStartEquity", out JsonElement dse) && dse.ValueKind == JsonValueKind.Number && dse.GetDouble() > 0) { - _dayStartEquity = root.TryGetProperty("dayStartEquity", out JsonElement dse) ? dse.GetDouble() : 0; - _todayRealized = root.TryGetProperty("todayRealized", out JsonElement tr) ? tr.GetDouble() : 0; + _dayStartEquity = dse.GetDouble(); + } + + // "todayRealized" of 5.0 held the close proceeds: never read again. + if (root.TryGetProperty("pendingSettlements", out JsonElement settlements) && _settlements.Queue.Load(settlements) > 0) + { + // A stop between a settled row and the state that forgets it: the row is not written twice. + HashSet written = [.. _ledger.ReadBaskets().Select(PnlCorrectionRecord.KeyOf)]; + int already = _settlements.Queue.RemoveWritten(written); + Log.Info($"{_settlements.Queue.Count} chiusure riprese dallo stato salvato: il loro P&L arriva dallo storico eToro{(already > 0 ? $" ({already} già scritte in baskets.csv, scartate)" : string.Empty)}"); } if (_equityStopped) diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index eb9ccfe..704ab75 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -89,10 +89,20 @@ public sealed partial class BasketEngine : IEngine private readonly HashSet _foreignPositions = []; private readonly HashSet _knownPositions = []; + /// Whose every position is, by the Storico's rule: fed with orders.jsonl and baskets.csv at startup, then line by line. + private readonly PositionOrigins _origins; + + /// Every close waits here for the venue's history (decision P2); persisted in the state as pendingSettlements. + private readonly Settlements _settlements; + + /// "P&L oggi": the bot's positions closed in the UTC day, from the venue's history plus the provisional estimates. + private readonly RealizedToday _today = new(); + private AccountSnapshot _account = new(DateTime.MinValue, "USD", 0, 0, 0, 0, 0); private DateOnly _sessionDate; - private double _dayStartEquity; - private double _todayRealized; + + /// Net equity (cash movements excluded) at the first account reading of the UTC day; NaN until then. + private double _dayStartEquity = double.NaN; private bool _killSwitched; private bool _equityStopped; private string? _haltReason; @@ -253,11 +263,18 @@ public sealed partial class BasketEngine : IEngine } _ledger = new Ledger(Path.Combine(_dataDir, "ledger")); + _origins = new PositionOrigins(_ledger.ReadOrders(), _ledger.ReadBaskets()); _tracker = new OrderTracker(Path.Combine(_dataDir, "state", _mode == ExecutionMode.Paper ? "pending_orders_paper.json" : "pending_orders.json")); - _tracker.Changed += (order, evento) => _ledger.Order(OrderRecord.From(order, _runId, evento)); + _tracker.Changed += (order, evento) => + { + OrderRecord line = OrderRecord.From(order, _runId, evento); + _ledger.Order(line); + _origins.Add(line); + }; _decider = new BasketDecider(_strategy); _executor = new BasketExecutor(_broker, _strategy, MidOf, static m => Log.Warn(m), _tracker, _mode.ToString()); _learning = new LearningState(_dataDir, config.Run.KnowledgePath, _ledger, _strategy); + _settlements = new Settlements(_ledger, _runId, _notifier, Teach, _origins.Add); _context = context ?? new FeedContextProvider(_dataDir, config.Etoro.UserAgent); } @@ -306,11 +323,22 @@ public sealed partial class BasketEngine : IEngine await ReconcileAsync(ct).ConfigureAwait(false); _sessionDate = DateOnly.FromDateTime(DateTime.UtcNow); - if (_dayStartEquity <= 0) + if (!(_dayStartEquity > 0) && _account.TimeUtc != DateTime.MinValue) { _dayStartEquity = _equity.NetEquity(_account.Equity); } + // The realised results of 4.0.0–5.0.0 were the close proceeds: checked once against + // the venue's history (Demo and Live only), then today's P&L from the same history. + await BackfillRealizedAsync(ct).ConfigureAwait(false); + _today.Roll(DateTime.UtcNow); + foreach (PendingSettlement s in _settlements.Queue.Items) + { + _today.AddProvisional(s.Key, s.Ids, s.Estimate, s.ClosedUtc, s.IsLoneLeg); + } + + await RefreshRealizedAsync(DateTime.UtcNow, ct, force: true).ConfigureAwait(false); + SaveState(); WriteHeartbeat(DateTime.UtcNow, "avvio", force: true); @@ -574,6 +602,10 @@ public sealed partial class BasketEngine : IEngine SaveState(); } + // One reading of the venue's history settles the closes, recomputes today's + // realised result and (shared with the reconciliation) explains the balance. + await RefreshRealizedAsync(now, ct).ConfigureAwait(false); + // ADR-0006: the weekly cycle runs inside the bot only when the operator turned learning on. if (_strategy.Learning.Enabled && _strategy.Learning.WeeklyCycle && _learning.CycleDue(now) && now.DayOfWeek == DayOfWeek.Sunday && now.Hour >= 10) { @@ -647,7 +679,7 @@ public sealed partial class BasketEngine : IEngine _lastDailySummary = today; if (now.Hour == hour || _lastDailySummary == default) { - List rows = _ledger.ReadBaskets().Where(r => DateOnly.FromDateTime(r.ClosedUtc) == today).ToList(); + List rows = _ledger.ReadBasketsCorrected().Where(r => DateOnly.FromDateTime(r.ClosedUtc) == today).ToList(); _notifier.Notify(NotificationKind.Daily, string.Create(CultureInfo.InvariantCulture, $"Riepilogo del {today:dd/MM}"), TelegramReports.Period("oggi", rows, _equity.Drawdown(_account.Equity))); } } @@ -776,7 +808,8 @@ public sealed partial class BasketEngine : IEngine if (!first) { - await RefreshAccountAsync(0, ct).ConfigureAwait(false); + // Read only: a close earlier in this tick must not be judged a cash movement here; the reconciliation judges. + await RefreshAccountAsync(double.NaN, ct).ConfigureAwait(false); } first = false; @@ -983,13 +1016,17 @@ public sealed partial class BasketEngine : IEngine double usdB = PipMath.QuoteToUsd(PipMath.QuoteCurrency(slot.B.Symbol), MidOf) ?? double.NaN; bool sameCrossOpen = _slots.Any(o => o != slot && o.Cross.Symbol == slot.Cross.Symbol && (o.Position is not null || o.State == BasketState.Entering || o.State.IsPending())); - double dailyPnl = _todayRealized + _account.UnrealizedPnl; - bool dailyLossHit = _dayStartEquity > 0 && dailyPnl <= -_dayStartEquity * _strategy.DailyLossPct / 100.0; + + // Daily loss (RISK_RULES, the same formula as the backtest): the net equity lost since + // 00:00 UTC — realised and unrealised, cash movements excluded — against the day's start. + double netEquity = NetEquityNow; + double dailyPnl = _dayStartEquity > 0 && double.IsFinite(netEquity) ? netEquity - _dayStartEquity : double.NaN; + bool dailyLossHit = DailyLoss.IsHit(_dayStartEquity, netEquity, _strategy.DailyLossPct); if (dailyLossHit && _dailyLossNotified != _sessionDate) { _dailyLossNotified = _sessionDate; - Log.Warn(string.Create(CultureInfo.InvariantCulture, $"perdita giornaliera raggiunta: {dailyPnl:+0.00;-0.00} USD su {_dayStartEquity:F2} di equity di partenza ({_strategy.DailyLossPct:0.#} %): niente nuove entrate fino a domani")); - _notifier.Notify(NotificationKind.Alert, "Perdita giornaliera raggiunta", string.Create(CultureInfo.InvariantCulture, $"{dailyPnl:+0.00;-0.00} USD oggi su {_dayStartEquity:N2} di equity ({_strategy.DailyLossPct:0.#} %): niente nuove entrate fino alla mezzanotte UTC")); + Log.Warn(string.Create(CultureInfo.InvariantCulture, $"perdita giornaliera raggiunta: equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:F2} di partenza ({_strategy.DailyLossPct:0.#} %): niente nuove entrate finché resta oltre la soglia, al più fino alla mezzanotte UTC")); + _notifier.Notify(NotificationKind.Alert, "Perdita giornaliera raggiunta", string.Create(CultureInfo.InvariantCulture, $"equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:N2} ({_strategy.DailyLossPct:0.#} %): niente nuove entrate finché resta oltre la soglia, al più fino alla mezzanotte UTC")); } return new BasketContext @@ -1185,6 +1222,13 @@ public sealed partial class BasketEngine : IEngine string evento = outcome.Unwound ? "leg_risk_unwind" : "rifiuto"; slot.Intent = $"NON APERTO — {outcome.Error}"; Log.Warn($"[{slot.Name}] {slot.Intent}"); + + // The leg that was undone has a realised result like any other close: it waits for the history. + if (outcome.Unwound && outcome.UnwindClose is { Closed: true } undo && outcome.UnwoundLeg is { } undone) + { + _knownPositions.Remove(undone.PositionId); + RecordLoneLegClose(slot.Name, basketId, undone, undo, "leg_risk_unwind", outcome.Error); + } if (outcome.Unwound || outcome.Error.Contains("NON richiusa", StringComparison.Ordinal)) { _notifier.Notify(NotificationKind.Alert, $"Unwind: {slot.Name}", TelegramEscape(outcome.Error)); @@ -1238,6 +1282,10 @@ public sealed partial class BasketEngine : IEngine { Log.Warn($"[{slot.Name}] aggiunta non eseguita: {outcome.Error}"); _ledger.Decision(_runId, ModeLabel, PresetLabel, _configHash, ctx, d, outcome.Unwound ? "leg_risk_unwind" : "rifiuto", slot.PositionBasketId, outcome.Error); + if (outcome.Unwound && outcome.UnwindClose is { Closed: true } undo && outcome.UnwoundLeg is { } added) + { + RecordLoneLegClose(slot.Name, slot.PositionBasketId, added, undo, "leg_risk_unwind", "aggiunta richiusa: " + outcome.Error); + } } } catch (Exception ex) when (ex is not OperationCanceledException) @@ -1286,54 +1334,62 @@ public sealed partial class BasketEngine : IEngine } } + /// + /// A basket closed. Its realised result is not known yet on eToro (the close answer + /// has none): the row waits in the settlement queue with the estimate from the exit + /// prices, and is written with the venue's netProfit − fees when the history shows the + /// positions. A simulator's final number is written at once. + /// private void CloseBasket(BasketSlot slot, BasketPosition p, ExitOutcome x, string reasonCode, string reason, BasketContext ctx, BasketDecision? d) { double costUsd = (p.EntryCostPips * ctx.PipValueUsdA * p.A.TotalUnits) + p.AccruedFeesUsd; double gross = x.RealizedPnlUsd + p.A.EntryFeesUsd + p.B.EntryFeesUsd + p.AccruedFeesUsd; + long[] ids = [.. p.A.AllPositionIds.Concat(p.B.AllPositionIds).Where(static id => id > 0).Distinct()]; BasketOutcomeRow row = new( slot.PositionBasketId, _runId, slot.Name, ModeLabel, PresetLabel, p.OpenedUtc, x.ClosedUtc, p.BuyCross, p.EntryZ, d?.Evaluation.Z ?? slot.LastEvaluation.Z, gross, x.RealizedPnlUsd, x.PipsTotal, p.EntryCostPips, costUsd, x.SlippagePipsA + x.SlippagePipsB, p.Adds, p.BarsHeld, reasonCode, p.EquityAtEntry, slot.PMl, - $"{reason} | ingresso: {p.EntryMotivazione}"); - _ledger.Basket(row); - _todayRealized += x.RealizedPnlUsd; - ObserveOutcome(slot, row.Label); + $"{reason} | ingresso: {p.EntryMotivazione} | {PositionMap.Mark(ids)}"); + string detail = string.Create(CultureInfo.InvariantCulture, $"{x.PipsTotal:+0.0;-0.0} pip, {p.BarsHeld} barre, motivo {reasonCode}\n{reason}"); + PendingSettlement settlement = new(PnlCorrectionRecord.KeyOf(row), row, ids, x.RealizedPnlUsd, x.ClosedUtc, true, VolContextAtClose(slot), $"Basket chiuso: {slot.Name}", detail); + if (x.PnlFinal) + { + _settlements.RecordNow(settlement, gross, x.RealizedPnlUsd, SettlementSource.Simulator); + } + else + { + EnqueueSettlement(settlement); + } - foreach (long id in p.A.AllPositionIds.Concat(p.B.AllPositionIds)) + foreach (long id in ids) { _knownPositions.Remove(id); } + string pnl = x.PnlFinal ? $"netto {Signed(x.RealizedPnlUsd)} USD" : $"stima {Signed(x.RealizedPnlUsd)} USD, in attesa dello storico eToro"; Log.Info(string.Create(CultureInfo.InvariantCulture, - $"[{slot.Name}] CHIUSO {slot.PositionBasketId}: netto {x.RealizedPnlUsd:+0.00;-0.00} USD, {x.PipsTotal:+0.0;-0.0} pip, {p.BarsHeld} barre, motivo {reasonCode}")); - _notifier.Notify(NotificationKind.Event, $"Basket chiuso: {slot.Name}", string.Create(CultureInfo.InvariantCulture, - $"netto {x.RealizedPnlUsd:+0.00;-0.00} USD, {x.PipsTotal:+0.0;-0.0} pip, {p.BarsHeld} barre, motivo {reasonCode}\n{TelegramEscape(reason)}")); + $"[{slot.Name}] CHIUSO {slot.PositionBasketId}: {pnl}, {x.PipsTotal:+0.0;-0.0} pip, {p.BarsHeld} barre, motivo {reasonCode}")); if (d is not null) { _ledger.Decision(_runId, ModeLabel, PresetLabel, _configHash, ctx, d, "uscita", slot.PositionBasketId, - string.Create(CultureInfo.InvariantCulture, $"chiuso: netto {x.RealizedPnlUsd:+0.00;-0.00} USD, {x.PipsTotal:+0.0;-0.0} pip, slippage {x.SlippagePipsA + x.SlippagePipsB:+0.0;-0.0} pip")); + string.Create(CultureInfo.InvariantCulture, $"chiuso: {pnl}, {x.PipsTotal:+0.0;-0.0} pip, slippage {x.SlippagePipsA + x.SlippagePipsB:+0.0;-0.0} pip")); } else { - _ledger.Note(_runId, "uscita", slot.PositionBasketId, string.Create(CultureInfo.InvariantCulture, $"{reason}: netto {x.RealizedPnlUsd:+0.00;-0.00} USD, {x.PipsTotal:+0.0;-0.0} pip"), w => w.WriteString("basket", slot.Name)); + _ledger.Note(_runId, "uscita", slot.PositionBasketId, string.Create(CultureInfo.InvariantCulture, $"{reason}: {pnl}, {x.PipsTotal:+0.0;-0.0} pip"), w => w.WriteString("basket", slot.Name)); } slot.Position = null; slot.PositionBasketId = string.Empty; Transition(slot, BasketState.Closed); Transition(slot, BasketState.Idle); - slot.Intent = $"chiuso ({reasonCode}): {x.RealizedPnlUsd:+0.00;-0.00} USD"; + slot.Intent = $"chiuso ({reasonCode}): {pnl}"; SaveState(); } - /// - /// The learning stack sees every close: the shadow model learns, the bandit is - /// rewarded and its proposal is logged. The proposal is not applied (5.0, - /// D-30): a parameter changed by the bot on its own is exactly what the rules forbid; - /// the path to a different preset is a proposal in knowledge/proposals.csv. - /// - private void ObserveOutcome(BasketSlot slot, int label) + /// The volatility context of a close, taken when it happens: the bandit's reward arrives later, with the venue's number. + private int VolContextAtClose(BasketSlot slot) { double sigma = slot.Vol.Count > 0 ? slot.Vol.Forecast() : double.NaN; if (double.IsFinite(sigma)) @@ -1345,12 +1401,46 @@ public sealed partial class BasketEngine : IEngine } } - int context = ThompsonBandit.VolatilityContext(sigma, _volHistory); - _learning.Observe(slot.PositionBasketId, label, context, _decider.Preset.Name); - (PresetName proposed, string text) = _learning.Propose(context); + return ThompsonBandit.VolatilityContext(sigma, _volHistory); + } + + /// + /// A basket's realised result, settled on the venue's history: the shadow model learns, + /// the bandit is rewarded and its proposal is logged. Estimates never get here. The + /// proposal is not applied (5.0, D-30): the path to a different preset is a + /// proposal in knowledge/proposals.csv. + /// + private void Teach(SettledOutcome settled) + { + PresetName preset = BasketPresets.TryParse(settled.Row.Preset, out PresetName parsed) ? parsed : _decider.Preset.Name; + _learning.Observe(settled.Row.BasketId, settled.Row.Label, settled.Pending.VolContext, preset); + (PresetName proposed, string text) = _learning.Propose(settled.Pending.VolContext); Log.Info($"bandit (solo proposta, non applicata): {text}{(proposed != _decider.Preset.Name ? $" — il preset resta {PresetLabel}" : string.Empty)}"); } + /// A close enters the settlement queue; its estimate counts in "P&L oggi" until the history shows it. + private void EnqueueSettlement(PendingSettlement settlement) + { + if (!_settlements.Enqueue(settlement)) + { + return; + } + + _today.AddProvisional(settlement.Key, settlement.Ids, settlement.Estimate, settlement.ClosedUtc, settlement.IsLoneLeg); + _collect?.Add(settlement); + _nextHistoryUtc = DateTime.MinValue; + SaveState(); + } + + /// A number for a log line or a message: signed with two decimals, or "—" when unknown (never "NaN"). + private static string Signed(double v) => double.IsFinite(v) ? v.ToString("+0.00;-0.00;0.00", CultureInfo.InvariantCulture) : "—"; + + /// Net equity now (cash movements excluded); NaN before the first account reading. + private double NetEquityNow => _account.TimeUtc == DateTime.MinValue ? double.NaN : _equity.NetEquity(_account.Equity); + + /// Net equity now minus net equity at the start of the UTC day: realised and unrealised change, cash excluded. NaN while either is unknown. + private double TodayEquityChange => _dayStartEquity > 0 && double.IsFinite(NetEquityNow) ? NetEquityNow - _dayStartEquity : double.NaN; + private void Transition(BasketSlot slot, BasketState to) { if (!BasketLifecycle.CanTransition(slot.State, to)) @@ -1370,17 +1460,23 @@ public sealed partial class BasketEngine : IEngine } _sessionDate = today; - _dayStartEquity = _equity.NetEquity(_account.Equity); - _todayRealized = 0; - Log.Info(string.Create(CultureInfo.InvariantCulture, $"── nuova giornata {today:yyyy-MM-dd}: equity di partenza {_dayStartEquity:F2} (al netto dei movimenti di cassa) ──")); + + // The day starts at the first account reading of the new day (asked for now), and + // its realised result from the first reading of its history: unknown until then. + _dayStartEquity = double.NaN; + _today.Roll(now); + _nextHistoryUtc = DateTime.MinValue; + _lastReconcileUtc = DateTime.MinValue; + Log.Info(string.Create(CultureInfo.InvariantCulture, $"── nuova giornata {today:yyyy-MM-dd} (UTC): equity di partenza alla prossima lettura del conto, P&L di oggi dallo storico eToro ──")); SaveState(); } private void LogStatus() { double dd = _equity.Drawdown(_account.Equity); + string today = Signed(_today.Value) + (_today.IsProvisional ? " stima" : string.Empty); string line = string.Create(CultureInfo.InvariantCulture, - $"[stato] {_mode} · equity {_account.Equity:F2} (saldo {_account.Balance:F2}, aperto {_account.UnrealizedPnl:+0.00;-0.00}, oggi {_todayRealized:+0.00;-0.00}) · DD {dd:P2} dal picco {_equity.PeakEquity:F2} · basket aperti {_slots.Count(static s => s.Position is not null)}/{_decider.Preset.MaxBaskets}, in attesa {_slots.Count(static s => s.State.IsPending())}, ordini pendenti {_tracker.PendingCount}, orfane {_orphanCount}, esterne {_foreignCount} · margine {_account.UsedMargin:F0}/{_account.Available:F0} · API {_apiState} {_apiLatencyMs:F0} ms"); + $"[stato] {_mode} · equity {_account.Equity:F2} (saldo {_account.Balance:F2}, aperto {_account.UnrealizedPnl:+0.00;-0.00}, oggi {today}, equity netta da mezzanotte {Signed(TodayEquityChange)}) · DD {dd:P2} dal picco {_equity.PeakEquity:F2} · basket aperti {_slots.Count(static s => s.Position is not null)}/{_decider.Preset.MaxBaskets}, in attesa {_slots.Count(static s => s.State.IsPending())}, ordini pendenti {_tracker.PendingCount}, da regolare {_settlements.Queue.Count}, orfane {_orphanCount}, esterne {_foreignCount} · margine {_account.UsedMargin:F0}/{_account.Available:F0} · API {_apiState} {_apiLatencyMs:F0} ms"); if (_haltReason is not null) { line += $" · BLOCCO: {_haltReason}"; diff --git a/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs b/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs index 1eae485..5c20005 100644 --- a/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs +++ b/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs @@ -165,13 +165,17 @@ public static class HeadlessRunner Console.WriteLine($"── {done.Message}: rapporto in reports/bonifica_{DateTime.UtcNow:yyyyMMdd}.csv"); } + /// A signed amount for the console, or "—" when unknown (never "NaN"). + private static string Signed(double v) => double.IsFinite(v) ? v.ToString("+0.00;-0.00;0.00", CultureInfo.InvariantCulture) : "—"; + public static void PrintStatus(BotSnapshot s) { Console.WriteLine(); Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"── {DateTime.UtcNow:HH:mm:ss} UTC · {s.Mode} · preset {s.Preset} · API {s.ApiState} {(double.IsFinite(s.ApiLatencyMs) ? s.ApiLatencyMs.ToString("0") + " ms" : "—")} · skew {s.ClockSkewSeconds:+0.0;-0.0} s")); Console.WriteLine(string.Create(CultureInfo.InvariantCulture, - $" BALANCE {s.Balance:N2} EQUITY {s.Equity:N2} APERTO {s.AccountOpenPnl:+0.00;-0.00} (basket {s.OpenPnl:+0.00;-0.00}, {s.OpenPnlPct:P2}) TODAY {s.TodayPnl:+0.00;-0.00} ({s.TodayPnlPct:P2}) DD {s.DrawdownPct:P2} basket {s.OpenBaskets}/{s.MaxBaskets} attesa {s.PendingBaskets} orfane {s.OrphanLegs} esterne {s.ForeignPositions} margine {s.UsedMargin:N0}/{s.AvailableBalance:N0}") + + $" BALANCE {s.Balance:N2} EQUITY {s.Equity:N2} APERTO {s.AccountOpenPnl:+0.00;-0.00} (basket {s.OpenPnl:+0.00;-0.00}, {s.OpenPnlPct:P2}) TODAY {Signed(s.TodayPnl)} ({(double.IsFinite(s.TodayPnlPct) ? s.TodayPnlPct.ToString("P2", CultureInfo.InvariantCulture) : "—")}){(s.TodayPnlProvisional ? " stima" : string.Empty)} EQUITY NETTA DA 00:00 {Signed(s.TodayEquityChange)} DD {s.DrawdownPct:P2} basket {s.OpenBaskets}/{s.MaxBaskets} attesa {s.PendingBaskets} orfane {s.OrphanLegs} esterne {s.ForeignPositions} margine {s.UsedMargin:N0}/{s.AvailableBalance:N0}") + + (s.DailyLossHit ? " PERDITA GIORNALIERA RAGGIUNTA" : string.Empty) + (s.Unreconciled ? $" NON RICONCILIATO: {s.UnreconciledReason}" : string.Empty) + (s.Halted ? $" BLOCCO: {s.HaltReason}" : string.Empty) + (s.EntriesBlockedReason is { Length: > 0 } blocked ? $" entrate bloccate: {blocked}" : string.Empty)); diff --git a/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs b/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs index a4dfe3d..4abd3c3 100644 --- a/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs +++ b/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs @@ -125,19 +125,8 @@ public sealed class HistoryService(BotConfig config) : IAsyncDisposable return rows; } - public List ReadBaskets() - { - List rows = []; - foreach (string line in Ledger.ReadLines(Path.Combine(LedgerDirectory, "baskets.csv"))) - { - if (BasketOutcomeRow.Parse(line) is { } r) - { - rows.Add(r); - } - } - - return rows; - } + /// baskets.csv through the corrected reader (its rows say whose each position is; the P&L of the page comes from the venue). + public List ReadBaskets() => Ledger.ReadBasketsCorrected(LedgerDirectory); /// The movimento_di_cassa lines of every decisions file. public List ReadCashMovements() diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs index 3502cb4..3409e06 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs @@ -35,6 +35,7 @@ public sealed class LearningState : IDisposable private string _lastReport = "nessun ciclo eseguito"; private string _banditProposal = "—"; private double _rollingAuc = double.NaN; + private DateTime _labelsFixedUtc; public LearningState(string dataDir, string knowledgeDir, Ledger ledger, BasketStrategyConfig cfg) { @@ -58,6 +59,33 @@ public sealed class LearningState : IDisposable public int Version => _version; + /// True once the models learnt from the proceeds-as-profit labels of 4.0.0–5.0.0 have been retired and rebuilt (). + public bool LabelsFixed => _labelsFixedUtc != default; + + /// The bandit's state as JSON (what bandit.json holds). + public string BanditJson + { + get + { + lock (_gate) + { + return _bandit.ToJson(); + } + } + } + + /// How many labelled baskets the shadow logistic has seen. + public int LogisticSeen + { + get + { + lock (_gate) + { + return _logistic.Seen; + } + } + } + /// Mean of the last ten labels, or NaN before there are any. public double LastOutcomes { @@ -252,18 +280,30 @@ public sealed class LearningState : IDisposable return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString())))[..16].ToLowerInvariant(); } - /// Joins the ingresso rows of the decisions ledger (features at entry) with the closed baskets (labels). + /// + /// Joins the ingresso rows of the decisions ledger (features at entry) with the + /// closed baskets (labels), read through the corrected reader: a row whose P&L the + /// venue has not established (an estimate, an unverifiable correction) has no label and + /// is left out; lone legs are not baskets. The lastNOutcomes feature of the rows + /// written before the feature_inaffidabile mark was computed from proceeds-based + /// labels: it is set to its neutral value (0.5, the value used when it is missing), + /// never rebuilt after the fact. + /// public List BuildDataset() { Dictionary outcomes = new(StringComparer.Ordinal); - foreach (BasketOutcomeRow r in _ledger.ReadBaskets()) + foreach (BasketOutcomeRow r in _ledger.ReadBasketsCorrected()) { - outcomes[r.BasketId] = r; + if (r.HasLabel && !r.IsLoneLeg && r.BasketId.Length > 0) + { + outcomes[r.BasketId] = r; + } } + DateTime maskLastOutcomesUntil = _ledger.ReadFeatureMaskUntil(LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]); Dictionary entries = new(StringComparer.Ordinal); string dir = Path.GetDirectoryName(_ledger.DecisionsPath)!; - foreach (string file in Directory.GetFiles(dir, "decisions*.jsonl").OrderBy(static f => f, StringComparer.Ordinal)) + foreach (string file in Ledger.DecisionFiles(dir)) { foreach (string line in Ledger.ReadLines(file)) { @@ -290,7 +330,14 @@ public sealed class LearningState : IDisposable continue; } - rows.Add(new LabelledBasket(id, o.OpenedUtc, o.ClosedUtc, e.Features, o.Label, o.PnlNetUsd, o.Basket, o.Preset, e.Features[25])); + double[] f = e.Features; + if (e.Ts < maskLastOutcomesUntil) + { + f = [.. f]; + f[LearningFeatures.LastOutcomesIndex] = 0.5; + } + + rows.Add(new LabelledBasket(id, o.OpenedUtc, o.ClosedUtc, f, o.Label, o.PnlNetUsd, o.Basket, o.Preset, f[LearningFeatures.VolRatioIndex])); } rows.Sort(static (a, b) => a.OpenedUtc.CompareTo(b.OpenedUtc)); @@ -420,6 +467,7 @@ public sealed class LearningState : IDisposable w.WriteNumber("version", _version); w.WriteString("lastCycleUtc", _lastCycleUtc.ToString("O", CultureInfo.InvariantCulture)); w.WriteString("lastReport", _lastReport); + w.WriteString("labelsFixedUtc", _labelsFixedUtc == default ? string.Empty : _labelsFixedUtc.ToString("O", CultureInfo.InvariantCulture)); w.WriteStartArray("recent"); foreach ((double p, int label) in _recent) { @@ -490,6 +538,12 @@ public sealed class LearningState : IDisposable _lastCycleUtc = t; } + if (r.TryGetProperty("labelsFixedUtc", out JsonElement lf) && lf.GetString() is { Length: > 0 } fixedText && + DateTime.TryParse(fixedText, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime fixedUtc)) + { + _labelsFixedUtc = fixedUtc; + } + if (r.TryGetProperty("recent", out JsonElement recent)) { foreach (JsonElement e in recent.EnumerateArray()) @@ -517,11 +571,12 @@ public sealed class LearningState : IDisposable } } + /// The recent outcomes behind lastNOutcomes: the last hundred baskets whose P&L the venue established. private void SeedOutcomesFromLedger() { try { - foreach (BasketOutcomeRow r in _ledger.ReadBaskets().TakeLast(100)) + foreach (BasketOutcomeRow r in _ledger.ReadBasketsCorrected().Where(static r => r.HasLabel && !r.IsLoneLeg).TakeLast(100)) { _lastOutcomes.Add(r.Label); } @@ -532,5 +587,78 @@ public sealed class LearningState : IDisposable } } + /// + /// Retires the models that learnt from the labels of 4.0.0–5.0.0, where the close + /// proceeds (margin + profit) were taken as the profit and almost every basket looked + /// like a win. Once only: the current model files are copied (the versioned ones moved) + /// to models/ritirati/<utc>-etichette-proceeds/; the logistic restarts and is + /// replayed on the corrected ledger (features as written at the decision, labels from + /// the venue); the challenger goes away until the next cycle; the bandit restarts from + /// its prior, because the volatility context of its past rewards is not in the ledger. + /// One line in models_registry.csv says it. Returns false when already done. + /// + public bool RetireAndReplay(DateTime nowUtc, string reason) + { + List replay = BuildDataset(); + lock (_gate) + { + if (_labelsFixedUtc != default) + { + return false; + } + + string aside = Path.Combine(_modelsDir, "ritirati", nowUtc.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + "-etichette-proceeds"); + Directory.CreateDirectory(aside); + foreach (string name in (string[])["logreg_current.json", "mlp_current.json", "bandit.json", "learning_state.json"]) + { + string source = Path.Combine(_modelsDir, name); + if (File.Exists(source)) + { + File.Copy(source, Path.Combine(aside, name), overwrite: true); + } + } + + foreach (string versioned in Directory.GetFiles(_modelsDir, "logreg_v*.json").Concat(Directory.GetFiles(_modelsDir, "mlp_v*.json"))) + { + File.Move(versioned, Path.Combine(aside, Path.GetFileName(versioned)), overwrite: true); + } + + string mlpCurrent = Path.Combine(_modelsDir, "mlp_current.json"); + if (File.Exists(mlpCurrent)) + { + File.Delete(mlpCurrent); + } + + _logistic = new OnlineLogistic(LearningFeatures.Count); + _challenger = null; + _champion = "logistica"; + _bandit = new ThompsonBandit(3, 42); + _banditProposal = "—"; + _recent.Clear(); + _lastOutcomes.Clear(); + _active = false; + _rollingAuc = double.NaN; + foreach (LabelledBasket b in replay) + { + _logistic.Update(b.Features, b.Label); + _lastOutcomes.Add(b.Label); + } + + while (_lastOutcomes.Count > 100) + { + _lastOutcomes.RemoveAt(0); + } + + _lastReport = string.Create(CultureInfo.InvariantCulture, $"modelli ritirati il {nowUtc:yyyy-MM-dd HH:mm} UTC (etichette dai proceeds): logistica rifatta su {replay.Count} basket con le etichette corrette, bandit dal prior"); + AppendRegistry("models_registry.csv", "versione;data;tipo;n_train;auc_wf;brier;logloss;stato;motivazione", + string.Create(CultureInfo.InvariantCulture, $"v{_version};{nowUtc:O};logistica+bandit;{replay.Count};;;;ritirato;{reason.Replace(';', ',')}")); + _labelsFixedUtc = nowUtc; + Save(); + } + + Log.Warn($"apprendimento: modelli addestrati sulle etichette sbagliate ritirati e rifatti ({replay.Count} basket con il P&L dello storico eToro); il bandit riparte dal prior"); + return true; + } + public void Dispose() => Save(); } diff --git a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs index fcd7587..04fc5f5 100644 --- a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs +++ b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs @@ -214,11 +214,87 @@ public sealed class Ledger : IDisposable /// A correction is a new line, never an edit of an old one. public void Correction(string runId, string basketId, string what) => Note(runId, "correzione", basketId, what); - /// Reads every closed basket, oldest first: the training set. - public List ReadBaskets() + /// + /// The realised result of one row of baskets.csv as the venue's history gives it + /// (tipo = pnl_realizzato), or — false — the admission + /// that it cannot be established. The row itself is never touched: the corrected reader + /// applies the newest line of its key. + /// + public void PnlCorrection(string runId, BasketOutcomeRow row, double gross, double net, bool verified, IReadOnlyCollection ids, string motivazione) + { + ArgumentNullException.ThrowIfNull(row); + ArgumentNullException.ThrowIfNull(ids); + Note(runId, PnlCorrectionRecord.Evento, row.BasketId, motivazione, w => + { + w.WriteString("tipo", PnlCorrectionRecord.Kind); + w.WriteString("riga", PnlCorrectionRecord.KeyOf(row)); + w.WriteString("basket", row.Basket); + w.WriteString("exit_reason", row.ExitReason); + Num(w, "pnl_net_registrato", row.PnlNetUsd); + if (verified && double.IsFinite(net)) + { + Num(w, "pnl_gross_corretto", gross); + Num(w, "pnl_net_corretto", net); + w.WriteNumber("label_corretta", net > 0 ? 1 : 0); + } + else + { + w.WriteNull("pnl_gross_corretto"); + w.WriteNull("pnl_net_corretto"); + w.WriteNull("label_corretta"); + } + + w.WriteBoolean("verificata", verified && double.IsFinite(net)); + w.WriteStartArray("position_ids"); + foreach (long id in ids) + { + w.WriteNumberValue(id); + } + + w.WriteEndArray(); + w.WriteString("fonte", "storico eToro: netProfit - fees"); + }); + + static void Num(Utf8JsonWriter w, string name, double v) + { + if (double.IsFinite(v)) + { + w.WriteNumber(name, Math.Round(v, 2)); + } + else + { + w.WriteNull(name); + } + } + } + + /// One-off line: is unreliable in every evaluation row written before . + public void FeatureUnreliable(string runId, string feature, int index, DateTime untilUtc, string motivazione) => + Note(runId, PnlCorrectionRecord.Evento, string.Empty, motivazione, w => + { + w.WriteString("tipo", LedgerMarkers.FeatureUnreliable); + w.WriteString("feature", feature); + w.WriteNumber("indice", index); + w.WriteString("fino_a", untilUtc.ToString("O", CultureInfo.InvariantCulture)); + }); + + /// One-off line: the pnl fields and the "netto" texts of the notes written in this range are the close proceeds, not the P&L. + public void ProceedsNotesRange(string runId, DateTime fromUtc, DateTime toUtc, string motivazione) => + Note(runId, PnlCorrectionRecord.Evento, string.Empty, motivazione, w => + { + w.WriteString("tipo", LedgerMarkers.ProceedsNotes); + w.WriteString("da", fromUtc.ToString("O", CultureInfo.InvariantCulture)); + w.WriteString("a", toUtc.ToString("O", CultureInfo.InvariantCulture)); + }); + + /// Reads every closed basket, oldest first, as the file has it (uncorrected). + public List ReadBaskets() => ReadBaskets(_directory); + + /// Every row of baskets.csv in , oldest first, as written. + public static List ReadBaskets(string directory) { List rows = []; - foreach (string line in ReadLines(BasketsPath)) + foreach (string line in ReadLines(Path.Combine(directory, "baskets.csv"))) { if (BasketOutcomeRow.Parse(line) is { } r) { @@ -230,6 +306,244 @@ public sealed class Ledger : IDisposable return rows; } + /// + /// baskets.csv as it must be read: the newest P&L correction applied to every + /// row, estimates and unverifiable rows marked (). + /// The file is never changed. The training set, the reports and the summaries read this. + /// + public List ReadBasketsCorrected() => ReadBasketsCorrected(_directory); + + public static List ReadBasketsCorrected(string directory) => + BasketCorrections.Apply(ReadBaskets(directory), ReadPnlCorrections(directory)); + + /// Every pnl_realizzato correction of every decisions*.jsonl (rotated months included), oldest first. + public List ReadPnlCorrections() => ReadPnlCorrections(_directory); + + public static List ReadPnlCorrections(string directory) => + [.. DecisionFiles(directory).SelectMany(static f => CorrectionScan.Read(f)).OrderBy(static c => c.Ts)]; + + /// The time until which is unreliable (feature_inaffidabile); when never marked. + public DateTime ReadFeatureMaskUntil(string feature) + { + DateTime until = DateTime.MinValue; + foreach (string line in DecisionLines(_directory, LedgerMarkers.FeatureUnreliable)) + { + if (LedgerMarkers.TryParseFeatureMask(line, out string f, out DateTime t) && f == feature && t > until) + { + until = t; + } + } + + return until; + } + + /// Whether a correzione line of this tipo was ever written. + public bool HasCorrectionOfKind(string kind) => DecisionLines(_directory, kind).Any(line => LedgerMarkers.IsCorrectionOfKind(line, kind)); + + /// The closing time of the last row the realised-P&L check has verified (verifica_realizzato); MinValue when never run. + public DateTime ReadBackfillWatermark() + { + DateTime until = DateTime.MinValue; + foreach (string line in DecisionLines(_directory, LedgerMarkers.BackfillEvento)) + { + if (LedgerMarkers.TryParseBackfill(line, out DateTime t) && t > until) + { + until = t; + } + } + + return until; + } + + /// The notes that name a lone leg the bot closed: leg_risk_unwind and orfana_chiusa with a position_id. + public List ReadLoneLegNotes() + { + List notes = []; + foreach (string line in DecisionLines(_directory, "position_id")) + { + if (!line.Contains("\"leg_risk_unwind\"", StringComparison.Ordinal) && !line.Contains("\"orfana_chiusa\"", StringComparison.Ordinal)) + { + continue; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + string evento = Str(r, "evento"); + if (evento is not ("leg_risk_unwind" or "orfana_chiusa") || !r.TryGetProperty("position_id", out JsonElement pid) || pid.ValueKind != JsonValueKind.Number) + { + continue; + } + + string exit = evento == "leg_risk_unwind" ? "leg_risk_unwind" : Str(r, "exit_reason"); + notes.Add(new LoneLegNote(Time(r, "ts"), evento, Str(r, "basket_id"), pid.GetInt64(), Str(r, "strumento"), exit)); + } + catch (JsonException) + { + // A damaged line is skipped, never repaired. + } + } + + return notes; + } + + /// The fill prices of every opened basket, from its ingresso line (eseguito: A @ …, B @ …). + public List ReadEntryFills() + { + List fills = []; + foreach (string line in DecisionLines(_directory, "eseguito: A @")) + { + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + if (Str(r, "evento") != "ingresso") + { + continue; + } + + System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(Str(r, "motivazione"), @"eseguito: A @ ([0-9]+(?:\.[0-9]+)?).*?B @ ([0-9]+(?:\.[0-9]+)?)", System.Text.RegularExpressions.RegexOptions.CultureInvariant); + if (m.Success) + { + fills.Add(new EntryFill(Str(r, "basket_id"), Time(r, "ts"), double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), double.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture))); + } + } + catch (JsonException) + { + // A damaged line is skipped. + } + } + + return fills; + } + + /// The decision files of a ledger folder in time order: the rotated months, then the current one. + public static List DecisionFiles(string directory) + { + if (!Directory.Exists(directory)) + { + return []; + } + + List rotated = [.. Directory.GetFiles(directory, "decisions_*.jsonl").OrderBy(static f => f, StringComparer.Ordinal)]; + string current = Path.Combine(directory, "decisions.jsonl"); + if (File.Exists(current)) + { + rotated.Add(current); + } + + return rotated; + } + + /// The lines of every decision file that contain , oldest first. + private static IEnumerable DecisionLines(string directory, string mustContain) + { + foreach (string file in DecisionFiles(directory)) + { + foreach (string line in ReadLines(file)) + { + if (line.Contains(mustContain, StringComparison.Ordinal)) + { + yield return line; + } + } + } + } + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + private static DateTime Time(JsonElement e, string name) => + DateTime.TryParse(Str(e, name), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : default; + + /// + /// The P&L corrections of one decision file, read incrementally: the ledger's files + /// only grow, so after the first reading only the bytes appended since are scanned + /// (the Storico page asks often; a month of evaluations is tens of megabytes). A file + /// whose first bytes changed, or that got shorter, is another file (the month rotated) + /// and is read again from the start. + /// + private static class CorrectionScan + { + private const int HeadBytes = 256; + + private sealed class Entry + { + public readonly Lock Gate = new(); + public readonly List Items = []; + public long Offset; + public byte[] Head = []; + } + + private static readonly System.Collections.Concurrent.ConcurrentDictionary Files = new(StringComparer.OrdinalIgnoreCase); + + public static List Read(string path) + { + Entry entry = Files.GetOrAdd(Path.GetFullPath(path), static _ => new Entry()); + lock (entry.Gate) + { + try + { + using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + byte[] head = ReadAt(stream, 0, (int)Math.Min(HeadBytes, stream.Length)); + int common = Math.Min(head.Length, entry.Head.Length); + if (stream.Length < entry.Offset || !head.AsSpan(0, common).SequenceEqual(entry.Head.AsSpan(0, common))) + { + entry.Offset = 0; + entry.Items.Clear(); + } + + entry.Head = head; + if (stream.Length > entry.Offset) + { + byte[] buffer = ReadAt(stream, entry.Offset, (int)Math.Min(int.MaxValue, stream.Length - entry.Offset)); + + // Only whole lines: a line still being written is read next time. + int end = buffer.Length == 0 ? -1 : Array.LastIndexOf(buffer, (byte)'\n'); + if (end >= 0) + { + foreach (string line in Encoding.UTF8.GetString(buffer, 0, end + 1).Split('\n')) + { + if (PnlCorrectionRecord.TryParse(line.TrimEnd('\r')) is { } c) + { + entry.Items.Add(c); + } + } + + entry.Offset += end + 1; + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warn($"ledger: correzioni non lette da {Path.GetFileName(path)} ({ex.Message})"); + } + + return [.. entry.Items]; + } + } + + private static byte[] ReadAt(FileStream stream, long offset, int count) + { + byte[] buffer = new byte[count]; + stream.Seek(offset, SeekOrigin.Begin); + int read = 0; + while (read < count) + { + int n = stream.Read(buffer, read, count - read); + if (n == 0) + { + break; + } + + read += n; + } + + return read == count ? buffer : buffer[..read]; + } + } + /// The current month's decision lines, oldest first. public List ReadDecisionLines() => ReadLines(DecisionsPath); diff --git a/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs b/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs new file mode 100644 index 0000000..11b9a7c --- /dev/null +++ b/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs @@ -0,0 +1,161 @@ +using System.Globalization; +using Encelado.Core.Baskets.History; +using Encelado.Core.Broker; + +namespace Encelado.Engine.Baskets; + +/// What one run of the realised-P&L check did. +public sealed record BackfillReport(int Checked, int Agreeing, int Corrected, int Unverifiable) +{ + public static readonly BackfillReport None = new(0, 0, 0, 0); + + public string Describe() => string.Create(CultureInfo.InvariantCulture, + $"{Checked} righe: {Agreeing} concordi, {Corrected} corrette, {Unverifiable} non verificabili"); +} + +/// +/// The correction of the realised results written by 4.0.0–5.0.0 (decision P5 of 5.1). +/// Those versions recorded the close proceeds (margin released + profit) as the P&L +/// of every basket and lone leg. At startup, on the Demo or Live account, every row of +/// baskets.csv of that account not yet verified is looked up in the venue's history +/// by position id: a row that agrees is left alone; one that disagrees gets a +/// correzione line (tipo = pnl_realizzato) with netProfit − fees; one whose +/// positions cannot be found gets a line that declares it unverifiable (no label). No row +/// is ever edited. Idempotent: a verified row is never checked again, the check ends +/// with a verifica_realizzato note, and a history that cannot be read writes nothing +/// (the check runs again at the next start). A row settled by 5.1 on the history is right +/// by construction; one written with the estimate is checked until the history confirms it. +/// +public sealed class RealizedBackfill( + Ledger ledger, + Func>> history, + string runId, + string mode, + Func instrumentOf, + Action? log = null) +{ + /// The marker every row settled by 5.1 carries in its motivation (| P&L: storico eToro, | P&L: stima…). + private const string SettledMarker = "| P&L: "; + + private readonly Ledger _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + private readonly Func>> _history = history ?? throw new ArgumentNullException(nameof(history)); + private readonly Func _instrumentOf = instrumentOf ?? throw new ArgumentNullException(nameof(instrumentOf)); + private readonly Action _log = log ?? (static _ => { }); + + public async Task RunAsync(DateTime nowUtc, CancellationToken ct) + { + Dictionary newest = BasketCorrections.Newest(_ledger.ReadPnlCorrections()); + DateTime watermark = _ledger.ReadBackfillWatermark(); + List<(BasketOutcomeRow Row, bool Retry)> rows = []; + foreach (BasketOutcomeRow r in _ledger.ReadBaskets()) + { + if (!SameAccount(r.Mode, mode) || r.Motivazione.Contains(BasketCorrections.VenueMarker, StringComparison.Ordinal)) + { + continue; + } + + if (newest.TryGetValue(PnlCorrectionRecord.KeyOf(r), out PnlCorrectionRecord? c)) + { + if (!c.Verified) + { + rows.Add((r, true)); // asked again; a new line only if the history now shows it + } + + continue; + } + + if (r.ClosedUtc > watermark || r.Motivazione.Contains(BasketCorrections.EstimateMarker, StringComparison.Ordinal)) + { + rows.Add((r, false)); + } + } + + if (rows.Count == 0) + { + return BackfillReport.None; + } + + // The route looks back less than a year; its minDate is the closing day (UTC). + DateTime oldest = rows.Min(static r => r.Row.ClosedUtc).Date.AddDays(-1); + DateTime from = oldest > nowUtc.Date.AddDays(-364) ? oldest : nowUtc.Date.AddDays(-364); + IReadOnlyList trades = await _history(from, ct).ConfigureAwait(false); + PositionMap map = PositionMap.Build(_ledger.ReadOrders(), _ledger.ReadLoneLegNotes(), _ledger.ReadEntryFills()); + + int agree = 0, corrected = 0, unverifiable = 0; + foreach ((BasketOutcomeRow r, bool retry) in rows) + { + IReadOnlyList ids = map.IdsOf(r, trades, _instrumentOf); + Settlement s = RealizedSettlement.Of(ids, trades); + bool estimate = r.Motivazione.Contains(BasketCorrections.EstimateMarker, StringComparison.Ordinal); + if (ids.Count == 0 || !s.Complete) + { + unverifiable++; + if (!retry) + { + _ledger.PnlCorrection(runId, r, double.NaN, double.NaN, false, ids, ids.Count == 0 + ? "posizioni della riga non ricostruibili dai file del bot: P&L non verificabile, riga esclusa dall'addestramento e dai riepiloghi" + : string.Create(CultureInfo.InvariantCulture, $"{s.Missing.Count} posizioni su {ids.Count} non ritrovate nello storico eToro: P&L non verificabile, riga esclusa dall'addestramento e dai riepiloghi")); + } + } + else if (!retry && !estimate && double.IsFinite(r.PnlNetUsd) && Math.Abs(s.NetUsd - r.PnlNetUsd) <= 0.01) + { + agree++; + } + else + { + corrected++; + string was = estimate ? "stimato dai prezzi di chiusura" : retry ? "non verificabile finora" : "= proceeds della chiusura (margine restituito + profitto), non il realizzato"; + _ledger.PnlCorrection(runId, r, s.GrossUsd, s.NetUsd, true, ids, string.Create(CultureInfo.InvariantCulture, + $"P&L registrato {Signed(r.PnlNetUsd)} USD {was}; storico eToro {Signed(s.NetUsd)} USD (netProfit − fees di {ids.Count} posizioni)")); + } + } + + BackfillReport report = new(rows.Count, agree, corrected, unverifiable); + + // The note marks how far the check went; a start that only asked again about rows + // still unverifiable, and found nothing new, writes nothing at all. + List fresh = [.. rows.Where(static r => !r.Retry).Select(static r => r.Row)]; + if (fresh.Count > 0 || corrected > 0) + { + DateTime until = (fresh.Count > 0 ? fresh : rows.Select(static r => r.Row)).Max(static r => r.ClosedUtc); + _ledger.Note(runId, LedgerMarkers.BackfillEvento, string.Empty, $"verifica del realizzato sullo storico eToro: {report.Describe()}", w => + { + w.WriteString("fino_a", until.ToString("O", CultureInfo.InvariantCulture)); + w.WriteNumber("righe", report.Checked); + w.WriteNumber("concordi", report.Agreeing); + w.WriteNumber("corrette", report.Corrected); + w.WriteNumber("non_verificabili", report.Unverifiable); + }); + _log($"verifica del realizzato: {report.Describe()}"); + } + + return report; + } + + /// + /// True when a row written before the fix (no | P&L: … marker) carries a correction: + /// the models learnt from wrong labels and must be retired (once). + /// + public static bool LegacyRowsWereCorrected(Ledger ledger) + { + ArgumentNullException.ThrowIfNull(ledger); + List corrections = ledger.ReadPnlCorrections(); + if (corrections.Count == 0) + { + return false; + } + + HashSet keys = [.. corrections.Select(static c => c.RowKey)]; + return ledger.ReadBaskets().Any(r => !r.Motivazione.Contains(SettledMarker, StringComparison.Ordinal) && keys.Contains(PnlCorrectionRecord.KeyOf(r))); + } + + private static string Signed(double v) => double.IsFinite(v) ? v.ToString("+0.00;-0.00;0.00", CultureInfo.InvariantCulture) : "—"; + + /// + /// Whether a row was written on the account the engine now reads: the same mode, with the + /// names of the first 4.0.0 files (DemoApprove, DemoAuto) counted as Demo. + /// + public static bool SameAccount(string rowMode, string mode) => + rowMode.Equals(mode, StringComparison.OrdinalIgnoreCase) || + (mode.Equals("Demo", StringComparison.OrdinalIgnoreCase) && rowMode.StartsWith("Demo", StringComparison.OrdinalIgnoreCase)); +} diff --git a/Encelado/src/Encelado.Engine/Baskets/Settlements.cs b/Encelado/src/Encelado.Engine/Baskets/Settlements.cs new file mode 100644 index 0000000..ea30355 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Baskets/Settlements.cs @@ -0,0 +1,132 @@ +using System.Globalization; +using Encelado.Core.Baskets.History; +using Encelado.Core.Broker; +using Encelado.Core.Notifications; +using Encelado.Engine.Logging; + +namespace Encelado.Engine.Baskets; + +/// +/// Where every close waits for its realised result (decision P2 of 5.1). The engine +/// enqueues a close with its estimate; each reading of the venue's history settles what +/// it shows: one row in baskets.csv with netProfit − fees, one +/// realizzato note, one message, and — for a basket — one lesson for the learning +/// stack. A close the history does not show within 30 minutes is written with the +/// estimate, flagged P&L: stima, and teaches nothing. The queue itself lives in the +/// engine's state on disk. +/// +public sealed class Settlements +{ + private readonly Ledger _ledger; + private readonly string _runId; + private readonly INotifier _notifier; + private readonly Action _teach; + private readonly Action? _rowWritten; + + public Settlements(Ledger ledger, string runId, INotifier notifier, Action teach, Action? rowWritten = null) + { + _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + _runId = runId ?? string.Empty; + _notifier = notifier ?? NullNotifier.Instance; + _teach = teach ?? throw new ArgumentNullException(nameof(teach)); + _rowWritten = rowWritten; + } + + public SettlementQueue Queue { get; } = new(); + + public bool Enqueue(PendingSettlement settlement) => Queue.Add(settlement); + + /// Settles what a fresh reading of the history confirms, and what waited past the timeout. Returns what was written. + public List Apply(IReadOnlyList history, DateTime nowUtc) + { + List done = Queue.Resolve(history, nowUtc); + foreach (SettledOutcome s in done) + { + Record(s); + } + + return done; + } + + /// A close whose final number is already known (a simulator): written at once. + public SettledOutcome RecordNow(PendingSettlement settlement, double gross, double net, SettlementSource source) + { + SettledOutcome s = SettlementQueue.Settle(settlement, gross, net, source); + Record(s); + return s; + } + + private void Record(SettledOutcome s) + { + PendingSettlement p = s.Pending; + _ledger.Basket(s.Row); + _rowWritten?.Invoke(s.Row); + string source = s.Source switch + { + SettlementSource.Venue => "storico eToro", + SettlementSource.Estimate => "stima dai prezzi di chiusura", + _ => "simulatore", + }; + string text = string.Create(CultureInfo.InvariantCulture, + $"{(p.IsLoneLeg ? "gamba singola" : "basket")} {p.Row.Basket} ({p.Row.ExitReason}): netto {Signed(s.NetUsd)} USD dallo {source}{(s.Source == SettlementSource.Venue && double.IsFinite(p.Estimate) ? $", stimato {Signed(p.Estimate)} alla chiusura" : string.Empty)}"); + _ledger.Note(_runId, "realizzato", p.Row.BasketId, text, w => + { + w.WriteString("basket", p.Row.Basket); + w.WriteString("exit_reason", p.Row.ExitReason); + w.WriteString("fonte", source); + w.WriteStartArray("position_ids"); + foreach (long id in p.Ids) + { + w.WriteNumberValue(id); + } + + w.WriteEndArray(); + Num(w, "pnl_lordo", s.GrossUsd); + Num(w, "pnl_netto", s.NetUsd); + Num(w, "stima", p.Estimate); + }); + + if (s.Source == SettlementSource.Estimate) + { + Log.Warn($"[{p.Row.Basket}] {text}: lo storico eToro non mostra le posizioni {string.Join(", ", p.Ids)} dopo 30 minuti; la riga resta una stima e non insegna niente ai modelli"); + } + else + { + Log.Info($"[{p.Row.Basket}] realizzato {p.Row.BasketId}: {text}"); + } + + // Only a final number teaches: an estimate never becomes a label. A failure of the + // learning code never stops the settlement of the other closes. + if (p.Learn && s.IsFinal && double.IsFinite(s.NetUsd)) + { + try + { + _teach(s); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Error($"[{p.Row.Basket}] apprendimento non aggiornato per {p.Row.BasketId}", ex); + } + } + + if (p.Title.Length > 0) + { + _notifier.Notify(NotificationKind.Event, p.Title, string.Create(CultureInfo.InvariantCulture, + $"netto {Signed(s.NetUsd)} USD ({TelegramNotifier.Escape(source)}){(p.Detail.Length > 0 ? ", " + TelegramNotifier.Escape(p.Detail) : string.Empty)}")); + } + } + + private static string Signed(double v) => double.IsFinite(v) ? v.ToString("+0.00;-0.00;0.00", CultureInfo.InvariantCulture) : "—"; + + private static void Num(System.Text.Json.Utf8JsonWriter w, string name, double v) + { + if (double.IsFinite(v)) + { + w.WriteNumber(name, Math.Round(v, 2)); + } + else + { + w.WriteNull(name); + } + } +} diff --git a/Encelado/src/Encelado.Engine/Baskets/TelegramReports.cs b/Encelado/src/Encelado.Engine/Baskets/TelegramReports.cs index 1a12adb..ca62022 100644 --- a/Encelado/src/Encelado.Engine/Baskets/TelegramReports.cs +++ b/Encelado/src/Encelado.Engine/Baskets/TelegramReports.cs @@ -23,7 +23,11 @@ public static class TelegramReports string state = s.HaltedWithResidue ? "BLOCCATO CON RESIDUO" : s.Halted ? "BLOCCATO" : s.State == BotState.Running ? "attivo" : "fermo"; sb.Append(CultureInfo.InvariantCulture, $"{E(state)} · {E(s.Mode)} · {E(s.ExecutionMode)} · preset {E(s.Preset)} · attivo da {E(Uptime(s.Uptime))}\n"); sb.Append(CultureInfo.InvariantCulture, $"Equity {s.Equity:N2} · saldo {s.Balance:N2} · disponibile {s.AvailableBalance:N2} · margine usato {s.UsedMargin:N2}\n"); - sb.Append(CultureInfo.InvariantCulture, $"P&L oggi {s.TodayPnl:+0.00;-0.00;0.00} ({s.TodayPnlPct:P2}) · aperto (conto) {s.AccountOpenPnl:+0.00;-0.00;0.00} · di cui basket {s.OpenPnl:+0.00;-0.00;0.00}\n"); + sb.Append(CultureInfo.InvariantCulture, $"P&L oggi {Signed(s.TodayPnl)} ({Pct(s.TodayPnlPct)}){(s.TodayPnlProvisional ? " stima" : string.Empty)} · equity netta da mezzanotte {Signed(s.TodayEquityChange)} · aperto (conto) {Signed(s.AccountOpenPnl)} · di cui basket {Signed(s.OpenPnl)}\n"); + if (s.DailyLossHit) + { + sb.Append("⚠ Perdita giornaliera raggiunta: niente nuove entrate finché resta oltre la soglia (al più fino alle 00:00 UTC)\n"); + } sb.Append(CultureInfo.InvariantCulture, $"Drawdown {s.DrawdownPct:P2} dal picco {s.PeakEquity:N2} (stop a {s.EquityStopPct:P0})\n"); sb.Append(CultureInfo.InvariantCulture, $"Basket aperti {s.OpenBaskets}/{s.MaxBaskets} · in attesa {s.PendingBaskets} · ordini pendenti {s.PendingOrders} · orfane {s.OrphanLegs} · esterne {s.ForeignPositions}\n"); foreach (BasketRow b in s.Baskets.Where(static b => b.IsOpen)) @@ -95,15 +99,21 @@ public static class TelegramReports return sb.ToString(); } - /// The daily summary and the answer to /storico: the closed baskets of a period. + /// + /// The daily summary and the answer to /storico: the closed baskets of a period, + /// read through the corrected reader. A row whose P&L the venue has not established + /// (an estimate, an unverifiable correction) is left out of the sums and counted apart. + /// public static string Period(string label, IReadOnlyList rows, double drawdownPct) { ArgumentNullException.ThrowIfNull(rows); - int n = rows.Count; - int won = rows.Count(static r => r.PnlNetUsd > 0); - double gross = rows.Sum(static r => double.IsFinite(r.PnlGrossUsd) ? r.PnlGrossUsd : r.PnlNetUsd); - double net = rows.Sum(static r => r.PnlNetUsd); - double cost = rows.Sum(static r => double.IsFinite(r.CostUsd) ? r.CostUsd : 0); + List known = [.. rows.Where(static r => r.HasLabel)]; + int skipped = rows.Count - known.Count; + int n = known.Count; + int won = known.Count(static r => r.PnlNetUsd > 0); + double gross = known.Sum(static r => double.IsFinite(r.PnlGrossUsd) ? r.PnlGrossUsd : r.PnlNetUsd); + double net = known.Sum(static r => r.PnlNetUsd); + double cost = known.Sum(static r => double.IsFinite(r.CostUsd) ? r.CostUsd : 0); StringBuilder sb = new(); sb.Append(CultureInfo.InvariantCulture, $"{E(label)}: {n} basket chiusi"); if (n > 0) @@ -111,6 +121,11 @@ public static class TelegramReports sb.Append(CultureInfo.InvariantCulture, $", {won} vinti ({(double)won / n:P0}), lordo {gross:+0.00;-0.00} USD, costi {cost:0.00}, netto {net:+0.00;-0.00} USD, media {net / n:+0.00;-0.00} per basket"); } + if (skipped > 0) + { + sb.Append(CultureInfo.InvariantCulture, $" ({skipped} esclusi: P&L non confermato dallo storico eToro)"); + } + sb.Append(CultureInfo.InvariantCulture, $"; drawdown attuale {drawdownPct:P2}"); Dictionary reasons = rows.GroupBy(static r => r.ExitReason).ToDictionary(static g => g.Key, static g => g.Count()); if (reasons.Count > 0) @@ -126,6 +141,11 @@ public static class TelegramReports private static string E(string? s) => TelegramNotifier.Escape(s); + /// A signed amount, or "—" when unknown: a message never says NaN. + private static string Signed(double v) => double.IsFinite(v) ? v.ToString("+0.00;-0.00;0.00", It) : "—"; + + private static string Pct(double v) => double.IsFinite(v) ? v.ToString("P2", It) : "—"; + private static string Uptime(TimeSpan t) => t.TotalHours >= 1 ? $"{(int)t.TotalHours}h {t.Minutes}m" : t.TotalMinutes >= 1 ? $"{t.Minutes}m" : "meno di un minuto"; } diff --git a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs index 12b0af9..30ea9cb 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs @@ -165,9 +165,36 @@ public sealed record BotSnapshot public double DailyLossPct { get; init; } - public double TodayPnl { get; init; } + /// + /// "P&L oggi": the realised net result (netProfit − fees) of the bot's positions closed + /// in the current UTC day, from the venue's history plus the provisional estimates of + /// closes it does not show yet. NaN while unknown (the history of the day not read yet). + /// + public double TodayPnl { get; init; } = double.NaN; - public double TodayPnlPct { get; init; } + /// over the net equity the day started with; NaN while unknown. + public double TodayPnlPct { get; init; } = double.NaN; + + /// True while contains estimates the history has not confirmed. + public bool TodayPnlProvisional { get; init; } + + /// Net equity now minus net equity at 00:00 UTC (realised + change of the open result, cash excluded); NaN while unknown. + public double TodayEquityChange { get; init; } = double.NaN; + + /// Net equity (cash movements excluded) at the start of the UTC day; NaN while unknown. + public double DayStartEquity { get; init; } = double.NaN; + + /// The units closed today: baskets, lone legs, won, lost. + public Encelado.Core.Baskets.History.TodayClosedStats TodayClosed { get; init; } = Encelado.Core.Baskets.History.TodayClosedStats.Empty; + + /// How much of the daily loss budget is used, 0..1; NaN while unknown. + public double DailyLossUsedPct { get; init; } = double.NaN; + + /// The daily-loss rule is hit: no new entries until 00:00 UTC. + public bool DailyLossHit { get; init; } + + /// Closes waiting for the venue's history (their P&L is still an estimate). + public int PendingSettlements { get; init; } public double OpenPnl { get; init; } diff --git a/Encelado/src/Encelado.Engine/Engine/SampleSnapshot.cs b/Encelado/src/Encelado.Engine/Engine/SampleSnapshot.cs index d680980..06fafe5 100644 --- a/Encelado/src/Encelado.Engine/Engine/SampleSnapshot.cs +++ b/Encelado/src/Encelado.Engine/Engine/SampleSnapshot.cs @@ -40,6 +40,12 @@ public static class SampleSnapshot DailyLossPct = 0.03, TodayPnl = 120.5, TodayPnlPct = 0.0011, + TodayPnlProvisional = false, + TodayEquityChange = 70.75, + DayStartEquity = 109_379.5, + TodayClosed = new Encelado.Core.Baskets.History.TodayClosedStats(2, 1, 1, 0), + DailyLossUsedPct = 0, + DailyLossHit = false, OpenPnl = -49.75, OpenPnlPct = -0.00045, AccountOpenPnl = -61.20, diff --git a/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs b/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs index fb5d8f9..f25e269 100644 --- a/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs +++ b/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs @@ -53,6 +53,18 @@ public static class SnapshotJson Num(w, "dailyLossPct", s.DailyLossPct); Num(w, "todayPnl", s.TodayPnl); Num(w, "todayPnlPct", s.TodayPnlPct); + w.WriteBoolean("todayPnlProvisional", s.TodayPnlProvisional); + Num(w, "todayEquityChange", s.TodayEquityChange); + Num(w, "dayStartEquity", s.DayStartEquity); + w.WriteStartObject("todayClosed"); + w.WriteNumber("baskets", s.TodayClosed.Baskets); + w.WriteNumber("won", s.TodayClosed.Won); + w.WriteNumber("lost", s.TodayClosed.Lost); + w.WriteNumber("loneLegs", s.TodayClosed.LoneLegs); + w.WriteEndObject(); + Num(w, "dailyLossUsedPct", s.DailyLossUsedPct); + w.WriteBoolean("dailyLossHit", s.DailyLossHit); + w.WriteNumber("pendingSettlements", s.PendingSettlements); Num(w, "openPnl", s.OpenPnl); Num(w, "openPnlPct", s.OpenPnlPct); Num(w, "accountOpenPnl", s.AccountOpenPnl); diff --git a/Encelado/src/Encelado.Etoro/EtoroBroker.cs b/Encelado/src/Encelado.Etoro/EtoroBroker.cs index 423bd04..acdf3a1 100644 --- a/Encelado/src/Encelado.Etoro/EtoroBroker.cs +++ b/Encelado/src/Encelado.Etoro/EtoroBroker.cs @@ -740,11 +740,17 @@ public sealed class EtoroBroker : IBroker }; } + /// + /// Closes one position and waits for the close order's outcome. The answer never + /// carries the realised result ( is NaN): eToro's + /// close-order info has no profit field, and its proceeds are the cash returned + /// (margin plus profit). The P&L of record comes from the trade history, by position id. + /// public async Task CloseAsync(long positionId, long instrumentId, CancellationToken ct) { if (!SupportsTrading) { - return new CloseOutcome(false, true, 0, 0, 0, DateTime.UtcNow, 0, "sessione in sola lettura: nessuna chiave eToro"); + return new CloseOutcome(false, true, 0, 0, 0, DateTime.UtcNow, double.NaN, "sessione in sola lettura: nessuna chiave eToro") { PositionId = positionId }; } string body = "{\"InstrumentID\":" + instrumentId.ToString(CultureInfo.InvariantCulture) + "}"; @@ -752,7 +758,7 @@ public sealed class EtoroBroker : IBroker if (!r.IsSuccess) { string why = Problem(r); - return new CloseOutcome(false, (int)r.Status is >= 400 and < 500, 0, 0, 0, DateTime.UtcNow, 0, why); + return new CloseOutcome(false, (int)r.Status is >= 400 and < 500, 0, 0, 0, DateTime.UtcNow, double.NaN, why) { PositionId = positionId }; } long orderId; @@ -769,12 +775,12 @@ public sealed class EtoroBroker : IBroker last = await CloseOrderInfoAsync(orderId, ct).ConfigureAwait(false); if (last is { Pending: false }) { - return last; + return last.PositionId > 0 ? last : last with { PositionId = positionId }; } } // Still pending on the venue: the caller reconciles against the position list. - return last ?? new CloseOutcome(false, false, orderId, 0, 0, DateTime.UtcNow, 0, "esito non ancora noto"); + return (last ?? new CloseOutcome(false, false, orderId, 0, 0, DateTime.UtcNow, double.NaN, "esito non ancora noto")) with { PositionId = positionId }; } private async Task CloseOrderInfoAsync(long orderId, CancellationToken ct) @@ -790,7 +796,10 @@ public sealed class EtoroBroker : IBroker int statusId = Json.Int(root, "statusID"); int errorCode = Json.Int(root, "errorCode"); string errorMessage = Json.String(root, "errorMessage"); - double proceeds = Json.Double(root, "proceeds"); + + // "proceeds" = margin released + profit: the cash the close returned, NOT the P&L. + // It is kept for diagnostics only; the realised result comes from the trade history. + double proceeds = Json.Double(root, "proceeds", double.NaN); foreach (JsonElement p in Json.Array(root, "positions")) { @@ -798,12 +807,17 @@ public sealed class EtoroBroker : IBroker if (double.IsFinite(rate) && rate > 0) { DateTime t = Json.Time(p, "occurred"); - return new CloseOutcome(true, false, orderId, rate, Json.Double(p, "units"), t == default ? DateTime.UtcNow : t, proceeds, string.Empty); + return new CloseOutcome(true, false, orderId, rate, Json.Double(p, "units"), t == default ? DateTime.UtcNow : t, double.NaN, string.Empty) + { + PositionId = Json.Long(p, "positionID"), + Proceeds = proceeds, + ConversionRate = Json.Double(p, "conversionRate", double.NaN), + }; } } bool rejected = statusId is 4 or 7 or 8 or 10 || errorCode != 0; - return new CloseOutcome(false, rejected, orderId, 0, 0, DateTime.UtcNow, 0, rejected ? (errorMessage.Length > 0 ? errorMessage : $"stato {statusId}, codice {errorCode}") : string.Empty); + return new CloseOutcome(false, rejected, orderId, 0, 0, DateTime.UtcNow, double.NaN, rejected ? (errorMessage.Length > 0 ? errorMessage : $"stato {statusId}, codice {errorCode}") : string.Empty); } public async Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) @@ -877,11 +891,17 @@ public sealed class EtoroBroker : IBroker return new CostEstimate(markup, spread, fee, overnight, weekend, t == default ? DateTime.UtcNow : t); } + /// + /// The trade history from 's UTC day on (the route filters on + /// the closing time at UTC midnight; its orderId is the opening order, so rows are + /// joined by positionId). excludes the fees. + /// Throws when a page cannot be read: an unreadable history is never "no closes". + /// public async Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) { if (!_options.HasKeys) { - return []; + throw new BrokerException("eToro: nessuna chiave, storico delle chiusure non leggibile"); } List trades = []; @@ -890,7 +910,8 @@ public sealed class EtoroBroker : IBroker EtoroResponse r = await _http.SendAsync(HttpMethod.Get, $"{P.History}?minDate={EtoroHttp.FormatDate(fromUtc)}&page={page}&pageSize=200", null, EtoroQuota.Default, ct).ConfigureAwait(false); if (!r.IsSuccess) { - break; + // An unreadable history is not an empty one: callers must never read "no closes, 0 USD". + throw Error($"storico delle chiusure dal {EtoroHttp.FormatDate(fromUtc)} (pagina {page})", r); } int before = trades.Count; diff --git a/Encelado/tests/Encelado.Tests/BasketTests.cs b/Encelado/tests/Encelado.Tests/BasketTests.cs index deda0a7..8322434 100644 --- a/Encelado/tests/Encelado.Tests/BasketTests.cs +++ b/Encelado/tests/Encelado.Tests/BasketTests.cs @@ -335,7 +335,9 @@ public class LegRiskTests { Events.Add($"close {positionId}"); bool removed = Positions.Remove(positionId); - return Task.FromResult(new CloseOutcome(removed, !removed, _next++, 1.1, 0, DateTime.UtcNow, 0, removed ? string.Empty : "inesistente")); + + // As eToro: the close answer carries no realised result. + return Task.FromResult(new CloseOutcome(removed, !removed, _next++, 1.1, 0, DateTime.UtcNow, double.NaN, removed ? string.Empty : "inesistente") { PositionId = positionId }); } public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true); @@ -415,6 +417,31 @@ public class LegRiskTests ExitOutcome exit = await executor.CloseAsync(ctx, outcome.Position, "test", CancellationToken.None); Assert.True(exit.Ok, exit.Error); Assert.Empty(broker.Positions); + + // No realised result from the venue: the number is the estimate from the exit prices, never zero by default. + Assert.False(exit.PnlFinal); + Assert.Equal(outcome.Position.NetPnlUsd(exit.ExitPriceA, exit.ExitPriceB, ctx.Mid), exit.RealizedPnlUsd, 9); + Assert.Equal(2, exit.Closes.Count); + } + + /// (13) The leg undone after a rejected leg B comes back with its close, so its realised result can be settled. + [Fact] + public async Task AnUnwoundLegAIsReportedWithItsClose() + { + (BasketContext ctx, BasketDecision d, BasketStrategyConfig cfg) = Scenario(); + RejectingBroker broker = new() { RejectFromOrder = 2 }; + BasketExecutor executor = new(broker, cfg, ctx.Mid, static _ => { }); + + EntryOutcome outcome = await executor.OpenAsync(ctx, d, cfg.Effective(), CancellationToken.None); + + Assert.True(outcome.Unwound, outcome.Error); + Assert.NotNull(outcome.UnwindClose); + Assert.True(outcome.UnwindClose!.Closed); + Assert.Equal(1, outcome.UnwindClose.PositionId); + Assert.True(double.IsNaN(outcome.UnwindClose.RealizedPnl)); + Assert.NotNull(outcome.UnwoundLeg); + Assert.Equal(1, outcome.UnwoundLeg!.PositionId); + Assert.Equal("EURUSD", outcome.UnwoundLeg.Symbol); } [Fact] diff --git a/Encelado/tests/Encelado.Tests/CorrectionTests.cs b/Encelado/tests/Encelado.Tests/CorrectionTests.cs new file mode 100644 index 0000000..61801d8 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/CorrectionTests.cs @@ -0,0 +1,621 @@ +using System.Text.Json; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; +using Encelado.Core.Baskets.Learning; +using Encelado.Core.Broker; +using Encelado.Core.Notifications; +using Encelado.Engine.Baskets; + +namespace Encelado.Tests; + +/// Shared scenery: rows, orders, ingresso lines and raw ledger lines with chosen timestamps. +internal static class CorrectionScenery +{ + public const string B1 = "B20260929091500-EURUSDUSDCAD"; + + public static BasketOutcomeRow Row(string basketId, string basket, string exit, double entryZ, string opened, string closed, double net, string motivazione = "take-profit | ingresso: z −2,2", int adds = 0, bool buyCross = true, string mode = "Demo") => + new(basketId, "run50", basket, mode, "MODERATE", DemoHistory.Utc(opened), DemoHistory.Utc(closed), buyCross, entryZ, 0.1, net, net, 3, 2.5, 3, 0.2, adds, 12, exit, 149_000, double.NaN, motivazione); + + /// The row 5.0 wrote for the EURUSD/USDCAD basket of 2026-09-29: the proceeds (17 908.25) as the P&L. + public static BasketOutcomeRow ProceedsRow() => Row(B1, "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T09:15:00Z", "2026-09-29T21:15:28.053Z", 17_908.25); + + public static OrderRecord Order(string ts, string basketId, string basket, string symbol, bool isBuy, OrderLeg leg, long positionId, string clientRef, string motivazione = "x") => + new(DemoHistory.Utc(ts), "run50", "Demo", basket, basketId, symbol, DemoHistory.InstrumentOf(symbol), isBuy, leg, 10_000, 10_000, 1.1, 1.1, 0, + "Filled", 3, OrderResolution.Filled, 800 + positionId, positionId, clientRef, 0, "risolto", motivazione); + + /// Appends a line to a ledger file the way another writer would (the ledger shares its files). + public static void AppendRaw(string path, string line) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using FileStream stream = new(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + using StreamWriter w = new(stream); + w.WriteLine(line); + } + + public static byte[] Bytes(string path) + { + using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using MemoryStream ms = new(); + stream.CopyTo(ms); + return ms.ToArray(); + } + + public static BasketContext Context(DateTime t, double lastOutcomes = double.NaN) + { + Instrument eurusd = new(1, "EURUSD", "EUR/USD", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1], true, true, 0, 50, ""); + Instrument usdcad = new(4, "USDCAD", "USD/CAD", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1], true, true, 0, 50, ""); + return new BasketContext + { + TimeUtc = t, + BasketId = "EURUSD/USDCAD", + Name = "EURUSD/USDCAD", + Cross = SyntheticCross.Derive("EURUSD", "USDCAD"), + A = new SymbolSeries(eurusd, TimeSpan.FromMinutes(15)), + B = new SymbolSeries(usdcad, TimeSpan.FromMinutes(15)), + Equity = 149_000, + PipValueUsdA = 1, + PipValueUsdB = 1, + UsdPerQuoteA = 1, + UsdPerQuoteB = 1, + Mid = static _ => null, + LastOutcomes = lastOutcomes, + }; + } + + /// The ingresso line of a basket: the features the dataset joins with the row's label. + public static void Ingresso(Ledger ledger, string basketId, DateTime t, double lastOutcomes = double.NaN) + { + BasketDecision d = new(DecisionKind.Enter, true, new SizingResult(true, 55_000, 117_000, 62_000, 117_000, 150, 2, "ok"), ["enter"], "entro", new BasketEvaluation { Z = -2.2, RhoW = -0.8 }, null); + ledger.Decision("run50", "Demo", "MODERATE", "h", Context(t, lastOutcomes), d, "ingresso", basketId, "eseguito: A @ 1.13369 (slippage +0.0 pip), B @ 1.41959 (slippage +0.0 pip), latenza 120 ms"); + } +} + +/// A notifier that keeps what it was given. +internal sealed class RecordingNotifier : INotifier +{ + public readonly List<(NotificationKind Kind, string Title, string Text)> Messages = []; + + public string Status => "test"; + + public void Notify(NotificationKind kind, string title, string text) => Messages.Add((kind, title, text)); +} + +/// A temporary data folder, removed afterwards. +public abstract class TempFolderTests : IDisposable +{ + protected TempFolderTests() + { + Root = Path.Combine(Path.GetTempPath(), $"encelado-51-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Root); + } + + protected string Root { get; } + + protected string LedgerDir => Path.Combine(Root, "ledger"); + + protected string KnowledgeDir => Path.Combine(Root, "knowledge"); + + public void Dispose() + { + try + { + Directory.Delete(Root, recursive: true); + } + catch (IOException) + { + // A file still held by a finalizer: the temp folder is cleaned by the OS. + } + + GC.SuppressFinalize(this); + } +} + +/// (21-24) Corrections are new lines; the corrected reader applies them; unverified rows teach nothing and are not summed. +public sealed class LedgerCorrectionTests : TempFolderTests +{ + private static readonly long[] Ids = [3605914106, 3605914105]; + + [Fact] + public void APnlCorrectionIsAnAppendedLineAndBasketsCsvIsUntouched() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.ProceedsRow()); + ledger.Note("run50", "skip", string.Empty, "una riga qualsiasi"); + byte[] before = CorrectionScenery.Bytes(ledger.BasketsPath); + int lines = ledger.ReadDecisionLines().Count; + + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, Ids, "P&L registrato = proceeds della chiusura"); + + Assert.Equal(before, CorrectionScenery.Bytes(ledger.BasketsPath)); + List after = ledger.ReadDecisionLines(); + Assert.Equal(lines + 1, after.Count); + string line = after[^1]; + Assert.Contains("\"evento\":\"correzione\"", line, StringComparison.Ordinal); + Assert.Contains("\"tipo\":\"pnl_realizzato\"", line, StringComparison.Ordinal); + Assert.Contains("\"riga\":\"B20260929091500-EURUSDUSDCAD|2026-09-29T21:15:28.0530000Z\"", line, StringComparison.Ordinal); + Assert.Contains("\"pnl_net_registrato\":17908.25", line, StringComparison.Ordinal); + Assert.Contains("\"pnl_net_corretto\":-38.79", line, StringComparison.Ordinal); + Assert.Contains("\"label_corretta\":0", line, StringComparison.Ordinal); + Assert.Contains("\"verificata\":true", line, StringComparison.Ordinal); + Assert.Contains("\"position_ids\":[3605914106,3605914105]", line, StringComparison.Ordinal); + } + + [Fact] + public void TheCorrectedReaderAppliesTheNewestCorrectionAndTheLabelFollows() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.ProceedsRow()); + BasketOutcomeRow stored = ledger.ReadBaskets()[0]; + Assert.Equal(1, stored.Label); + + ledger.PnlCorrection("run51", stored, -38.79, -38.79, true, Ids, "prima correzione"); + BasketOutcomeRow first = Assert.Single(ledger.ReadBasketsCorrected()); + Assert.Equal(-38.79, first.PnlNetUsd, 2); + Assert.Equal(0, first.Label); + Assert.True(first.Corrected); + Assert.True(first.HasLabel); + + ledger.PnlCorrection("run52", stored, 5.0, 4.5, true, Ids, "correzione più recente"); + BasketOutcomeRow newest = Assert.Single(ledger.ReadBasketsCorrected()); + Assert.Equal(4.5, newest.PnlNetUsd, 2); + Assert.Equal(5.0, newest.PnlGrossUsd, 2); + Assert.Equal(1, newest.Label); + + // The file never changed. + Assert.Equal(17_908.25, ledger.ReadBaskets()[0].PnlNetUsd, 2); + } + + [Fact] + public void CorrectionsInARotatedMonthAreHonoured() + { + using (Ledger ledger = new(LedgerDir)) + { + ledger.Basket(CorrectionScenery.ProceedsRow()); + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, Ids, "correzione"); + } + + File.Move(Path.Combine(LedgerDir, "decisions.jsonl"), Path.Combine(LedgerDir, "decisions_202609.jsonl")); + using Ledger again = new(LedgerDir); + again.Note("run52", "skip", string.Empty, "il mese nuovo"); + + Assert.Single(again.ReadPnlCorrections()); + Assert.Equal(-38.79, Assert.Single(again.ReadBasketsCorrected()).PnlNetUsd, 2); + Assert.Equal(-38.79, Assert.Single(Ledger.ReadBasketsCorrected(LedgerDir)).PnlNetUsd, 2); + } + + [Fact] + public void UnverifiedRowsHaveNoLabelAndReportsSkipThem() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.Row("V1", "EURUSD/USDCAD", "tp_pips", -2.1, "2026-09-29T09:00:00Z", "2026-09-29T10:00:00Z", 5, "tp | P&L: storico eToro (netProfit − fees)")); + ledger.Basket(CorrectionScenery.Row("V2", "EURUSD/USDCAD", "tp_pips", -2.1, "2026-09-29T11:00:00Z", "2026-09-29T12:00:00Z", 3, "tp | P&L: stima dai prezzi di chiusura")); + ledger.Basket(CorrectionScenery.Row("V3", "EURUSD/USDCAD", "stop_z", -2.1, "2026-09-29T13:00:00Z", "2026-09-29T14:00:00Z", 7_000)); + ledger.PnlCorrection("run51", ledger.ReadBaskets().Single(static r => r.BasketId == "V3"), double.NaN, double.NaN, false, [], "posizioni non ritrovate"); + foreach (string id in (string[])["V1", "V2", "V3"]) + { + CorrectionScenery.Ingresso(ledger, id, new DateTime(2026, 9, 29, 9, 0, 0, DateTimeKind.Utc)); + } + + List rows = ledger.ReadBasketsCorrected(); + Assert.True(rows.Single(static r => r.BasketId == "V1").HasLabel); + Assert.True(rows.Single(static r => r.BasketId == "V2").Unverified); + BasketOutcomeRow v3 = rows.Single(static r => r.BasketId == "V3"); + Assert.True(v3.Unverified); + Assert.True(double.IsNaN(v3.PnlNetUsd)); + + string text = TelegramReports.Period("oggi", rows, 0); + Assert.Contains("oggi: 1 basket chiusi", text, StringComparison.Ordinal); + Assert.Contains("netto +5.00 USD", text, StringComparison.Ordinal); + Assert.Contains("2 esclusi", text, StringComparison.Ordinal); + Assert.DoesNotContain("NaN", text, StringComparison.Ordinal); + + using LearningState learning = new(Root, KnowledgeDir, ledger, BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)); + Assert.Equal(["V1"], learning.BuildDataset().Select(static r => r.BasketId)); + } +} + +/// (25-27) The learning stack reads the corrected labels, masks the contaminated feature, retires the models once. +public sealed class LearningCorrectionTests : TempFolderTests +{ + private static BasketStrategyConfig Cfg() => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + + [Fact] + public void BuildDatasetUsesCorrectedLabels() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.ProceedsRow()); + CorrectionScenery.Ingresso(ledger, CorrectionScenery.B1, new DateTime(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc)); + using LearningState learning = new(Root, KnowledgeDir, ledger, Cfg()); + Assert.Equal(1, Assert.Single(learning.BuildDataset()).Label); + + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, [3605914106, 3605914105], "proceeds"); + + LabelledBasket row = Assert.Single(learning.BuildDataset()); + Assert.Equal(0, row.Label); + Assert.Equal(-38.79, row.PnlNetUsd, 2); + } + + [Fact] + public void LastOutcomesIsMaskedBeforeTheReliabilityMark() + { + using Ledger ledger = new(LedgerDir); + DateTime before = new(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc); + DateTime after = new(2026, 9, 30, 10, 0, 0, DateTimeKind.Utc); + ledger.Basket(CorrectionScenery.Row("M1", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T09:15:00Z", "2026-09-29T12:00:00Z", -3)); + ledger.Basket(CorrectionScenery.Row("M2", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-30T10:00:00Z", "2026-09-30T12:00:00Z", 4)); + CorrectionScenery.Ingresso(ledger, "M1", before, lastOutcomes: 1.0); + CorrectionScenery.Ingresso(ledger, "M2", after, lastOutcomes: 1.0); + ledger.FeatureUnreliable("run51", "lastNOutcomes", LearningFeatures.LastOutcomesIndex, new DateTime(2026, 9, 30, 0, 0, 0, DateTimeKind.Utc), "etichette dai proceeds"); + + using LearningState learning = new(Root, KnowledgeDir, ledger, Cfg()); + List rows = learning.BuildDataset(); + + Assert.Equal(26, LearningFeatures.LastOutcomesIndex); + Assert.Equal(0.5, rows.Single(static r => r.BasketId == "M1").Features[LearningFeatures.LastOutcomesIndex]); + Assert.Equal(1.0, rows.Single(static r => r.BasketId == "M2").Features[LearningFeatures.LastOutcomesIndex]); + } + + [Fact] + public void RetireAndReplayCopiesTheModelsAsideResetsTheBanditAndRunsOnce() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.ProceedsRow()); + CorrectionScenery.Ingresso(ledger, CorrectionScenery.B1, new DateTime(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc)); + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, [3605914106, 3605914105], "proceeds"); + string fresh = new ThompsonBandit(3, 42).ToJson(); + DateTime now = new(2026, 9, 30, 8, 0, 0, DateTimeKind.Utc); + + using (LearningState learning = new(Root, KnowledgeDir, ledger, Cfg())) + { + // What 5.0 did: a basket "won" on its proceeds and the models learnt it. + learning.RememberEntry("X", new double[LearningFeatures.Count]); + learning.Observe("X", 1, 1, PresetName.Moderate); + Assert.NotEqual(fresh, learning.BanditJson); + Assert.False(learning.LabelsFixed); + + Assert.True(learning.RetireAndReplay(now, "etichette dai proceeds")); + + Assert.True(learning.LabelsFixed); + Assert.Equal(fresh, learning.BanditJson); + Assert.Equal(1, learning.LogisticSeen); // replayed on the one corrected basket + string aside = Assert.Single(Directory.GetDirectories(Path.Combine(Root, "models", "ritirati"))); + Assert.EndsWith("20260930-080000-etichette-proceeds", aside, StringComparison.Ordinal); + Assert.True(File.Exists(Path.Combine(aside, "logreg_current.json"))); + Assert.True(File.Exists(Path.Combine(aside, "bandit.json"))); + Assert.True(File.Exists(Path.Combine(aside, "learning_state.json"))); + + Assert.False(learning.RetireAndReplay(now.AddMinutes(5), "di nuovo")); + Assert.Single(Directory.GetDirectories(Path.Combine(Root, "models", "ritirati"))); + } + + string[] registry = File.ReadAllLines(Path.Combine(KnowledgeDir, "models_registry.csv")); + Assert.Single(registry, static l => l.Contains(";ritirato;", StringComparison.Ordinal)); + + using LearningState again = new(Root, KnowledgeDir, ledger, Cfg()); + Assert.True(again.LabelsFixed); + Assert.Equal(fresh, again.BanditJson); + } +} + +/// (28-31) The backfill of 4.0.0–5.0.0: proceeds rows corrected by position id, the rest left alone, idempotent, nothing written without the history. +public sealed class RealizedBackfillTests : TempFolderTests +{ + private const string B2 = "B20260929181500-EURUSDUSDCHF"; + private const string B9 = "B20260929120000-AUDUSDUSDCAD"; + private const string B10 = "B20260929154500-NZDUSDEURNZD"; + + /// Five rows as 5.0 (and 4.0) left them: a proceeds basket, a broker close already right, a proceeds orphan, a basket without traces, a 4.0 basket without orders. + private Ledger Seed() + { + // Lines of decisions.jsonl with their own timestamps, written before the ledger opens the file. + string decisions = Path.Combine(LedgerDir, "decisions.jsonl"); + CorrectionScenery.AppendRaw(decisions, """{"ts":"2026-09-29T15:15:25.0000000Z","run_id":"run50","evento":"orfana_chiusa","basket_id":"","basket":"NZDUSD/EURNZD","position_id":3606352134,"strumento":"NZDUSD","pnl":7735.0,"exit_reason":"orphan_closed","motivazione":"adottata alla riconciliazione e chiusa: +7735.00 USD"}"""); + CorrectionScenery.AppendRaw(decisions, """{"ts":"2026-09-29T15:45:00.0000000Z","run_id":"run40","config_hash":"h","basket":"NZDUSD/EURNZD","basket_id":"B20260929154500-NZDUSDEURNZD","evento":"ingresso","decision":"Enter","buy_cross":true,"z":-2.4,"motivazione":"entro — eseguito: A @ 0.56327 (slippage +0.0 pip), B @ 2.01195 (slippage +0.1 pip), latenza 1900 ms"}"""); + + Ledger ledger = new(LedgerDir); + bool buyNzd = SyntheticCross.Derive("NZDUSD", "EURNZD").Legs(true) == (true, true); + ledger.Basket(CorrectionScenery.ProceedsRow()); + ledger.Basket(CorrectionScenery.Row(B2, "EURUSD/USDCHF", "closed_by_broker", 2.3, "2026-09-29T18:15:00Z", "2026-09-29T21:06:13Z", -232.77, "chiuso dal broker")); + ledger.Basket(CorrectionScenery.Row(string.Empty, "NZDUSD/EURNZD", "orphan_closed", double.NaN, "2026-09-29T15:15:02.707Z", "2026-09-29T15:15:24.44Z", 7_735, + "gamba singola long 137181.16 NZDUSD @ 0.56345 chiusa @ 0.56349: adottata alla riconciliazione e chiusa")); + ledger.Basket(CorrectionScenery.Row(B9, "AUDUSD/USDCAD", "tp_pips", 2.0, "2026-09-29T12:00:00Z", "2026-09-29T14:00:00Z", 9_000)); + ledger.Basket(CorrectionScenery.Row(B10, "NZDUSD/EURNZD", "tp_pips", -2.4, "2026-09-29T15:45:00Z", "2026-09-29T21:30:24Z", 17_963.60, "take-profit", buyCross: buyNzd)); + + ledger.Order(CorrectionScenery.Order("2026-09-29T09:15:58Z", CorrectionScenery.B1, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.A, 3605914106, "a1")); + ledger.Order(CorrectionScenery.Order("2026-09-29T09:15:59Z", CorrectionScenery.B1, "EURUSD/USDCAD", "USDCAD", true, OrderLeg.B, 3605914105, "b1")); + ledger.Order(CorrectionScenery.Order("2026-09-29T18:15:01Z", B2, "EURUSD/USDCHF", "EURUSD", false, OrderLeg.A, 3606542492, "a2")); + ledger.Order(CorrectionScenery.Order("2026-09-29T18:15:02Z", B2, "EURUSD/USDCHF", "USDCHF", false, OrderLeg.B, 3606542494, "b2")); + return ledger; + } + + private static RealizedBackfill Backfill(Ledger ledger, Func>>? history = null) => + new(ledger, history ?? ((_, _) => Task.FromResult>(DemoHistory.All())), "run51", "Demo", DemoHistory.InstrumentOf); + + private static readonly DateTime Now = new(2026, 9, 30, 8, 0, 0, DateTimeKind.Utc); + + [Fact] + public async Task ProceedsRowsAreCorrectedAndTheRestIsLeftAlone() + { + using Ledger ledger = Seed(); + + BackfillReport report = await Backfill(ledger).RunAsync(Now, CancellationToken.None); + + Assert.Equal(new BackfillReport(5, 1, 3, 1), report); + List rows = ledger.ReadBasketsCorrected(); + BasketOutcomeRow b1 = rows.Single(static r => r.BasketId == CorrectionScenery.B1); + Assert.Equal(-38.79, b1.PnlNetUsd, 2); + Assert.Equal(0, b1.Label); + Assert.True(b1.Corrected); + BasketOutcomeRow b2 = rows.Single(static r => r.BasketId == B2); + Assert.False(b2.Corrected); + Assert.Equal(-232.77, b2.PnlNetUsd, 2); + Assert.Equal(5.49, rows.Single(static r => r.ExitReason == "orphan_closed").PnlNetUsd, 2); + Assert.Equal(32.0 - 205.86, rows.Single(static r => r.BasketId == B10).PnlNetUsd, 2); + BasketOutcomeRow b9 = rows.Single(static r => r.BasketId == B9); + Assert.True(b9.Unverified); + Assert.True(double.IsNaN(b9.PnlNetUsd)); + + Assert.Equal(4, ledger.ReadPnlCorrections().Count); + Assert.Contains(ledger.ReadDecisionLines(), static l => l.Contains("\"evento\":\"verifica_realizzato\"", StringComparison.Ordinal)); + Assert.Equal(new DateTime(2026, 9, 29, 21, 30, 24, DateTimeKind.Utc), ledger.ReadBackfillWatermark()); + Assert.True(RealizedBackfill.LegacyRowsWereCorrected(ledger)); + + // baskets.csv still says what 5.0 wrote. + Assert.Equal(17_908.25, ledger.ReadBaskets().Single(static r => r.BasketId == CorrectionScenery.B1).PnlNetUsd, 2); + } + + [Fact] + public async Task TheBackfillIsIdempotent() + { + using Ledger ledger = Seed(); + await Backfill(ledger).RunAsync(Now, CancellationToken.None); + int lines = ledger.ReadDecisionLines().Count; + + BackfillReport second = await Backfill(ledger).RunAsync(Now.AddHours(1), CancellationToken.None); + + Assert.Equal(0, second.Corrected); + Assert.Equal(lines, ledger.ReadDecisionLines().Count); + } + + [Fact] + public void AnUnwoundAddIsNotAttributedToTheBasket() + { + const string b3 = "B20260929100000-EURUSDUSDCAD"; + List orders = + [ + CorrectionScenery.Order("2026-09-29T10:00:01Z", b3, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.A, 1001, "a"), + CorrectionScenery.Order("2026-09-29T10:00:02Z", b3, "EURUSD/USDCAD", "USDCAD", true, OrderLeg.B, 1002, "b"), + + // 5.1: the unwind names the add's position. + CorrectionScenery.Order("2026-09-29T10:15:01Z", b3, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.Add, 1003, "add1"), + CorrectionScenery.Order("2026-09-29T10:15:03Z", b3, "EURUSD/USDCAD", "EURUSD", false, OrderLeg.Unwind, 1003, "undo1", "leg_risk_unwind dell'aggiunta"), + + // 5.0: the unwind has no position; the same symbol within two minutes, "dell'aggiunta". + CorrectionScenery.Order("2026-09-29T10:30:01Z", b3, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.Add, 1004, "add2"), + CorrectionScenery.Order("2026-09-29T10:30:04Z", b3, "EURUSD/USDCAD", "EURUSD", false, OrderLeg.Unwind, 0, "undo2", "leg_risk_unwind dell'aggiunta"), + + // An add that stayed: it is the basket's. + CorrectionScenery.Order("2026-09-29T10:45:01Z", b3, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.Add, 1005, "add3"), + CorrectionScenery.Order("2026-09-29T10:45:02Z", b3, "EURUSD/USDCAD", "USDCAD", true, OrderLeg.Add, 1006, "add4"), + ]; + PositionMap map = PositionMap.Build(orders, [], []); + BasketOutcomeRow row = CorrectionScenery.Row(b3, "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T10:00:00Z", "2026-09-29T12:00:00Z", 900, adds: 1); + + Assert.Equal([1001L, 1002L, 1005L, 1006L], map.IdsOf(row, [], DemoHistory.InstrumentOf).Order()); + + // A 5.1 row names its positions: those are taken as they are. + BasketOutcomeRow named = row with { Motivazione = "tp | posizioni: 1001 1002" }; + Assert.Equal([1001L, 1002L], map.IdsOf(named, [], DemoHistory.InstrumentOf)); + } + + [Fact] + public void ALoneLegIsFoundByItsNoteByItsLegAOrByWhatItsMotivationSays() + { + DateTime t = new(2026, 9, 29, 10, 0, 0, DateTimeKind.Utc); + List notes = [new(t.AddSeconds(2), "leg_risk_unwind", "B5", 2001, string.Empty, "leg_risk_unwind")]; + List orders = [CorrectionScenery.Order("2026-09-29T11:00:00Z", "B6", "EURAUD/AUDCAD", "EURAUD", false, OrderLeg.A, 2002, "a6")]; + PositionMap map = PositionMap.Build(orders, notes, []); + List history = + [ + DemoHistory.Trade(2003, 12, false, 17_420.9, 1.61043, 1.6094, "2026-09-29T12:00:03Z", "2026-09-29T12:30:00Z", 10.3), + DemoHistory.Trade(2004, 12, false, 5_000, 1.61, 1.6094, "2026-09-29T12:00:03Z", "2026-09-29T12:30:00Z", 3.1), + DemoHistory.Trade(2005, 12, false, 5_000, 1.61, 1.6094, "2026-09-29T12:00:05Z", "2026-09-29T12:30:01Z", 3.1), + ]; + + // 1. The note written when the leg was closed. + BasketOutcomeRow unwound = CorrectionScenery.Row("B5", "EURUSD/USDCHF", "leg_risk_unwind", double.NaN, "2026-09-29T09:59:50Z", "2026-09-29T10:00:00Z", 900, + "gamba singola long 10000 EURUSD @ 1.1001 chiusa @ 1.1: segnale decaduto"); + Assert.Equal([2001L], map.IdsOf(unwound, history, DemoHistory.InstrumentOf)); + + // 2. Leg A of the attempt (a pending leg closed by the kill-switch, no note). + BasketOutcomeRow pending = CorrectionScenery.Row("B6", "EURAUD/AUDCAD", "kill_switch", double.NaN, "2026-09-29T11:00:00Z", "2026-09-29T11:20:00Z", 800, + "gamba singola short 17420.9 EURAUD @ 1.61043 chiusa @ 1.6094: kill-switch"); + Assert.Equal([2002L], map.IdsOf(pending, history, DemoHistory.InstrumentOf)); + + // 3. What the motivation says, matched on the history: one position fits. + BasketOutcomeRow orphan = CorrectionScenery.Row(string.Empty, "EURAUD/AUDCAD", "orphan_closed", double.NaN, "2026-09-29T12:00:03Z", "2026-09-29T12:30:00Z", 700, + "gamba singola short 17420.9 EURAUD @ 1.61043 chiusa @ 1.6094: adottata alla riconciliazione e chiusa"); + Assert.Equal([2003L], map.IdsOf(orphan, history, DemoHistory.InstrumentOf)); + + // Two positions fit: nothing is guessed. + BasketOutcomeRow ambiguous = CorrectionScenery.Row(string.Empty, "EURAUD/AUDCAD", "orphan_closed", double.NaN, "2026-09-29T12:00:03Z", "2026-09-29T12:30:00Z", 700, + "gamba singola short 5000 EURAUD @ 1.61 chiusa @ 1.6094: adottata alla riconciliazione e chiusa"); + Assert.Empty(map.IdsOf(ambiguous, history, DemoHistory.InstrumentOf)); + } + + [Theory] + [InlineData("Demo", "Demo", true)] + [InlineData("DemoAuto", "Demo", true)] + [InlineData("DemoApprove", "Demo", true)] + [InlineData("Paper", "Demo", false)] + [InlineData("Live", "Demo", false)] + [InlineData("Demo", "Live", false)] + [InlineData("Live", "Live", true)] + public void OnlyTheRowsOfTheAccountInUseAreVerified(string rowMode, string mode, bool expected) => + Assert.Equal(expected, RealizedBackfill.SameAccount(rowMode, mode)); + + [Fact] + public async Task AHistoryFailureWritesNothing() + { + using Ledger ledger = Seed(); + int lines = ledger.ReadDecisionLines().Count; + + await Assert.ThrowsAsync(() => Backfill(ledger, static (_, _) => throw new BrokerException("eToro, storico: HTTP 500", 500)).RunAsync(Now, CancellationToken.None)); + + Assert.Equal(lines, ledger.ReadDecisionLines().Count); + Assert.Empty(ledger.ReadPnlCorrections()); + Assert.False(RealizedBackfill.LegacyRowsWereCorrected(ledger)); + } +} + +/// (32-34) The settlement queue: it survives a restart, writes one row with the venue's number and teaches once; past the timeout it writes the estimate, flagged, and teaches nothing. +public sealed class SettlementTests : TempFolderTests +{ + private static readonly long[] Ids = [3605914106, 3605914105]; + + private static PendingSettlement Pending(double estimate = 12.34) + { + BasketOutcomeRow row = CorrectionScenery.Row(CorrectionScenery.B1, "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T09:15:00Z", "2026-09-29T21:15:28.053Z", estimate, + "take-profit | ingresso: z −2,2 | posizioni: 3605914106 3605914105"); + return new PendingSettlement(PnlCorrectionRecord.KeyOf(row), row, Ids, estimate, row.ClosedUtc, true, 2, "Basket chiuso: EURUSD/USDCAD", "+1.6 pip, 48 barre, motivo tp_pips"); + } + + [Fact] + public void APendingSettlementSurvivesARestart() + { + SettlementQueue queue = new(); + BasketOutcomeRow lone = CorrectionScenery.Row(string.Empty, "NZDUSD/EURNZD", "orphan_closed", double.NaN, "2026-09-29T15:15:02.707Z", "2026-09-29T15:15:24.44Z", double.NaN, + "gamba singola long 137181.16 NZDUSD @ 0.56345 chiusa @ 0: adottata | posizioni: 3606352134"); + Assert.True(queue.Add(Pending())); + Assert.True(queue.Add(new PendingSettlement(PnlCorrectionRecord.KeyOf(lone), lone, [3606352134], double.NaN, lone.ClosedUtc, false, 0, string.Empty, string.Empty))); + Assert.False(queue.Add(Pending())); + + using MemoryStream ms = new(); + using (Utf8JsonWriter w = new(ms)) + { + w.WriteStartObject(); + queue.Write(w, "pendingSettlements"); + w.WriteEndObject(); + } + + using JsonDocument doc = JsonDocument.Parse(ms.ToArray()); + SettlementQueue restored = new(); + Assert.Equal(2, restored.Load(doc.RootElement.GetProperty("pendingSettlements"))); + + PendingSettlement basket = restored.Items[0]; + Assert.Equal(Pending().Key, basket.Key); + Assert.Equal(Ids, basket.Ids); + Assert.Equal(12.34, basket.Estimate, 9); + Assert.Equal(Pending().ClosedUtc, basket.ClosedUtc); + Assert.True(basket.Learn); + Assert.Equal(2, basket.VolContext); + Assert.Equal("Basket chiuso: EURUSD/USDCAD", basket.Title); + Assert.Equal(CorrectionScenery.B1, basket.Row.BasketId); + Assert.Equal(-2.2, basket.Row.EntryZ, 9); + Assert.Equal(PnlCorrectionRecord.KeyOf(Pending().Row), PnlCorrectionRecord.KeyOf(basket.Row)); + + PendingSettlement orphan = restored.Items[1]; + Assert.True(orphan.IsLoneLeg); + Assert.True(double.IsNaN(orphan.Estimate)); + Assert.Equal([3606352134L], orphan.Ids); + Assert.True(restored.Contains(3606352134)); + Assert.Equal(DemoHistory.Utc("2026-09-29T15:15:24.44Z"), restored.OldestClosedUtc); + + // A row already in baskets.csv (stopped between the row and the state) is not settled twice. + Assert.Equal(1, restored.RemoveWritten(new HashSet(StringComparer.Ordinal) { PnlCorrectionRecord.KeyOf(Pending().Row) })); + Assert.Single(restored.Items); + Assert.True(restored.Items[0].IsLoneLeg); + } + + [Fact] + public void ASettlementWritesOneRowWithTheVenueNumberAndTeachesOnce() + { + using Ledger ledger = new(LedgerDir); + List taught = []; + RecordingNotifier notifier = new(); + Settlements desk = new(ledger, "run51", notifier, taught.Add); + PendingSettlement pending = Pending(); + desk.Enqueue(pending); + + // The history lags the close: nothing is written yet. + Assert.Empty(desk.Apply([DemoHistory.EurNzdLong], pending.ClosedUtc.AddSeconds(10))); + Assert.Empty(ledger.ReadBaskets()); + Assert.Equal(TimeSpan.FromSeconds(5), desk.Queue.NextCheckIn(pending.ClosedUtc.AddSeconds(10))); + + SettledOutcome settled = Assert.Single(desk.Apply(DemoHistory.All(), pending.ClosedUtc.AddSeconds(30))); + + Assert.Equal(SettlementSource.Venue, settled.Source); + BasketOutcomeRow row = Assert.Single(ledger.ReadBaskets()); + Assert.Equal(-38.79, row.PnlNetUsd, 2); + Assert.Equal(-38.79, row.PnlGrossUsd, 2); + Assert.Equal(0, row.Label); + Assert.Contains(BasketCorrections.VenueMarker, row.Motivazione, StringComparison.Ordinal); + Assert.Contains("posizioni: 3605914106 3605914105", row.Motivazione, StringComparison.Ordinal); + SettledOutcome lesson = Assert.Single(taught); + Assert.Equal(0, lesson.Row.Label); + Assert.Equal(2, lesson.Pending.VolContext); + (_, string title, string text) = Assert.Single(notifier.Messages); + Assert.Equal("Basket chiuso: EURUSD/USDCAD", title); + Assert.Contains("netto -38.79 USD (storico eToro)", text, StringComparison.Ordinal); + Assert.Contains(ledger.ReadDecisionLines(), static l => l.Contains("\"evento\":\"realizzato\"", StringComparison.Ordinal) && l.Contains("\"pnl_netto\":-38.79", StringComparison.Ordinal)); + + // Settled once: a later reading writes nothing more and teaches nothing more. + Assert.Empty(desk.Apply(DemoHistory.All(), pending.ClosedUtc.AddMinutes(2))); + Assert.Single(ledger.ReadBaskets()); + Assert.Single(taught); + Assert.Equal(TimeSpan.FromMinutes(5), desk.Queue.NextCheckIn(pending.ClosedUtc.AddMinutes(2))); + } + + [Fact] + public void AfterTheTimeoutTheEstimateIsWrittenFlaggedAndNeverTaught() + { + using Ledger ledger = new(LedgerDir); + List taught = []; + RecordingNotifier notifier = new(); + Settlements desk = new(ledger, "run51", notifier, taught.Add); + PendingSettlement pending = Pending(); + desk.Enqueue(pending); + + Assert.Empty(desk.Apply([], pending.ClosedUtc.AddMinutes(29))); + SettledOutcome settled = Assert.Single(desk.Apply([], pending.ClosedUtc.AddMinutes(31))); + + Assert.Equal(SettlementSource.Estimate, settled.Source); + BasketOutcomeRow row = Assert.Single(ledger.ReadBaskets()); + Assert.Equal(12.34, row.PnlNetUsd, 2); + Assert.Contains(BasketCorrections.EstimateMarker, row.Motivazione, StringComparison.Ordinal); + Assert.Empty(taught); + Assert.True(Assert.Single(ledger.ReadBasketsCorrected()).Unverified); + Assert.Contains("(stima dai prezzi di chiusura)", Assert.Single(notifier.Messages).Text, StringComparison.Ordinal); + } +} + +/// (36) The kill-switch sums only the results it knows and counts the others. +public class KillSwitchPnlTests +{ + [Fact] + public async Task KillSwitchSumsOnlyKnownPnl() + { + List targets = + [ + new(1, 1, "EURUSD", true, 10_000, "EURUSD/USDCHF", "basket"), + new(2, 6, "USDCHF", true, 9_000, "EURUSD/USDCHF", "basket"), + new(3, 12, "EURAUD", false, 17_420, "EURAUD/AUDCAD", "orfana-bot"), + ]; + static Task Closer(FlattenTarget t, CancellationToken ct) => + Task.FromResult(new CloseOutcome(true, false, 50 + t.PositionId, 1.1, t.Units, DateTime.UtcNow, t.PositionId switch { 1 => 2.5, 2 => double.NaN, _ => -1.0 }, string.Empty)); + + FlattenCloses closes = await FlattenProcedure.CloseTargetsAsync(targets, Closer, static _ => { }, CancellationToken.None); + + Assert.Equal(3, closes.Closed.Count); + Assert.Equal(1.5, closes.RealizedKnown, 9); + Assert.Equal(1, closes.UnknownPnl); + Assert.Contains("1 da confermare", closes.Describe(), StringComparison.Ordinal); + Assert.Equal([1L, 2L, 3L], closes.Outcomes.Select(static o => o.Close.PositionId)); + + FlattenProcedure procedure = new(new SlowVenue(), new OrderTracker(string.Empty), static _ => { }) { PollInterval = TimeSpan.FromMilliseconds(20), FlatnessTimeout = TimeSpan.FromMilliseconds(100) }; + FlattenReport report = await procedure.RunAsync(targets, Closer, null, CancellationToken.None); + Assert.Equal(1.5, report.RealizedPnlUsd, 9); + Assert.Equal(1, report.UnknownPnl); + Assert.DoesNotContain("NaN", report.Summary, StringComparison.Ordinal); + } +} diff --git a/Encelado/tests/Encelado.Tests/RealizedPnlTests.cs b/Encelado/tests/Encelado.Tests/RealizedPnlTests.cs new file mode 100644 index 0000000..ce358d4 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/RealizedPnlTests.cs @@ -0,0 +1,445 @@ +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.Backtest; +using Encelado.Core.Baskets.Data; +using Encelado.Core.Baskets.History; +using Encelado.Core.Broker; +using Encelado.Etoro; + +namespace Encelado.Tests; + +/// A fake HTTP endpoint for the eToro client: answers by script and records every request. +internal sealed class ScriptedHttp(Func script) : HttpMessageHandler +{ + public readonly List Requests = []; + + public static HttpResponseMessage Json(HttpStatusCode status, string body) => new(status) + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add($"{request.Method} {request.RequestUri!.PathAndQuery}"); + return Task.FromResult(script(request)); + } +} + +/// Real closes of the demo account on 2026-09-29, as the trade history returned them (read-only, 2026-09-30). +internal static class DemoHistory +{ + public static ClosedTrade Trade(long id, long instrument, bool buy, double units, double open, double close, string opened, string closed, double netProfit, double fees = 0) => + new(id, instrument, buy, units, open, close, Utc(opened), Utc(closed), netProfit, fees); + + public static DateTime Utc(string s) => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); + + /// Basket EURUSD/USDCAD of 2026-09-29: EURUSD +9.90, USDCAD −48.69 → −38.79 (the row that 5.0 recorded as +17 908). + public static readonly ClosedTrade EurUsdLong = Trade(3605914106, 1, true, 55021.23, 1.13369, 1.13387, "2026-09-29T09:15:59.58Z", "2026-09-29T21:15:28.053Z", 9.9); + + public static readonly ClosedTrade UsdCadLong = Trade(3605914105, 4, true, 117098.37, 1.41959, 1.419, "2026-09-29T09:15:58.03Z", "2026-09-29T21:15:27.223Z", -48.69); + + /// Basket EURUSD/USDCHF closed by the broker: −68.11 − 164.66 = −232.77. + public static readonly ClosedTrade EurUsdShort = Trade(3606542492, 1, false, 71698.89, 1.1336, 1.13455, "2026-09-29T18:15:01.093Z", "2026-09-29T21:06:12.667Z", -68.11); + + public static readonly ClosedTrade UsdChfShort = Trade(3606542494, 6, false, 98247.1, 0.83394, 0.83534, "2026-09-29T18:15:02.75Z", "2026-09-29T21:06:05.723Z", -164.66); + + /// A lone NZDUSD leg closed twenty seconds after opening: +5.49. + public static readonly ClosedTrade NzdUsdLone = Trade(3606352134, 3, true, 137181.16, 0.56345, 0.56349, "2026-09-29T15:15:02.707Z", "2026-09-29T15:15:24.44Z", 5.49); + + /// Basket NZDUSD/EURNZD opened at 15:45: NZDUSD +32.00 (proceeds 7 242.02), EURNZD −205.86. + public static readonly ClosedTrade NzdUsdLong = Trade(3606496659, 3, true, 128002.99, 0.56327, 0.56352, "2026-09-29T15:45:01.767Z", "2026-09-29T21:30:23.43Z", 32.0); + + public static readonly ClosedTrade EurNzdLong = Trade(3606496661, 49, true, 94886.4, 2.01195, 2.0081, "2026-09-29T15:45:03.377Z", "2026-09-29T21:16:50.24Z", -205.86); + + public static List All() => [EurUsdLong, UsdCadLong, EurUsdShort, UsdChfShort, NzdUsdLone, NzdUsdLong, EurNzdLong]; + + public static long InstrumentOf(string symbol) => symbol switch + { + "EURUSD" => 1, + "NZDUSD" => 3, + "USDCAD" => 4, + "USDCHF" => 6, + "AUDUSD" => 7, + "EURAUD" => 12, + "EURNZD" => 49, + _ => 0, + }; +} + +/// (1-5) The eToro client: the close answer is never a P&L, the history keeps fees apart and never looks empty when it cannot be read. +public class EtoroRealizedTests +{ + private static EtoroOptions Options(int fillTimeoutSeconds = 4) => new() { ApiKey = "a", UserKey = "u", Environment = "demo", FillTimeoutSeconds = fillTimeoutSeconds }; + + [Fact] + public async Task TheCloseOrderProceedsAreNeverTheRealizedPnl() + { + ScriptedHttp http = new(r => + { + string path = r.RequestUri!.PathAndQuery; + if (r.Method == HttpMethod.Post && path.EndsWith("/demo/market-close-orders/positions/3606496659", StringComparison.Ordinal)) + { + return ScriptedHttp.Json(HttpStatusCode.OK, """{"orderForClose":{"orderID":900}}"""); + } + + if (path.EndsWith("/demo/close-orders/900", StringComparison.Ordinal)) + { + // proceeds = investment 7210.02 + netProfit 32.00 of the position: the cash returned, not the profit. + return ScriptedHttp.Json(HttpStatusCode.OK, """ + {"orderID":900,"CID":15467847,"statusID":3,"orderType":18,"operationType":1,"assetCurrencyID":1,"accountCurrencyID":1,"instrumentID":3, + "requestOccurred":"2026-09-29T21:30:23.2Z","proceeds":7242.02,"externalOperationType":0, + "positions":[{"positionID":3606496659,"occurred":"2026-09-29T21:30:23.43Z","rate":0.56352,"units":128002.99,"conversionRate":1.0,"amount":7210.02}]} + """); + } + + return ScriptedHttp.Json(HttpStatusCode.NotFound, "{}"); + }); + await using EtoroBroker broker = new(Options(), http); + + CloseOutcome c = await broker.CloseAsync(3606496659, 3, CancellationToken.None); + + Assert.True(c.Closed, c.Error); + Assert.True(double.IsNaN(c.RealizedPnl), "il proceeds non è il P&L"); + Assert.Equal(7242.02, c.Proceeds, 2); + Assert.Equal(3606496659, c.PositionId); + Assert.Equal(0.56352, c.CloseRate, 5); + Assert.Equal(128002.99, c.Units, 2); + Assert.Equal(1.0, c.ConversionRate, 6); + Assert.Equal(new DateTime(2026, 9, 29, 21, 30, 23, 430, DateTimeKind.Utc), c.TimeUtc); + } + + [Fact] + public async Task APendingCloseCarriesNoPnl() + { + ScriptedHttp http = new(r => r.Method == HttpMethod.Post + ? ScriptedHttp.Json(HttpStatusCode.OK, """{"orderForClose":{"orderID":901}}""") + : ScriptedHttp.Json(HttpStatusCode.NotFound, """{"title":"Order was not found"}""")); + await using EtoroBroker broker = new(Options(fillTimeoutSeconds: 1), http); + + CloseOutcome c = await broker.CloseAsync(3606496661, 49, CancellationToken.None); + + Assert.True(c.Pending); + Assert.True(double.IsNaN(c.RealizedPnl)); + Assert.Equal(901, c.OrderId); + Assert.Equal(3606496661, c.PositionId); + } + + [Fact] + public async Task TheHistoryIsParsedWithFeesApart() + { + ScriptedHttp http = new(static r => r.RequestUri!.PathAndQuery.Contains("/trade/demo/history", StringComparison.Ordinal) + ? ScriptedHttp.Json(HttpStatusCode.OK, """ + [{"netProfit":-205.86,"closeRate":2.0081,"closeTimestamp":"2026-09-29T21:16:50.24Z","positionId":3606496661,"instrumentId":49,"isBuy":true,"leverage":10, + "openRate":2.01195,"openTimestamp":"2026-09-29T15:45:03.377Z","stopLossRate":1.99684,"takeProfitRate":4.02397,"trailingStopLoss":false,"orderId":384879111, + "socialTradeId":0,"parentPositionId":0,"investment":10753.58,"initialInvestment":10753.58,"fees":1.25,"units":94886.4}] + """) + : ScriptedHttp.Json(HttpStatusCode.NotFound, "{}")); + await using EtoroBroker broker = new(Options(), http); + + IReadOnlyList trades = await broker.GetClosedTradesAsync(new DateTime(2026, 9, 29, 0, 0, 0, DateTimeKind.Utc), CancellationToken.None); + + ClosedTrade t = Assert.Single(trades); + Assert.Equal(3606496661, t.PositionId); + Assert.Equal(49, t.InstrumentId); + Assert.True(t.IsBuy); + Assert.Equal(-205.86, t.NetProfit, 2); + Assert.Equal(1.25, t.Fees, 2); + Assert.Equal(-207.11, t.NetUsd, 2); + Assert.Equal(DateTimeKind.Utc, t.ClosedUtc.Kind); + Assert.Equal(new DateTime(2026, 9, 29, 21, 16, 50, 240, DateTimeKind.Utc), t.ClosedUtc); + Assert.Equal(new DateTime(2026, 9, 29, 15, 45, 3, 377, DateTimeKind.Utc), t.OpenedUtc); + } + + [Theory] + [InlineData(HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.Unauthorized)] + public async Task AnUnreadableHistoryThrowsInsteadOfLookingEmpty(HttpStatusCode status) + { + ScriptedHttp http = new(r => ScriptedHttp.Json(status, """{"title":"errore"}""")); + await using EtoroBroker broker = new(Options(), http); + + BrokerException ex = await Assert.ThrowsAsync(() => broker.GetClosedTradesAsync(DateTime.UtcNow.Date, CancellationToken.None)); + Assert.Equal((int)status, ex.StatusCode); + } + + [Fact] + public async Task WithoutKeysTheHistoryIsUnreadableNotEmpty() + { + await using EtoroBroker broker = new(new EtoroOptions { Environment = "demo" }, new ScriptedHttp(static _ => ScriptedHttp.Json(HttpStatusCode.OK, "[]"))); + await Assert.ThrowsAsync(() => broker.GetClosedTradesAsync(DateTime.UtcNow.Date, CancellationToken.None)); + } + + [Fact] + public async Task TheHistoryIsAskedFromTheCloseDay() + { + ScriptedHttp http = new(static _ => ScriptedHttp.Json(HttpStatusCode.OK, "[]")); + await using EtoroBroker broker = new(Options(), http); + + IReadOnlyList trades = await broker.GetClosedTradesAsync(new DateTime(2026, 9, 29, 21, 15, 27, DateTimeKind.Utc), CancellationToken.None); + + Assert.Empty(trades); + string request = Assert.Single(http.Requests); + Assert.Contains("/api/v1/trading/info/trade/demo/history?minDate=2026-09-29&page=1&pageSize=200", request, StringComparison.Ordinal); + } +} + +/// (6-9) Settlement by position id, and the estimate that stands in until the history confirms. +public class RealizedSettlementTests +{ + [Fact] + public void SumsNetProfitMinusFeesOfEveryPositionIncludingAdds() + { + ClosedTrade add = DemoHistory.Trade(3605914200, 1, true, 20_000, 1.1339, 1.13387, "2026-09-29T12:15:00Z", "2026-09-29T21:15:29Z", -0.6, 0.4); + List history = [.. DemoHistory.All(), add]; + + Settlement s = RealizedSettlement.Of([3605914106, 3605914105, 3605914200], history); + + Assert.True(s.Complete); + Assert.Equal(9.9 - 48.69 - 0.6, s.GrossUsd, 6); + Assert.Equal(0.4, s.FeesUsd, 6); + Assert.Equal(9.9 - 48.69 - 0.6 - 0.4, s.NetUsd, 6); + } + + [Fact] + public void AMissingPositionMakesTheSettlementIncomplete() + { + Settlement s = RealizedSettlement.Of([3605914106, 3699999999], DemoHistory.All()); + + Assert.False(s.Complete); + Assert.Equal([3699999999L], s.Missing); + } + + [Fact] + public void AZeroResultIsAResultNotUnknown() + { + ClosedTrade zero = DemoHistory.Trade(3603653346, 1, true, 10_000, 1.16, 1.16, "2026-09-25T10:00:00Z", "2026-09-25T10:15:00Z", 0.0); + + Settlement s = RealizedSettlement.Of([3603653346], [zero]); + + Assert.True(s.Complete); + Assert.Equal(0.0, s.NetUsd); + } + + [Fact] + public void TheEstimateMatchesTheVenueOnRealTrades() + { + // NZDUSD short, 124 476.43 units, 0.56677 → 0.56619, USD-quoted: +72.20 on the history. + Assert.Equal(72.20, RealizedSettlement.Estimate(false, 124_476.43, 0.56677, 0.56619, 1.0, 0), 2); + + // EURNZD long, 94 886.4 units, 2.01195 → 2.0081, NZD → USD 0.563518: −205.86. + Assert.InRange(RealizedSettlement.Estimate(true, 94_886.4, 2.01195, 2.0081, 0.563518, 0), -205.87, -205.85); + + // USDCAD long, 117 098.37 units, 1.41959 → 1.419, CAD → USD 1/1.419: −48.69. + Assert.InRange(RealizedSettlement.Estimate(true, 117_098.37, 1.41959, 1.419, 1 / 1.419, 0), -48.70, -48.68); + + // EURUSD long, 55 021.23 units, 1.13369 → 1.13387: +9.90; fees come off on top. + Assert.InRange(RealizedSettlement.Estimate(true, 55_021.23, 1.13369, 1.13387, 1.0, 0), 9.89, 9.91); + Assert.InRange(RealizedSettlement.Estimate(true, 55_021.23, 1.13369, 1.13387, 1.0, 1.25), 8.64, 8.66); + + // Nothing made up: without the conversion or the close price there is no estimate. + Assert.True(double.IsNaN(RealizedSettlement.Estimate(true, 94_886.4, 2.01195, 2.0081, double.NaN, 0))); + Assert.True(double.IsNaN(RealizedSettlement.Estimate(true, 94_886.4, 2.01195, 0, 0.56, 0))); + } +} + +/// A venue that closes like eToro: a rate, no realised result, the proceeds apart; one close can stay without an answer while the position disappears. +internal sealed class ProceedsVenue : IBroker +{ + public readonly Dictionary Positions = []; + + /// Close answers by position: the rate, or 0 for "pending" (the position disappears anyway). + public readonly Dictionary Rates = []; + + public BrokerEnvironment Environment => BrokerEnvironment.Demo; + + public string Name => "proceeds"; + + public bool SupportsTrading => true; + + public TimeSpan ClockSkew => TimeSpan.Zero; + + public Task> GetInstrumentsAsync(IReadOnlyList symbols, CancellationToken ct) => Task.FromResult>([]); + + public Task> GetQuotesAsync(IReadOnlyList instrumentIds, CancellationToken ct) => Task.FromResult>([]); + + public Task> GetCandlesAsync(long instrumentId, TimeSpan interval, int count, CancellationToken ct) => Task.FromResult>([]); + + public Task GetAccountAsync(CancellationToken ct) => Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", 100_000, 100_000, 90_000, 10_000, 0)); + + public Task> GetPositionsAsync(CancellationToken ct) => Task.FromResult>([.. Positions.Values]); + + public Task OpenAsync(OrderRequest request, CancellationToken ct) => throw new NotSupportedException(); + + public Task LookupOrderAsync(string clientRef, CancellationToken ct) => Task.FromResult(null); + + public Task LookupOrderByIdAsync(long orderId, CancellationToken ct) => Task.FromResult(null); + + public Task CancelOrderAsync(long orderId, CancellationToken ct) => Task.FromResult(false); + + public Task CloseAsync(long positionId, long instrumentId, CancellationToken ct) + { + Positions.Remove(positionId, out BrokerPosition? p); + double rate = Rates.GetValueOrDefault(positionId); + if (rate <= 0) + { + return Task.FromResult(new CloseOutcome(false, false, 7000 + positionId, 0, 0, DateTime.UtcNow, double.NaN, "esito non ancora noto") { PositionId = positionId }); + } + + double margin = p is null ? 0 : p.Margin; + return Task.FromResult(new CloseOutcome(true, false, 7000 + positionId, rate, p?.Units ?? 0, DateTime.UtcNow, double.NaN, string.Empty) + { + PositionId = positionId, + Proceeds = margin + 10, + ConversionRate = 1.0, + }); + } + + public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true); + + public Task GetCostAsync(OrderRequest request, CancellationToken ct) => Task.FromResult(null); + + public Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) => Task.FromResult>([]); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} + +/// (10-12) The executor: proceeds never become P&L, fees are not subtracted twice, a close without a rate does not drag the exit to zero. +public class ExecutorRealizedTests +{ + private static BasketPosition Basket(params (long Id, double Units)[] addsOnA) + { + BasketPosition p = new() + { + BasketId = "B20260929091500-EURUSDUSDCHF", + Name = "EURUSD/USDCHF", + BuyCross = true, + A = new BasketLeg { Symbol = "EURUSD", InstrumentId = 1, IsBuy = true, Units = 10_000, EntryPrice = 1.0990, PositionId = 11, OpenedUtc = DateTime.UtcNow.AddHours(-2) }, + B = new BasketLeg { Symbol = "USDCHF", InstrumentId = 6, IsBuy = true, Units = 9_000, EntryPrice = 0.8990, PositionId = 12, OpenedUtc = DateTime.UtcNow.AddHours(-2) }, + OpenedUtc = DateTime.UtcNow.AddHours(-2), + EntryZ = -2.2, + }; + foreach ((long id, double units) in addsOnA) + { + p.A.Adds.Add((id, units, 1.0990, "add")); + } + + return p; + } + + private static ProceedsVenue Venue(BasketPosition p, double rateA, double rateB) + { + ProceedsVenue venue = new(); + foreach (long id in p.A.AllPositionIds) + { + venue.Positions[id] = new BrokerPosition(id, 1, true, 10_000, 1.0990, p.OpenedUtc, 0, 0, 10, 1_099, 10, 0, rateA); + venue.Rates[id] = rateA; + } + + venue.Positions[12] = new BrokerPosition(12, 6, true, 9_000, 0.8990, p.OpenedUtc, 0, 0, 10, 900, 9, 0, rateB); + venue.Rates[12] = rateB; + return venue; + } + + [Fact] + public async Task AnEtoroLikeVenueNeverTurnsProceedsIntoPnl() + { + (BasketContext ctx, _, BasketStrategyConfig cfg) = ExecutionScenery.Entry(); + BasketPosition p = Basket(); + ProceedsVenue venue = Venue(p, 1.1000, 0.9000); + BasketExecutor executor = new(venue, cfg, ctx.Mid, static _ => { }); + + ExitOutcome x = await executor.CloseAsync(ctx, p, "test", CancellationToken.None); + + Assert.True(x.Ok, x.Error); + Assert.False(x.PnlFinal); + Assert.Equal(p.NetPnlUsd(x.ExitPriceA, x.ExitPriceB, ctx.Mid), x.RealizedPnlUsd, 9); + Assert.InRange(x.RealizedPnlUsd, 19.9, 20.1); // +10 on EURUSD, +9 CHF on USDCHF + Assert.True(Math.Abs(x.RealizedPnlUsd) < 0.05 * 11_000, "un P&L grande quanto il margine restituito è il proceeds"); + Assert.All(x.Closes, static c => Assert.True(c.Proceeds > 900)); + Assert.Equal([11L, 12L], x.Closes.Select(static c => c.PositionId)); + } + + [Fact] + public async Task SimulatorFeesAreNotSubtractedTwice() + { + Instrument eurusd = ExecutionScenery.EurUsd; + Instrument usdchf = ExecutionScenery.UsdChf; + BacktestBroker broker = new([eurusd, usdchf], 100_000, slippagePips: 0, overnightPipsPerDay: 1.0); + DateTime t0 = new(2026, 9, 16, 10, 0, 0, DateTimeKind.Utc); + QuoteSnapshot[] quotes = [new(1, t0, 1.1000, 1.1001, true), new(6, t0, 0.9000, 0.9001, true)]; + broker.Advance(t0, quotes); + OrderOutcome a = await broker.OpenAsync(new OrderRequest("a", 1, "EURUSD", true, 10_000, 10, null, null, "t"), CancellationToken.None); + OrderOutcome b = await broker.OpenAsync(new OrderRequest("b", 6, "USDCHF", true, 9_000, 10, null, null, "t"), CancellationToken.None); + + // A night goes by: overnight fees on both positions. + DateTime t1 = new(2026, 9, 16, 21, 30, 0, DateTimeKind.Utc); + QuoteSnapshot[] later = [new(1, t1, 1.1020, 1.1021, true), new(6, t1, 0.9015, 0.9016, true)]; + broker.Advance(t1, later); + IReadOnlyList open = await broker.GetPositionsAsync(CancellationToken.None); + double fees = open.Sum(static x => x.Fees); + Assert.True(fees > 1.5, "le fee overnight sono state addebitate"); + + BasketPosition p = new() + { + BasketId = "B1", + Name = "EURUSD/USDCHF", + BuyCross = true, + A = new BasketLeg { Symbol = "EURUSD", InstrumentId = 1, IsBuy = true, Units = 10_000, EntryPrice = a.FillRate, PositionId = a.PositionId }, + B = new BasketLeg { Symbol = "USDCHF", InstrumentId = 6, IsBuy = true, Units = 9_000, EntryPrice = b.FillRate, PositionId = b.PositionId }, + OpenedUtc = t0, + EntryZ = -2.2, + AccruedFeesUsd = fees, // what the engine's reconciliation writes from the venue's fee field + }; + SymbolSeries sa = new(eurusd, TimeSpan.FromMinutes(15)); + SymbolSeries sb = new(usdchf, TimeSpan.FromMinutes(15)); + sa.OnQuote(later[0], t1); + sb.OnQuote(later[1], t1); + BasketContext ctx = new() + { + TimeUtc = t1, + BasketId = "EURUSD/USDCHF", + Name = "EURUSD/USDCHF", + Cross = SyntheticCross.Derive("EURUSD", "USDCHF"), + A = sa, + B = sb, + Equity = 100_000, + PipValueUsdA = 1, + PipValueUsdB = 1, + UsdPerQuoteA = 1, + UsdPerQuoteB = 1 / 0.90155, + Mid = broker.MidOf, + }; + BasketExecutor executor = new(broker, BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _), broker.MidOf, static _ => { }); + + ExitOutcome x = await executor.CloseAsync(ctx, p, "test", CancellationToken.None); + + double legs = PipMath.LegPnlUsd("EURUSD", true, 10_000, a.FillRate, 1.1020, broker.MidOf) + PipMath.LegPnlUsd("USDCHF", true, 9_000, b.FillRate, 0.9015, broker.MidOf); + Assert.True(x.PnlFinal); + Assert.Equal(legs - fees, x.RealizedPnlUsd, 6); + Assert.Equal(broker.Closed.Sum(static c => c.NetUsd), x.RealizedPnlUsd, 6); + Assert.All(broker.Closed, static c => Assert.True(c.Fees > 0 && c.NetUsd < c.NetProfit, "la storia del simulatore tiene le fee a parte, come eToro")); + } + + [Fact] + public async Task ACloseSeenOnlyOnThePositionListDoesNotDragTheExitPriceToZero() + { + (BasketContext ctx, _, BasketStrategyConfig cfg) = ExecutionScenery.Entry(); + BasketPosition p = Basket((13, 5_000)); + ProceedsVenue venue = Venue(p, 1.1000, 0.9000); + venue.Rates[13] = 0; // the add's close stays without an answer; the position disappears from the list + + BasketExecutor executor = new(venue, cfg, ctx.Mid, static _ => { }); + ExitOutcome x = await executor.CloseAsync(ctx, p, "test", CancellationToken.None); + + Assert.True(x.Ok, x.Error); + Assert.Equal(1.1000, x.ExitPriceA, 6); + Assert.Equal(0.9000, x.ExitPriceB, 6); + Assert.False(x.PnlFinal); + Assert.Contains(x.Closes, static c => c.PositionId == 13 && c.Closed && c.CloseRate == 0 && double.IsNaN(c.RealizedPnl)); + Assert.Equal(p.NetPnlUsd(1.1000, 0.9000, ctx.Mid), x.RealizedPnlUsd, 9); + } +} diff --git a/Encelado/tests/Encelado.Tests/TodayPnlTests.cs b/Encelado/tests/Encelado.Tests/TodayPnlTests.cs new file mode 100644 index 0000000..6abb69a --- /dev/null +++ b/Encelado/tests/Encelado.Tests/TodayPnlTests.cs @@ -0,0 +1,232 @@ +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; +using Encelado.Core.Broker; +using Encelado.Engine; +using Encelado.Engine.Baskets; + +namespace Encelado.Tests; + +/// (14-17) "P&L oggi": the bot's positions closed in the UTC day, from the venue's history, equal to the Storico's "oggi". +public class RealizedTodayTests +{ + private static readonly DateTime Now = new(2026, 9, 30, 12, 0, 0, DateTimeKind.Utc); + + private static ClosedTrade Closed(long id, string closedUtc, double netProfit, double fees = 0) => + DemoHistory.Trade(id, 1, true, 10_000, 1.1, 1.1, "2026-09-29T20:00:00Z", closedUtc, netProfit, fees); + + private static OrderRecord Order(string basketId, string basket, OrderLeg leg, long positionId) => + new(Now.AddHours(-20), "run", "Demo", basket, basketId, "EURUSD", 1, true, leg, 10_000, 10_000, 1.1, 1.1, 0, "Filled", 3, OrderResolution.Filled, 900 + positionId, positionId, $"c{positionId}", 0, "risolto", "x"); + + private static BasketOutcomeRow Row(string basketId, string exit, double entryZ, double net) => + new(basketId, "run", "EURUSD/USDCHF", "Demo", "MODERATE", Now.AddHours(-20), Now.AddHours(-11), true, entryZ, 0.1, net, net, 5, 3, 3, 0.2, 0, 8, exit, 100_000, double.NaN, "x"); + + [Fact] + public void TodayIsTheNetOfTheBotsPositionsClosedTodayUtc() + { + List history = + [ + Closed(1, "2026-09-30T00:00:01Z", 10, 0.5), // opened yesterday, closed today: counts, fees off + Closed(2, "2026-09-29T23:59:59Z", 1000), // closed yesterday: out + Closed(3, "2026-09-30T08:00:00Z", 500), // a stranger's: out + Closed(4, "2026-09-30T11:00:00Z", -3), + ]; + PositionOwner Owner(long id) => id == 3 ? PositionOwner.Foreign : new PositionOwner(PositionOwner.BasketOrigin, "B1", "EURUSD/USDCHF", "tp_pips"); + + RealizedToday today = new(); + today.Roll(Now); + today.Apply(history, Owner); + + Assert.True(today.IsKnown); + Assert.Equal(6.5, today.Value, 9); + Assert.False(today.IsProvisional); + Assert.Equal(new TodayClosedStats(1, 1, 0, 0), today.Closed); + } + + [Fact] + public void TodayEqualsTheStoricoOggiPeriod() + { + List orders = + [ + Order("B1", "EURUSD/USDCHF", OrderLeg.A, 11), + Order("B1", "EURUSD/USDCHF", OrderLeg.B, 12), + Order("B2", "AUDUSD/USDCAD", OrderLeg.A, 13), + Order("B3", "EURUSD/USDCHF", OrderLeg.A, 15), + Order("B3", "EURUSD/USDCHF", OrderLeg.B, 16), + ]; + List baskets = + [ + Row("B1", "tp_pips", -2.1, 9), + Row("B2", "leg_risk_unwind", double.NaN, -10), + Row("B3", "stop_z", 2.4, -30), + ]; + List history = + [ + Closed(11, "2026-09-30T09:00:00Z", 10, 0.5), + Closed(12, "2026-09-30T09:00:01Z", -0.5), + Closed(13, "2026-09-30T10:00:00Z", -10), + Closed(15, "2026-09-30T11:00:00Z", -12, 0.2), + Closed(16, "2026-09-30T11:00:01Z", -18), + Closed(14, "2026-09-30T11:30:00Z", 44), // external: out of both + Closed(17, "2026-09-29T23:00:00Z", 7), // yesterday: out of both + ]; + + PositionOrigins origins = new(orders, baskets); + List rows = HistoryBuilder.Positions(history, [], baskets, orders, [], static _ => "EURUSD", PipMath.Pip, Now); + PeriodStats oggi = HistoryBuilder.Periods(rows, Now).Single(static p => p.Periodo == "oggi"); + + RealizedToday today = new(); + today.Roll(Now); + today.Apply(history, origins.Classify); + + Assert.Equal(oggi.PnlNetto, today.Value, 9); + Assert.Equal(10 - 0.5 - 0.5 - 10 - 12 - 0.2 - 18, today.Value, 9); + Assert.Equal(oggi.NBasket, today.Closed.Baskets + today.Closed.LoneLegs); + Assert.Equal(oggi.Vinti, today.Closed.Won); + Assert.Equal(oggi.Persi, today.Closed.Lost); + Assert.Equal(1, today.Closed.LoneLegs); + } + + [Fact] + public void AProvisionalEstimateIsReplacedNotAdded() + { + RealizedToday today = new(); + today.Roll(Now); + today.Apply([], static _ => new PositionOwner(PositionOwner.BasketOrigin, "B1", "b", "tp")); + today.AddProvisional("B1|t", [1, 2], 10, Now.AddMinutes(-1)); + + Assert.Equal(10, today.Value, 9); + Assert.True(today.IsProvisional); + Assert.Equal(new TodayClosedStats(1, 1, 0, 0), today.Closed); + + // Only one leg in the history yet: the estimate still stands for the whole basket, the leg is held back. + today.Apply([Closed(1, "2026-09-30T11:59:00Z", 5)], static _ => new PositionOwner(PositionOwner.BasketOrigin, "B1", "b", "tp")); + Assert.Equal(10, today.Value, 9); + Assert.True(today.IsProvisional); + + // Both legs: the venue's number replaces the estimate. + today.Apply([Closed(1, "2026-09-30T11:59:00Z", 5), Closed(2, "2026-09-30T11:59:01Z", 3)], static _ => new PositionOwner(PositionOwner.BasketOrigin, "B1", "b", "tp")); + Assert.Equal(8, today.Value, 9); + Assert.False(today.IsProvisional); + Assert.Equal(new TodayClosedStats(1, 1, 0, 0), today.Closed); + } + + [Fact] + public void UnknownUntilTheFirstReadAndResetAtUtcMidnight() + { + RealizedToday today = new(); + Assert.True(today.Roll(Now)); + Assert.False(today.IsKnown); + Assert.True(double.IsNaN(today.Value)); + + // An estimate alone does not make the day known. + today.AddProvisional("k", [1], 4, Now); + Assert.True(double.IsNaN(today.Value)); + + today.Apply([Closed(9, "2026-09-30T01:00:00Z", 2)], static _ => new PositionOwner(PositionOwner.OrphanOrigin, string.Empty, "x", "orphan_closed")); + Assert.Equal(6, today.Value, 9); + Assert.False(today.Roll(Now.AddHours(3))); + + Assert.True(today.Roll(new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc))); + Assert.True(double.IsNaN(today.Settled)); + Assert.True(double.IsNaN(today.Value)); + Assert.False(today.IsProvisional); + Assert.Equal(TodayClosedStats.Empty, today.Closed); + } +} + +/// (18-20) The daily-loss rule on net equity, as RISK_RULES and the backtest say. +public class DailyLossTests +{ + [Fact] + public void DailyLossIsTheEquityDropSinceMidnightNetOfCash() + { + Assert.True(DailyLoss.IsHit(100_000, 97_000, 3)); + Assert.False(DailyLoss.IsHit(100_000, 97_001, 3)); + Assert.False(DailyLoss.IsHit(double.NaN, 90_000, 3)); + Assert.False(DailyLoss.IsHit(100_000, double.NaN, 3)); + Assert.Equal(0.5, DailyLoss.UsedFraction(100_000, 98_500, 3), 9); + Assert.Equal(0, DailyLoss.UsedFraction(100_000, 101_000, 3), 9); + Assert.Equal(1, DailyLoss.UsedFraction(100_000, 90_000, 3), 9); + Assert.True(double.IsNaN(DailyLoss.UsedFraction(double.NaN, 90_000, 3))); + } + + [Fact] + public void ADepositDoesNotHideADailyLoss() + { + EquityTracker t = new(); + DateTime midnight = new(2026, 9, 30, 0, 0, 5, DateTimeKind.Utc); + Assert.Null(t.Observe(midnight, 100_000, 100_000, 0)); + double dayStart = t.NetEquity(100_000); + + // A basket loses 4 000 and 30 000 of virtual credit arrive in the same hour. + CashMovement? m = t.Observe(midnight.AddHours(3), 126_000, 126_000, -4_000); + + Assert.NotNull(m); + Assert.Equal(30_000, m!.Amount, 2); + Assert.Equal(96_000, t.NetEquity(126_000), 2); + Assert.True(DailyLoss.IsHit(dayStart, t.NetEquity(126_000), 3)); + Assert.False(DailyLoss.IsHit(dayStart, 126_000, 3), "sull'equity lorda il deposito nasconderebbe la perdita"); + } + + [Fact] + public void AnUnexplainedBalanceChangeIsNotACashMovementYet() + { + EquityTracker t = new(); + DateTime t0 = new(2026, 9, 30, 9, 0, 0, DateTimeKind.Utc); + t.Observe(t0, 100_000, 100_000, 0); + + // A basket closed at a loss; the history does not show it yet. + Assert.Null(t.Observe(t0.AddSeconds(20), 96_000, 96_000, double.NaN)); + Assert.Equal(100_000, t.LastBalance, 2); + Assert.Equal(0, t.CumulativeCashFlow, 2); + Assert.Equal(100_000, t.PeakNetEquity, 2); + + // The history explains it at the next reading: still no cash movement. + Assert.Null(t.Observe(t0.AddSeconds(40), 96_000, 96_000, -4_000)); + Assert.Equal(96_000, t.LastBalance, 2); + Assert.Equal(0, t.CumulativeCashFlow, 2); + + // At startup without the history the balance only becomes the new reference. + t.Rebase(t0.AddHours(5), 90_000, 90_000); + Assert.Equal(90_000, t.LastBalance, 2); + Assert.Equal(0, t.CumulativeCashFlow, 2); + Assert.Null(t.Observe(t0.AddHours(5).AddSeconds(20), 90_000, 90_000, 0)); + } +} + +/// (35) Unknown values are a dash for the phone and null for the web, never "NaN". +public class UnknownTodayTests +{ + [Fact] + public void HourlyShowsADashWhenTodayIsUnknown() + { + BotSnapshot s = SampleSnapshot.Populated() with { TodayPnl = double.NaN, TodayPnlPct = double.NaN, TodayEquityChange = double.NaN }; + + string text = TelegramReports.Hourly(s, "Telegram: ok"); + + Assert.Contains("P&L oggi — (—)", text, StringComparison.Ordinal); + Assert.Contains("equity netta da mezzanotte —", text, StringComparison.Ordinal); + Assert.DoesNotContain("NaN", text, StringComparison.Ordinal); + } + + [Fact] + public void AProvisionalTodayIsMarkedAndTheSnapshotCarriesTheNewFields() + { + BotSnapshot s = SampleSnapshot.Populated() with { TodayPnlProvisional = true, DailyLossHit = true }; + Assert.Contains("P&L oggi +120.50 (0.11 %) stima", TelegramReports.Hourly(s, string.Empty), StringComparison.Ordinal); + Assert.Contains("Perdita giornaliera raggiunta", TelegramReports.Hourly(s, string.Empty), StringComparison.Ordinal); + + string json = SnapshotJson.Write(s); + Assert.Contains("\"todayPnl\":120.5", json, StringComparison.Ordinal); + Assert.Contains("\"todayPnlProvisional\":true", json, StringComparison.Ordinal); + Assert.Contains("\"todayEquityChange\":70.75", json, StringComparison.Ordinal); + Assert.Contains("\"todayClosed\":{\"baskets\":2,\"won\":1,\"lost\":1,\"loneLegs\":0}", json, StringComparison.Ordinal); + Assert.Contains("\"dailyLossHit\":true", json, StringComparison.Ordinal); + + string idle = SnapshotJson.Write(SampleSnapshot.Minimal(BotState.Stopped)); + Assert.Contains("\"todayPnl\":null", idle, StringComparison.Ordinal); + Assert.Contains("\"todayEquityChange\":null", idle, StringComparison.Ordinal); + Assert.Contains("\"dailyLossUsedPct\":null", idle, StringComparison.Ordinal); + Assert.DoesNotContain("NaN", idle, StringComparison.Ordinal); + } +}