Files
Encelado/Encelado/src/Encelado.Engine/Engine/SampleData.cs
T
Alby96andClaude Opus 5.5 07a00cd91c 5.1 revisione, ciclo di vita del motore: un solo lucchetto per avvio, arresto e riavvii, nessun comando senza risposta, chiusura all'arresto sul thread di decisione
FERMA arrivato mentre AVVIA (o un riavvio automatico delle impostazioni) costruiva il motore dichiarava il bot fermo e lasciava un motore che operava senza che kill-switch, FERMA e comandi lo raggiungessero. Ora il supervisore ha un unico lucchetto del ciclo di vita che serializza avvio, arresto, riavvio automatico, rilascio di un motore in errore e ciclo di apprendimento a motore fermo; ogni avvio ha un numero di generazione e un arresto pulisce solo il motore che ha fermato; lo stato resta «stopping» finché il motore vecchio non ha lasciato instance.lock, così AVVIA subito dopo FERMA aspetta invece di fallire con «un'altra istanza». Un motore il cui ciclo finisce senza che nessuno l'abbia fermato è un errore, non un arresto silenzioso.

Il riavvio automatico passa dallo stesso lucchetto, rilegge lo stato e riavvia solo un motore ancora acceso: FERMA arrivato durante un salvataggio o durante la verifica delle chiavi non viene più annullato. Un kill-switch, una chiusura o la chiusura dei residui in corso non vengono mai tagliati a metà: FERMA e i salvataggi che riavvierebbero il motore rispondono 409 prima di scrivere; solo l'arresto del processo li interrompe, dopo 30 s, e un kill-switch interrotto registra il residuo (Halted-Residuo) invece di un blocco pulito.

Ogni comando riceve risposta: quelli in coda o interrotti quando il motore si ferma (anche quando l'avvio fallisce) rispondono subito «comando interrotto: il motore si è fermato» e finiscono nel ledger; un'attesa scaduta risponde 504 con un messaggio esplicito, mai 500. Con closeOnShutdown la chiusura all'arresto è un comando eseguito dal motore sul suo thread di decisione (blocca nuove entrate e aggiunte, chiude entro 30 s, poi il ciclo viene annullato): nessun metodo del motore è più chiamato da un altro thread e una chiusura oltre il tempo non lascia più il supervisore bloccato in «stopping» con il motore che continua a operare. Lo stato si scrive con un file temporaneo unico.

«Esegui ciclo» risponde 409 finché il ciclo di decisione non è partito. SnapshotHub non tiene più un iscritto quando il primo tick fallisce (e un file del modello non leggibile per permessi non fa più fallire ogni tick). Il motore pubblica l'intervallo dell'heartbeat, che si cambia a caldo fino a 600 s: campo heartbeatSeconds nel tick, in /api/system e in /api/health, e il controllo di salute usa 3 × intervallo + 15 s invece dei 105 s fissi. docs/API.md aggiornato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:11:29 +02:00

779 lines
43 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using Encelado.Core.Baskets;
using Encelado.Core.Baskets.History;
using Encelado.Core.Baskets.Learning;
using Encelado.Core.Broker;
using Encelado.Core.News;
using Encelado.Core.Notifications;
using Encelado.Engine.Baskets;
using Encelado.Engine.Configuration;
using Encelado.Engine.Settings;
using Encelado.Etoro;
namespace Encelado.Engine;
/// <summary>
/// The scenario of <c>--sample</c>, one pure function per section (5.1, decision E6): same
/// anchor and same instant, same numbers everywhere. Prices drift a little every second
/// around fixed levels; the account, the open basket and the positions page are priced on
/// those quotes; the calendar and the orders sit at fixed distances from the anchor, so a
/// release approaches, blacks out a basket, passes. Nothing here is ever sent anywhere.
/// </summary>
public static partial class SampleData
{
/// <summary>The instruments of the scenario: symbol, eToro-like id, mid level, typical spread in pips, conversion only.</summary>
private static readonly (string Symbol, long Id, double Mid, double SpreadPips, bool Conversion)[] Instruments =
[
("EURUSD", 1, 1.15520, 0.6, false),
("USDCHF", 6, 0.81870, 1.1, false),
("AUDUSD", 7, 0.66050, 0.9, false),
("USDCAD", 4, 1.38100, 1.3, false),
("NZDUSD", 8, 0.58500, 1.4, false),
("EURNZD", 49, 1.97470, 3.2, false),
("EURAUD", 44, 1.74900, 2.4, false),
("AUDCAD", 40, 0.91210, 2.0, false),
("GBPUSD", 2, 1.34400, 1.1, true),
("USDJPY", 5, 148.200, 1.0, true),
];
private const string RunId = "20260930-070000-5a1b2c";
private const string StrategyHash = "1a2b3c4d5e6f7a8b";
private const double Balance = 139_200.00;
private const double PeakNetEquity = 140_100.00;
private const double DayStartEquity = 139_050.00;
private sealed record Quote(string Symbol, long Id, double Bid, double Ask, double Pip, bool Conversion)
{
public double Mid => (Bid + Ask) / 2;
}
/// <summary>The scenario's anchor: the instant rounded down to the minute.</summary>
public static DateTime Anchor(DateTime utc) => new(utc.Ticks - (utc.Ticks % TimeSpan.TicksPerMinute), DateTimeKind.Utc);
private static double Seconds(DateTime epoch, DateTime now) => Math.Max(0, (now - epoch).TotalSeconds);
private static double Wave(double t, double period, double amplitude, double phase = 0) => amplitude * Math.Sin((t / period) + phase);
private static DateTime BarClose(DateTime now) => new(now.Ticks - (now.Ticks % TimeSpan.FromMinutes(15).Ticks), DateTimeKind.Utc);
private static string F(FormattableString s) => s.ToString(CultureInfo.InvariantCulture);
// -----------------------------------------------------------------------
// Quotes and exchange rates
// -----------------------------------------------------------------------
private static Dictionary<string, Quote> Quotes(double t)
{
Dictionary<string, Quote> map = new(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < Instruments.Length; i++)
{
(string symbol, long id, double level, double spreadPips, bool conversion) = Instruments[i];
double pip = PipMath.Pip(symbol);
double mid = level * (1 + Wave(t, 41, 0.00018, i));
double spread = spreadPips * (1 + Wave(t, 13, 0.15, i * 0.7)) * pip;
int digits = PipMath.Digits(symbol);
map[symbol] = new Quote(symbol, id, Math.Round(mid - (spread / 2), digits), Math.Round(mid + (spread / 2), digits), pip, conversion);
}
return map;
}
private static Func<string, double?> MidOf(Dictionary<string, Quote> quotes) => s => quotes.TryGetValue(s, out Quote? q) ? q.Mid : null;
// -----------------------------------------------------------------------
// The engine's picture
// -----------------------------------------------------------------------
/// <summary>The engine's picture at <paramref name="now"/> for the scenario anchored at <paramref name="epoch"/>.</summary>
public static EngineView View(DateTime epoch, DateTime now, BasketStrategyConfig strategy, IReadOnlyList<PositionRecord>? history = null)
{
ArgumentNullException.ThrowIfNull(strategy);
double t = Seconds(epoch, now);
Dictionary<string, Quote> q = Quotes(t);
Func<string, double?> mid = MidOf(q);
ThresholdsView th = ThresholdsView.From(strategy);
ContextView ctx = Context(epoch, now);
DateTime started = epoch.AddHours(-3);
DateTime barClose = BarClose(now);
// The open basket's legs, the orphan and the two foreign positions, priced on the quotes of the moment.
List<AccountPositionView> positions = Positions(epoch, now, q, mid);
bool pendingOnEurcad = strategy.Baskets.Any(static b => b.Name == "EURAUD/AUDCAD");
List<BasketView> baskets = [];
int index = 0;
foreach (BasketDefinition d in strategy.Baskets)
{
baskets.Add(Basket(index++, d, epoch, now, t, q, mid, th, ctx, positions, barClose, pendingOnEurcad));
}
double unrealized = positions.Sum(static p => p.Position.UnrealizedPnl);
double margin = positions.Sum(static p => p.Position.Margin);
double equity = Balance + unrealized;
double openPnl = baskets.Where(static b => b.IsOpen && double.IsFinite(b.Evaluation.PnlOpenUsd)).Sum(static b => b.Evaluation.PnlOpenUsd);
IReadOnlyList<PositionRecord> past = history ?? History(epoch, now).Positions;
PeriodStats today = HistoryBuilder.Period("oggi", now.Date, now.Date.AddDays(1), past);
TodayClosedStats closed = TodayUnits(past, now);
FundsView funds = new()
{
AccountUtc = now.AddSeconds(-(t % 20)),
Equity = equity,
Balance = Balance,
Available = Balance - margin,
UsedMargin = margin,
UnrealizedPnl = unrealized,
OpenPnl = openPnl,
PeakEquity = PeakNetEquity,
DrawdownPct = Math.Max(0, (PeakNetEquity - equity) / PeakNetEquity),
CumulativeCashFlow = 0,
DayStartEquity = DayStartEquity,
TodayPnl = today.PnlNetto,
TodayPnlProvisional = false,
TodayEquityChange = equity - DayStartEquity,
TodayClosed = closed,
DailyLossUsedPct = DailyLoss.UsedFraction(DayStartEquity, equity, strategy.DailyLossPct),
DailyLossHit = DailyLoss.IsHit(DayStartEquity, equity, strategy.DailyLossPct),
PendingSettlements = 0,
};
List<QuoteView> quotes = [];
foreach (Quote x in q.Values)
{
List<string> usedBy = [.. strategy.Baskets.Where(b => b.A.Equals(x.Symbol, StringComparison.OrdinalIgnoreCase) || b.B.Equals(x.Symbol, StringComparison.OrdinalIgnoreCase)).Select(static b => b.Name)];
double spreadPips = (x.Ask - x.Bid) / x.Pip;
double median = Instruments.First(i => i.Symbol == x.Symbol).SpreadPips;
quotes.Add(new QuoteView(x.Symbol, x.Id, x.Bid, x.Ask, now.AddMilliseconds(-400), now.AddMilliseconds(-300), true, spreadPips, median,
Math.Round(median * 6.5, 1), barClose, string.Empty, usedBy, x.Conversion && usedBy.Count == 0, x.Pip));
}
PendingOrderView[] pendingOrders = baskets.Any(static b => b.Pending is not null)
? [new PendingOrderView("7f3c1a2e-5b9d-4c11-9e2a-0b6f5d3c8a41", 0, "EURAUD/AUDCAD", PendingBasketId(epoch), "A", "EURAUD", true, 21_000, now.AddSeconds(-(95 + (t % 240))), "Unknown", 3 + (int)(t % 240 / 30))]
: [];
return new EngineView
{
PublishedUtc = now,
TickUtc = now.AddMilliseconds(-350),
StartedUtc = started,
RunId = RunId,
StrategyHash = StrategyHash,
Preset = strategy.Preset,
Mode = ExecutionMode.Demo,
Endpoint = "https://public-api.etoro.com",
OrphanPolicy = OrphanPolicy.Report,
InstanceLock = "/data/data/state/instance.lock",
HeartbeatUtc = now.AddSeconds(-(t % 30)),
HeartbeatSeconds = 30,
RecoveryPending = false,
Api = Api(epoch, now, t),
Funds = funds,
Alarms = new AlarmsView { EntriesBlockedReason = string.Empty },
Thresholds = th,
OpenBaskets = baskets.Count(static b => b.IsOpen),
PendingBaskets = baskets.Count(static b => b.Pending is not null),
PendingOrders = pendingOrders.Length,
OrphanLegs = positions.Count(static p => p.Origin == PositionOrigin.OrphanBot),
ForeignPositions = positions.Count(static p => p.Origin == PositionOrigin.Foreign),
Baskets = baskets,
Quotes = quotes,
Fx = Fx(q, now),
Positions = new PositionsView(now.AddSeconds(-(t % 20)), string.Empty, positions),
PendingOrderList = pendingOrders,
Learning = SampleHeadline(epoch, strategy),
LearningText = SampleLearningText(epoch, strategy),
BanditText = Core(epoch).Proposal.Text + " (solo proposta)",
};
}
private static string SampleLearningText(DateTime epoch, BasketStrategyConfig strategy)
{
LearningCore core = Core(epoch);
double auc = ModelEvaluator.RollingAuc(core.Recent, RollingMetrics.Window);
string line = F($"logistica v{core.Cycle.Version} in ombra: {core.Logistic.Seen} basket visti, AUC mobile {(double.IsFinite(auc) ? auc.ToString("0.000", CultureInfo.InvariantCulture) : "n/d")}; {core.Cycle.Rows} basket su 300 richiesti");
return strategy.Learning.Enabled ? line : "disattivato (ADR-0006): " + line;
}
private static readonly (string Currency, string Pair, bool Invert)[] FxPairs =
[("EUR", "EURUSD", false), ("GBP", "GBPUSD", false), ("AUD", "AUDUSD", false), ("NZD", "NZDUSD", false), ("CHF", "USDCHF", true), ("JPY", "USDJPY", true), ("CAD", "USDCAD", true)];
private static List<FxView> Fx(Dictionary<string, Quote> q, DateTime now)
{
List<FxView> rates = [new FxView("USD", 1, string.Empty, false, now)];
foreach ((string currency, string pair, bool invert) in FxPairs)
{
double m = q[pair].Mid;
rates.Add(new FxView(currency, invert ? 1 / m : m, pair, invert, now.AddMilliseconds(-400)));
}
return rates;
}
private static ApiView Api(DateTime epoch, DateTime now, double t)
{
long requests = 7_200 + (long)(t / 1.4);
QuotaUsage[] quotas =
[
new("market-data", 21 + (int)Math.Abs(Wave(t, 7, 3)), 110, 60, null, 0),
new("trading", 0, 18, 60, null, 0),
new("portfolio", 6, 55, 60, null, 0),
new("lookup", 4 + (int)(t % 3), 55, 60, null, 1),
new("costs", 2, 18, 60, null, 0),
new("eligibility", 0, 18, 60, null, 0),
new("default", 3, 55, 60, null, 0),
];
EtoroHttpStats http = new(Math.Round(138 + Wave(t, 5, 22), 1), Math.Round(151 + Wave(t, 60, 6), 1), requests, 3, 0,
new ApiError(epoch.AddMinutes(-47), "GET api/v1/trading/info/trade/demo/history: nessuna risposta entro il timeout"), quotas);
return new ApiView("connesso", "https://public-api.etoro.com", Math.Round(0.4 + Wave(t, 90, 0.1), 2), 5, 0, now.AddSeconds(-(t % 3)), http);
}
// -----------------------------------------------------------------------
// Positions of the account
// -----------------------------------------------------------------------
private static string OpenBasketId(DateTime epoch) => string.Create(CultureInfo.InvariantCulture, $"B{epoch.AddMinutes(-90):yyyyMMddHHmm}00-EURUSDUSDCHF");
private static string PendingBasketId(DateTime epoch) => string.Create(CultureInfo.InvariantCulture, $"B{epoch.AddMinutes(-2):yyyyMMddHHmm}00-EURAUDAUDCAD");
private static List<AccountPositionView> Positions(DateTime epoch, DateTime now, Dictionary<string, Quote> q, Func<string, double?> mid)
{
string basketId = OpenBasketId(epoch);
return
[
Position(3_104_555_001, "EURUSD", false, 43_000, 1.15612, epoch.AddMinutes(-90), 1.20 + 0.40, q, mid, PositionOrigin.Basket, "EURUSD/USDCHF", basketId, "A", "gamba di un basket noto"),
Position(3_104_555_002, "USDCHF", false, 49_000, 0.81950, epoch.AddMinutes(-90), 1.35 + 0.45, q, mid, PositionOrigin.Basket, "EURUSD/USDCHF", basketId, "B", "gamba di un basket noto"),
Position(3_104_551_234, "NZDUSD", true, 12_000, 0.58321, epoch.AddDays(-2).AddHours(-3), 0.95, q, mid, PositionOrigin.OrphanBot, "NZDUSD/EURNZD",
string.Create(CultureInfo.InvariantCulture, $"B{epoch.AddDays(-2).AddHours(-3):yyyyMMddHHmm}00-NZDUSDEURNZD"), string.Empty,
string.Create(CultureInfo.InvariantCulture, $"firma del bot: ingresso di NZDUSD/EURNZD alle {epoch.AddDays(-2).AddHours(-3):HH:mm}:11 UTC (3 s), unità coerenti")),
Position(3_104_549_876, "GBPUSD", true, 20_000, 1.33810, epoch.AddDays(-5), 2.10, q, mid, PositionOrigin.Foreign, string.Empty, string.Empty, string.Empty,
"nessun basket, nessun ordine del registro, nessuna decisione del ledger coerente"),
Position(3_104_540_001, "USDJPY", false, 15_000, 149.10, epoch.AddDays(-9), 3.40, q, mid, PositionOrigin.Foreign, string.Empty, string.Empty, string.Empty,
"nessun basket, nessun ordine del registro, nessuna decisione del ledger coerente"),
];
}
private static AccountPositionView Position(long id, string symbol, bool isBuy, double units, double openRate, DateTime opened, double fees, Dictionary<string, Quote> q, Func<string, double?> mid,
PositionOrigin origin, string basket, string basketId, string leg, string reason)
{
Quote x = q[symbol];
double exit = isBuy ? x.Bid : x.Ask;
double pnl = PipMath.LegPnlUsd(symbol, isBuy, units, openRate, exit, mid) - fees;
double margin = PipMath.NotionalUsd(symbol, units, openRate, mid) / 10;
BrokerPosition p = new(id, x.Id, isBuy, units, openRate, opened, 0, 0, 10, Math.Round(margin, 2), Math.Round(pnl, 2), fees, exit);
return new AccountPositionView(p, symbol, x.Pip, origin, basket, basketId, leg, reason);
}
// -----------------------------------------------------------------------
// Baskets
// -----------------------------------------------------------------------
private static BasketView Basket(int index, BasketDefinition d, DateTime epoch, DateTime now, double t, Dictionary<string, Quote> q, Func<string, double?> mid,
ThresholdsView th, ContextView ctx, List<AccountPositionView> positions, DateTime barClose, bool pendingOnEurcad)
{
SyntheticCross cross = SyntheticCross.TryDerive(d.A, d.B, out SyntheticCross? c) ? c! : new SyntheticCross(d.A, d.B, "USD", "???", 1, true, -1);
(string longCcy, string shortCcy) = cross.Exposure();
BasketContextFeatures features = ContextFeatures.For(ctx, longCcy, shortCcy, cross.Common, now);
Quote? qa = q.GetValueOrDefault(d.A);
Quote? qb = q.GetValueOrDefault(d.B);
double pipA = PipMath.Pip(d.A), pipB = PipMath.Pip(d.B);
double spreadA = qa is null ? double.NaN : (qa.Ask - qa.Bid) / pipA;
double spreadB = qb is null ? double.NaN : (qb.Ask - qb.Bid) / pipB;
double medianA = Instruments.FirstOrDefault(i => i.Symbol == d.A).SpreadPips;
double medianB = Instruments.FirstOrDefault(i => i.Symbol == d.B).SpreadPips;
double volRatio = 0.93 + Wave(t, 300, 0.05, index);
VolStats vol = new(2880, index == 0 ? "HAR" : "EWMA", 0.00041 + Wave(t, 200, 0.00002, index), 0.00038 + Wave(t, 200, 0.00002, index),
(0.00041 * volRatio) + Wave(t, 200, 0.00001, index), 0.00041, 0.00012, 0.00011, 312, 8, epoch.AddHours(-5));
double zInEffective = th.ZIn * Math.Clamp(vol.Ratio, th.VolScaleMin, th.VolScaleMax);
(double hs, double hc) = BasketMath.HourFeatures(now);
string scenario = d.Name switch
{
"EURUSD/USDCHF" => "open",
"AUDUSD/USDCAD" => "quiet",
"NZDUSD/EURNZD" => "blocked",
"USDCAD/EURUSD" => pendingOnEurcad ? "samecross" : "quiet",
"EURAUD/AUDCAD" => "pending",
_ => "quiet",
};
double z = scenario switch
{
"open" => 1.62 + Wave(t, 29, 0.12),
"blocked" => -2.31 + Wave(t, 31, 0.05),
"samecross" => 2.05 + Wave(t, 37, 0.04),
"pending" => -2.37,
_ => 0.42 + Wave(t, 53, 0.2, index),
};
double rho = scenario == "quiet" ? -0.61 : -0.72 + Wave(t, 97, 0.02, index);
double rhoShort = -0.55 + Wave(t, 71, 0.05, index);
double halfLife = 31 + (index * 7);
// Within 3× the TP of the default preset, so the cost gate of the pending entry passes as the engine's would.
double costPips = Math.Round(2.5 + (index * 0.15) + Wave(t, 19, 0.15, index), 2);
double breakEven = 0.45 + (index * 0.03);
BasketEvaluation eval = new()
{
Z = z,
ZInEffective = zInEffective,
RhoW = rho,
RhoShort = rhoShort,
HalfLife = halfLife,
AtrPipsA = Math.Round(medianA * 6.5, 1),
AtrPipsB = Math.Round(medianB * 6.5, 1),
SigmaX = 0.0021,
EwmaVolX = 0.00043,
TrendStrength = 18 + (index * 3),
SpreadPipsA = spreadA,
SpreadPipsB = spreadB,
CostPips = costPips,
BreakEvenWinRate = breakEven,
HourSin = hs,
HourCos = hc,
DayOfWeek = (int)now.DayOfWeek,
PriceA = qa?.Mid ?? 0,
PriceB = qb?.Mid ?? 0,
};
PositionView? position = null;
PendingView? pending = null;
DecisionView? decision;
string intent;
BasketState state = BasketState.Idle;
double[] ml = LearningFeatures.From(new BasketContext
{
TimeUtc = now,
BasketId = d.Name,
Name = d.Name,
Cross = cross,
A = Placeholder(d.A, qa?.Id ?? 0),
B = Placeholder(d.B, qb?.Id ?? 0),
Equity = Balance,
PipValueUsdA = 1,
PipValueUsdB = 1,
UsdPerQuoteA = 1,
UsdPerQuoteB = 1,
Mid = mid,
MinutesToNextHigh = features.MinutesToNextHigh,
MinutesSinceLastHigh = features.MinutesSinceLastHigh,
SurpriseLast = features.SurpriseLast,
NetSentimentDiff1h = features.NetSentimentDiff1h,
NetSentimentDiff4h = features.NetSentimentDiff4h,
NetSentimentDiff24h = features.NetSentimentDiff24h,
HawkishDiff = features.HawkishDiff,
RiskOff = features.RiskOff,
NewsCount = features.NewsCount,
SigmaForecast = vol.ForecastSigma,
SigmaAverage30d = vol.Average30dSigma,
LastOutcomes = 0.54,
}, eval, z < 0);
// The scenario's logistic scores the vector: the learning page's contributions add up to this p.
double pMl = Core(epoch).Logistic.Predict(ml);
CostGateResult cost = new(true, costPips, spreadA, spreadB, 0.2, 0.3, 0.4, breakEven, F($"costo {costPips:F1} pip, TP {th.TpPips:F1} = {th.TpPips / costPips:F1}× il costo, break-even {breakEven:P0}"));
switch (scenario)
{
case "open":
{
position = OpenPosition(epoch, now, positions, q, mid, th);
double pips = position.A.Pips + position.B.Pips;
double pnl = position.A.PnlUsd + position.B.PnlUsd - position.A.EntryFeesUsd - position.B.EntryFeesUsd - position.AccruedFeesUsd;
eval = eval with { PipsOpen = pips, PnlOpenUsd = pnl, BarsHeld = position.BarsHeld };
state = BasketState.Open;
intent = F($"IN POSIZIONE — {pips:+0.0;-0.0} pip, netto {pnl:+0.00;-0.00} USD, z {z:+0.00;-0.00} (entrata {position.EntryZ:+0.00;-0.00}), {position.BarsHeld}/{th.MaxHoldingBars} barre");
decision = new DecisionView(DecisionKind.Hold, false, ["hold"], intent, barClose, null, null);
break;
}
case "pending":
{
SizingResult sizing = new(true, 21_000, 23_000, 36_700, 20_980, 690, 4.1, "vol-parity: A 21000, B 23000 unità, perdita allo stop 690 USD (0.50 % dell'equity)") { Bound = "risk", MarginUsd = 5_768 };
string why = F($"COMPRO il cross {cross.Symbol}: z {z:+0.00;-0.00} oltre ±{zInEffective:0.00}, ρ_W {rho:+0.00;-0.00}, ρ_20 {rhoShort:+0.00;-0.00}, HL {halfLife:0} barre; {cost.Reason}; {sizing.Reason}; gambe long {d.A} + long {d.B}; p_ML {pMl:0.00} (ombra)");
decision = new DecisionView(DecisionKind.Enter, true, ["enter"], why, barClose, cost, sizing);
DateTime decided = now.AddSeconds(-(95 + (t % 240)));
pending = new PendingView("A", PendingBasketId(epoch), true, decided, 21_000, 23_000, z, false);
state = BasketState.PendingA;
intent = F($"IN ATTESA dell'esito della gamba A (ordine nel registro dalle {decided:HH:mm:ss} UTC)");
break;
}
case "blocked":
{
List<string> codes = [];
string reason;
if (features.MinutesToNextHigh is >= 0 and var m && m != int.MaxValue && m <= th.BlackoutBeforeMin)
{
codes.Add("blackout_before");
reason = F($"evento ad alto impatto fra {m} min (blackout {th.BlackoutBeforeMin})");
}
else if (features.MinutesSinceLastHigh is >= 0 and var s && s != int.MaxValue && s <= th.BlackoutAfterMin)
{
codes.Add("blackout_after");
reason = F($"evento ad alto impatto {s} min fa (blackout {th.BlackoutAfterMin})");
}
else
{
codes.Add("cost_gate");
cost = cost with { Passed = false, CostPips = 4.1, Reason = F($"TP {th.TpPips:F1} pip sotto {th.CostMultiple:F1}× il costo 4.1 pip (break-even 58%)") };
eval = eval with { CostPips = 4.1 };
reason = cost.Reason;
}
intent = F($"segnale (z {z:+0.00;-0.00}) ma NON ENTRO: {reason}");
decision = new DecisionView(DecisionKind.Skip, false, codes, intent, barClose, cost, null);
break;
}
case "samecross":
intent = F($"segnale (z {z:+0.00;-0.00}) ma NON ENTRO: un altro basket sullo stesso cross sintetico {cross.Symbol} è aperto");
decision = new DecisionView(DecisionKind.Skip, false, ["same_cross"], intent, barClose, cost, null);
break;
default:
intent = F($"|z| {Math.Abs(z):F2} sotto zIn {zInEffective:F2}; ρ {rho:+0.00;-0.00}, HL {halfLife:0}");
decision = new DecisionView(DecisionKind.Skip, false, ["no_signal"], intent, barClose, null, null);
break;
}
bool enabled = d.Enabled;
string disabledReason = enabled ? string.Empty : "disattivato nella strategia (Impostazioni ▸ Strategia)";
if (!enabled && position is null && pending is null)
{
intent = disabledReason;
decision = null;
}
else if (!enabled && position is not null)
{
intent = "IN POSIZIONE, basket disattivato: niente aggiunte, uscite attive — " + intent;
}
return new BasketView
{
Name = d.Name,
PairA = d.A,
PairB = d.B,
Cross = cross.Symbol,
SignB = cross.SignB,
Currencies = SyntheticCross.Currencies(d.A, d.B),
State = state,
Enabled = enabled,
Available = true,
DisabledReason = disabledReason,
Intent = intent,
LastDecision = decision,
Evaluation = eval,
Features = features,
PMl = pMl,
MlActive = false,
MlFeatures = ml,
Vol = vol,
SpreadMedianA = medianA,
SpreadMedianB = medianB,
PipA = pipA,
PipB = pipB,
TpPips = position?.TpPips ?? th.TpPips,
Position = position,
Pending = pending,
Recent = Recent(scenario, barClose, z, index),
};
}
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, SymbolSeries> Placeholders = new(StringComparer.OrdinalIgnoreCase);
/// <summary>An empty series per symbol, built once: the feature vector reads the context's numbers, never the bars.</summary>
private static SymbolSeries Placeholder(string symbol, long id) => Placeholders.GetOrAdd(symbol, s =>
new SymbolSeries(new Instrument(id, s, s, "Forex", PipMath.Pip(s), PipMath.Digits(s), 0, 0, 0, [1], true, true, 0, 0, string.Empty), TimeSpan.FromMinutes(15), 500));
private static PositionView OpenPosition(DateTime epoch, DateTime now, List<AccountPositionView> positions, Dictionary<string, Quote> q, Func<string, double?> mid, ThresholdsView th)
{
DateTime opened = epoch.AddMinutes(-90);
int bars = 6 + (int)((now - epoch).TotalMinutes / 15);
LegView a = Leg("A", "EURUSD", false, 43_000, 1.15612, 1.20, 3_104_555_001, q, mid, positions);
LegView b = Leg("B", "USDCHF", false, 49_000, 0.81950, 1.35, 3_104_555_002, q, mid, positions);
return new PositionView(OpenBasketId(epoch), false, opened, bars, 0, 2.14, 2.14, 3.1, 10, 3.5, 1, 2_085, 0.85, 139_010,
"VENDO il cross EURCHF: z +2.14 oltre ±2.00, ρ_W -0.72, ρ_20 -0.55, HL 31 barre; costo 3.1 pip, TP 10.0 = 3.2× il costo, break-even 45%; vol-parity: A 43000, B 49000 unità, perdita allo stop 695 USD (0.50 % dell'equity); gambe short EURUSD + short USDCHF",
0, 0, a, b);
}
private static LegView Leg(string name, string symbol, bool isBuy, double units, double entry, double fees, long positionId, Dictionary<string, Quote> q, Func<string, double?> mid, List<AccountPositionView> positions)
{
Quote x = q[symbol];
double exit = isBuy ? x.Bid : x.Ask;
double pips = (isBuy ? exit - entry : entry - exit) / x.Pip;
double pnl = PipMath.LegPnlUsd(symbol, isBuy, units, entry, exit, mid);
BrokerPosition? bp = positions.FirstOrDefault(p => p.Position.PositionId == positionId)?.Position;
LegVenueView? venue = bp is null ? null : new LegVenueView(bp.UnrealizedPnl, bp.Fees, bp.CurrentRate, bp.Margin, bp.Leverage);
return new LegView(name, symbol, x.Id, isBuy, units, units, entry, fees, 0, [positionId], x.Bid, x.Ask, pips, pnl, venue);
}
private static IReadOnlyList<RecentDecision> Recent(string scenario, DateTime barClose, double z, int index)
{
List<RecentDecision> rows = new(20);
for (int k = 19; k >= 0; k--)
{
DateTime at = barClose.AddMinutes(-15 * k);
double zk = z + (k * 0.035 * (index % 2 == 0 ? 1 : -1));
string evento = scenario switch
{
"open" => k > 6 ? (k == 7 ? "segnale_ingresso" : "skip") : "posizione",
"pending" => k == 0 ? "segnale_ingresso" : "skip",
_ => "skip",
};
string text = evento switch
{
"posizione" => F($"IN POSIZIONE — z {zk:+0.00;-0.00}"),
"segnale_ingresso" => F($"SEGNALE — z {zk:+0.00;-0.00} oltre la soglia"),
_ => F($"|z| {Math.Abs(zk):F2} sotto zIn 2.00"),
};
rows.Add(new RecentDecision(at, evento, zk, text));
}
return rows;
}
private static TodayClosedStats TodayUnits(IReadOnlyList<PositionRecord> history, DateTime now)
{
Dictionary<string, (double Net, bool Lone)> units = new(StringComparer.Ordinal);
foreach (PositionRecord p in history)
{
if (p.IsOpen || p.ClosedUtc is not { } closed || closed.Date != now.Date || p.Origin is not ("basket" or "orfana-bot"))
{
continue;
}
string key = p.Origin == "basket" && p.BasketId.Length > 0 ? p.BasketId : "#" + p.PositionId.ToString(CultureInfo.InvariantCulture);
(double net, _) = units.GetValueOrDefault(key);
units[key] = (net + p.PnlNetUsd, p.Origin != "basket");
}
return 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));
}
// -----------------------------------------------------------------------
// Calendar, headlines, sentiment, feeds
// -----------------------------------------------------------------------
/// <summary>The context of the scenario: a week of releases around the anchor, headlines of the last day, the sentiment, the sources.</summary>
public static ContextView Context(DateTime epoch, DateTime now)
{
double t = Seconds(epoch, now);
DateTime a = epoch;
CalendarEvent E(double hours, string ccy, string title, EventImpact impact, string forecast, string previous, string actual = "") =>
new(title, ccy, Anchor(a.AddHours(hours)), impact, forecast, previous, actual);
List<CalendarEvent> events =
[
E(-50, "AUD", "Retail Sales m/m", EventImpact.Medium, "0.3%", "0.5%", "0.4%"),
E(-30, "EUR", "German Ifo Business Climate", EventImpact.Medium, "88.9", "88.6", "89.2"),
E(-26, "USD", "CB Consumer Confidence", EventImpact.High, "96.0", "97.4", "95.1"),
E(-20, "JPY", "BOJ Core CPI y/y", EventImpact.Low, "2.1%", "2.0%", "2.1%"),
E(-6, "CHF", "KOF Economic Barometer", EventImpact.Medium, "101.2", "100.9", "101.7"),
E(-3, "EUR", "German Prelim CPI m/m", EventImpact.High, "0.2%", "0.1%", "0.3%"),
E(-1.5, "GBP", "Current Account", EventImpact.Low, "-18.2B", "-21.2B", "-17.9B"),
E(38.0 / 60, "USD", "Core PCE Price Index m/m", EventImpact.High, "0.2%", "0.3%"),
E(2.5, "CAD", "GDP m/m", EventImpact.Medium, "0.1%", "0.2%"),
E(5, "EUR", "ECB President Lagarde Speaks", EventImpact.High, string.Empty, string.Empty),
E(9, "NZD", "ANZ Business Confidence", EventImpact.Medium, string.Empty, "49.7"),
E(14, "AUD", "Employment Change", EventImpact.High, "25.0K", "24.5K"),
E(20, "CHF", "Bank Holiday", EventImpact.Holiday, string.Empty, string.Empty),
E(26, "USD", "ISM Manufacturing PMI", EventImpact.High, "49.2", "48.7"),
E(33, "CAD", "BOC Rate Statement", EventImpact.High, "2.50%", "2.75%"),
E(50, "USD", "Non-Farm Employment Change", EventImpact.High, "150K", "142K"),
E(52, "NZD", "RBNZ Rate Statement", EventImpact.High, "3.00%", "3.25%"),
];
(string Source, string Title, string[] Ccy, double Net, double Hawk, double RiskOff)[] headlines =
[
("ForexLive", "EUR/USD holds 1.1550 ahead of US PCE data", ["EUR", "USD"], 0.10, 0.00, -0.05),
("FXStreet", "Swiss franc steadies as SNB signals patience on rates", ["CHF"], 0.20, -0.30, 0.10),
("ECB", "ECB: monetary policy decisions — rates unchanged", ["EUR"], 0.00, 0.20, 0.00),
("Google News RBA", "Reserve Bank of Australia keeps cash rate on hold, warns on inflation", ["AUD"], -0.10, 0.60, 0.00),
("Fed", "Federal Reserve Board announces approval of application", ["USD"], 0.00, 0.00, 0.00),
("ForexLive", "Canadian dollar slips as oil extends decline", ["CAD"], -0.40, 0.00, 0.20),
("Google News RBNZ", "RBNZ expected to cut again as economy stalls", ["NZD"], -0.50, -0.70, 0.10),
("FXStreet", "USD/JPY: yen weakens past 148 on wide yield gap", ["USD", "JPY"], 0.30, 0.10, -0.20),
("Google News forex", "Dollar edges higher as traders await inflation figures", ["USD"], 0.25, 0.20, -0.10),
("BoC", "Bank of Canada releases Business Outlook Survey", ["CAD"], -0.20, -0.10, 0.00),
("Google News EURUSD", "Euro supported by stronger German inflation print", ["EUR"], 0.40, 0.30, -0.10),
("FXStreet", "Risk appetite fades as equities slip; havens bid", ["CHF", "JPY"], -0.30, 0.00, 0.60),
];
List<ScoredItem> news = [];
for (int i = 0; i < headlines.Length; i++)
{
(string source, string title, string[] ccy, double net, double hawk, double off) = headlines[i];
DateTime published = a.AddMinutes(-(7 + (i * 83)));
string slug = string.Concat(title.ToLowerInvariant().Where(static ch => char.IsLetterOrDigit(ch) || ch == ' '));
news.Add(new ScoredItem(new NewsItem(published, source, title, title, "https://example.org/notizie/" + slug.Replace(' ', '-')), net, hawk, off, ccy));
}
double minute = Math.Floor(t / 60);
List<CurrencySentiment> sentiment = [];
foreach (string c in ContextView.SentimentCurrencies)
{
int i = Array.IndexOf(ContextView.SentimentCurrencies, c);
List<ScoredItem> mine = [.. news.Where(n => n.Currencies.Contains(c))];
double net = mine.Count > 0 ? mine.Average(static n => n.Net) : 0;
double hawk = mine.Count > 0 ? mine.Average(static n => n.Hawkish) : 0;
sentiment.Add(new CurrencySentiment(c, Math.Round(net + Wave(minute, 7, 0.03, i), 3), Math.Round(net * 0.8, 3), Math.Round(net * 0.5, 3), Math.Round(hawk, 3), 0.05, mine.Count + 3 + i));
}
List<FeedSourceState> feeds = [];
foreach (FeedSource s in FeedContextProvider.DefaultSources())
{
bool failing = s.Name == "Google News SNB";
DateTime lastRequest = Anchor(now.AddMinutes(-(t / 60 % 10)));
feeds.Add(new FeedSourceState(s.Name, s.Kind == "calendar-json" ? "calendar" : "rss", s.Currency, s.Url.Host, lastRequest,
failing ? a.AddHours(-7) : lastRequest, failing ? 3 : 0, failing ? lastRequest.AddMinutes(16) : null, true, failing ? "HTTP 503" : string.Empty));
}
DateTime refreshed = Anchor(now.AddMinutes(-(t / 60 % 10)));
return new ContextView
{
PublishedUtc = Anchor(now),
CalendarUpdatedUtc = refreshed,
CalendarState = F($"aggiornato {refreshed:HH:mm} UTC, {events.Count} eventi in memoria, 0 nuovi"),
NewsUpdatedUtc = refreshed,
NewsState = F($"{news.Count} notizie nelle ultime 30 h da 12 feed, ultimo aggiornamento {refreshed:HH:mm} UTC"),
Events = events,
News = news,
Sentiment = sentiment,
SentimentUtc = Anchor(now),
RiskOff4h = Math.Round(0.12 + Wave(minute, 11, 0.02), 3),
Feeds = feeds,
};
}
// -----------------------------------------------------------------------
// Host side: Telegram and the secrets
// -----------------------------------------------------------------------
public static TelegramStatus Telegram(DateTime epoch, DateTime now)
{
int hours = (int)Math.Max(0, (now - epoch).TotalHours);
return new TelegramStatus(true, true, true, true, true, true, true, 21, "123456789", 0, 42 + hours, 1, epoch.AddMinutes(-12).AddHours(hours), string.Empty);
}
public static SecretsSummary Secrets(DateTime epoch) => new(
"open",
new SecretInfo(true, "a1b2…", epoch.AddDays(-12)),
SecretInfo.None,
new SecretInfo(true, "7412…", epoch.AddDays(-12)),
InterfacePassword.Variable,
[],
string.Empty,
string.Empty);
// -----------------------------------------------------------------------
// Storico
// -----------------------------------------------------------------------
/// <summary>The closed baskets of the last weeks (both legs, net of fees), a lone leg, a foreign trade, the open positions, and the order lines behind them.</summary>
public static (List<PositionRecord> Positions, List<OrderRecord> Orders) History(DateTime epoch, DateTime now)
{
Random rng = new(42);
string[] names = ["EURUSD/USDCHF", "AUDUSD/USDCAD", "NZDUSD/EURNZD", "USDCAD/EURUSD", "EURAUD/AUDCAD"];
List<PositionRecord> rows = [];
List<OrderRecord> orders = [];
long nextId = 3_104_400_000;
for (int k = 0; k < 40; k++)
{
string basket = names[k % names.Length];
string[] pairs = basket.Split('/');
DateTime closed = epoch.AddMinutes(-(35 + (k * 419)));
DateTime opened = closed.AddMinutes(-(45 + rng.Next(0, 600)));
string basketId = string.Create(CultureInfo.InvariantCulture, $"B{opened:yyyyMMddHHmmss}-{basket.Replace("/", string.Empty, StringComparison.Ordinal)}");
bool win = rng.NextDouble() < 0.52;
double net = win ? 40 + (rng.NextDouble() * 220) : -(30 + (rng.NextDouble() * 260));
bool buy = rng.NextDouble() < 0.5;
string exit = win ? (rng.NextDouble() < 0.6 ? "tp_pips" : "tp_z") : (rng.NextDouble() < 0.5 ? "stop_z" : "time_stop");
for (int leg = 0; leg < 2; leg++)
{
string symbol = pairs[leg];
double level = Instruments.First(i => i.Symbol == symbol).Mid;
double pip = PipMath.Pip(symbol);
double share = leg == 0 ? 0.62 : 0.38;
double fees = Math.Round(1 + (rng.NextDouble() * 1.5), 2);
double legNet = Math.Round(net * share, 2);
double openRate = Math.Round(level * (1 + ((rng.NextDouble() - 0.5) * 0.004)), PipMath.Digits(symbol));
double pips = Math.Round((legNet + fees) / 4.3, 1);
bool isBuy = leg == 0 ? buy : buy;
double closeRate = Math.Round(openRate + ((isBuy ? 1 : -1) * pips * pip), PipMath.Digits(symbol));
long id = nextId++;
rows.Add(new PositionRecord(id, symbol, isBuy, 40_000 + (leg * 6_000), openRate, closeRate, opened, closed, legNet + fees, fees, legNet, pips, "basket", basketId, basket, exit, false, string.Empty));
orders.Add(new OrderRecord(opened, RunId, "Demo", basket, basketId, symbol, Instruments.First(i => i.Symbol == symbol).Id, isBuy, leg == 0 ? OrderLeg.A : OrderLeg.B,
40_000 + (leg * 6_000), 40_000 + (leg * 6_000), openRate, openRate, 0.1, "Executed", 3, OrderResolution.Filled, 90_000_000 + id % 1_000_000, id,
string.Create(CultureInfo.InvariantCulture, $"sample-{id}"), fees, "risolto", "eseguito"));
}
}
// A lone leg the bot closed (an unwind) and a trade someone else made.
rows.Add(new PositionRecord(nextId++, "EURAUD", true, 21_000, 1.74810, 1.74770, epoch.AddHours(-30), epoch.AddHours(-30).AddMinutes(2), -12.10, 1.40, -13.50, -4.0, "orfana-bot",
string.Empty, "EURAUD/AUDCAD", "leg_risk_unwind", false, "gamba A richiusa: seconda gamba rifiutata"));
rows.Add(new PositionRecord(nextId, "GBPUSD", false, 10_000, 1.34900, 1.34420, epoch.AddDays(-6), epoch.AddDays(-4), 48.00, 2.20, 45.80, 48.0, "esterna",
string.Empty, string.Empty, string.Empty, false, "posizione non aperta dal bot"));
// The open positions of the moment.
Dictionary<string, Quote> q = Quotes(Seconds(epoch, now));
foreach (AccountPositionView p in Positions(epoch, now, q, MidOf(q)))
{
BrokerPosition bp = p.Position;
double pips = p.Pip > 0 ? (bp.IsBuy ? bp.CurrentRate - bp.OpenRate : bp.OpenRate - bp.CurrentRate) / p.Pip : double.NaN;
rows.Add(new PositionRecord(bp.PositionId, p.Symbol, bp.IsBuy, bp.Units, bp.OpenRate, bp.CurrentRate, bp.OpenedUtc, null, bp.UnrealizedPnl + bp.Fees, bp.Fees, bp.UnrealizedPnl, pips,
p.OriginName, p.BasketId, p.Basket, string.Empty, true, "aperta: P&L corrente"));
}
rows.Sort(static (x, y) => (y.ClosedUtc ?? DateTime.MaxValue).CompareTo(x.ClosedUtc ?? DateTime.MaxValue));
return (rows, orders);
}
// -----------------------------------------------------------------------
// Log
// -----------------------------------------------------------------------
/// <summary>One line of the sample log.</summary>
public sealed record LogLine(DateTime TimeUtc, string Level, string Source, string Message);
private static readonly (string Level, string Source, string Message)[] LogTemplates =
[
("info", "BasketEngine", "[{0}] barra {1:HH:mm} chiusa: bid {2} ask {3} (212 quote)"),
("info", "BasketEngine", "[AUDUSD/USDCAD] |z| 0.42 sotto zIn 2.00; ρ -0.61, HL 44"),
("info", "BasketEngine", "[EURUSD/USDCHF] IN POSIZIONE — +3.1 pip, netto +18.40 USD, z +1.62 (entrata +2.14), 7/96 barre"),
("warn", "BasketEngine", "[NZDUSD/EURNZD] segnale (z -2.31) ma NON ENTRO: evento ad alto impatto fra 38 min (blackout 45)"),
("info", "BasketEngine", "[stato] Demo · equity 139246.18 (saldo 139200.00, aperto +46.18, oggi +150.00) · DD 0.61% dal picco 140100.00 · basket aperti 1/3, in attesa 1, ordini pendenti 1"),
("warn", "Feeds", "feed Google News SNB: HTTP 503 (secondo errore: ritento con attese crescenti, uso la cache)"),
("info", "BasketEngine", "registro ordini: ordine A EURAUD/AUDCAD senza esito, verifica 4 (Unknown)"),
("warn", "BasketEngine", "GAMBA ORFANA del bot: posizione 3104551234 su NZDUSD (long 12000 @ 0.58321, P&L -21.40) — firma del bot; in attesa della bonifica"),
("info", "NotifierHub", "Telegram attivo: chat 123456789, stato orario sì, eventi sì, riepilogo alle 21:00 UTC, comandi sì"),
("error", "BasketEngine", "storico delle chiusure non letto: eToro non raggiungibile (GET api/v1/trading/info/trade/demo/history): timeout\n at Encelado.Etoro.EtoroHttp.SendAsync\n at Encelado.Engine.Baskets.BasketEngine.ReadHistoryAsync"),
("info", "BasketEngine", "[EURAUD/AUDCAD] SEGNALE — COMPRO il cross EURCAD: z -2.37 oltre ±2.00"),
("info", "LearningState", "bandit (solo proposta, non applicata): propone MODERATE nel terzile di vol 1"),
];
/// <summary>The log of the last hour before the anchor (for the Log page and the dashboard's strip).</summary>
public static IReadOnlyList<LogLine> LogBacklog(DateTime epoch, int count = 150)
{
List<LogLine> lines = new(count);
for (int i = count - 1; i >= 0; i--)
{
lines.Add(NextLogLine(count - 1 - i, epoch.AddSeconds(-24 * i)));
}
return lines;
}
/// <summary>The <paramref name="n"/>-th line of the rotating sample log, stamped <paramref name="timeUtc"/>.</summary>
public static LogLine NextLogLine(long n, DateTime timeUtc)
{
(string level, string source, string message) = LogTemplates[(int)(n % LogTemplates.Length)];
if (message.Contains("{0}", StringComparison.Ordinal))
{
(string symbol, _, double mid, _, _) = Instruments[(int)(n % Instruments.Length)];
DateTime bar = BarClose(timeUtc);
message = string.Format(CultureInfo.InvariantCulture, message, symbol, bar, Math.Round(mid, 5), Math.Round(mid + (PipMath.Pip(symbol) * 0.8), 5));
}
return new LogLine(timeUtc, level, source, message);
}
}