Run the strategies live in simulation with the live engine (refs #47)

The live engine makes each decision at its time of SPEC 5.5 through the
same DecideOnce call the backtest uses, so live and backtest cannot drift:
the crypto close at 00:05 UTC, the stock signals 20 minutes after the
close, the meanrev exits 5 minutes before it, the stock orders and the
daily stops at the open. Each decision has a run key written in the same
transaction as its decision rows, planned orders and diary lines, and each
planned order's id gives the order key, so a restart never decides or
sends anything twice. Entries recovered late are dropped when the price
has moved too far.

The engine runs from the scheduler once the accounts are reconciled. The
IEX stream follows held stocks, planned orders and SPY during the session,
and the stock simulator's day orders now expire at the close.

Tests: parity with the backtest for crypto_trend (40 days) and
equity_meanrev (6 weeks), and a 14-day run with the network down, a lost
answer, a restart mid-order and the database unreachable, ending
reconciled with no duplicate orders, on SQLite and PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:28:08 +01:00
1 parent 98ee504dab
commit 41e067e7d1
13 files changed
+2073 -5

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The live engine in simulation (issue #47, SPEC 5.5, 5.6, 12.3, 17 phase 6).</summary>
[TestClass]
public sealed class LiveEngineTests
{
private static readonly DateOnly LiveFrom = new(2026, 9, 1);
[TestMethod]
public async Task TheLiveEngineMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(39);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.DayAsync(day).ConfigureAwait(false);
}
// The backtest decides on the close of the day before the first live morning and fills on the live days, with
// the same correctives (crypto regime) and the same risk stage.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic path should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// Every decision was written once, with its run key.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
Assert.HasCount(40, runs);
Assert.AreEqual(0, live.Failures);
}
/// <summary>
/// The stock side (SPEC 5.5): equity_meanrev decides after the close, buys at the next open, leaves five minutes
/// before the close; the trades are the backtest's, which buys at the open and sells at the close.
/// </summary>
[TestMethod]
public async Task TheStockSideMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(41);
await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.SessionAsync(day).ConfigureAwait(false);
}
var run = live.Backtest(StrategyNames.EquityMeanrev, LiveFrom.AddDays(-1), last);
var expected = LiveRig.Grouped(run, LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic stocks should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// One decision per session, each written once: the close of the day before the first one included, made at the
// first start as a recovered decision.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
var sessions = WeekdayCalendar.Sessions(LiveFrom.AddDays(-1), last).Count();
Assert.HasCount(sessions, runs.Where(r => r.StartsWith(StrategyNames.EquityMeanrev + ":", StringComparison.Ordinal)).ToList());
}
/// <summary>
/// SPEC 17 phase 6: an accelerated run of at least 10 market days with faults injected (network, a restart
/// halfway through an order, the database unreachable) ends with ledger and account reconciled and no order sent
/// twice; the trades are still the backtest's.
/// </summary>
[TestMethod]
public async Task TenDaysWithFaultsEndReconciledWithoutDuplicateOrders()
{
var last = LiveFrom.AddDays(13);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
var restarted = false;
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
var index = day.DayNumber - LiveFrom.DayNumber;
Func<int, Task>? faults = index switch
{
// Network down for the first minutes of the decision: no quotes, no broker. When it comes back, the
// answer to the first order is lost on the way back.
0 => minute =>
{
live.Rig.QuotesDown = live.Broker.Down = minute < 4;
if (minute == 4)
{
live.Broker.LoseNextAnswer = true;
}
return Task.CompletedTask;
}
,
// The process dies with a purchase working at the broker and starts again.
11 => async minute =>
{
if (!restarted && await live.WorkingOrdersAsync().ConfigureAwait(false) > 0)
{
restarted = true;
await live.RestartAsync().ConfigureAwait(false);
}
}
,
// The database cannot be reached around the decision.
12 => minute =>
{
live.DatabaseDown = minute < 6;
return Task.CompletedTask;
}
,
_ => null,
};
await live.DayAsync(day, faults).ConfigureAwait(false);
if (index == 0)
{
Assert.IsFalse(live.Broker.LoseNextAnswer, "An answer must have been lost.");
}
}
Assert.IsTrue(restarted, "The run must restart halfway through an order.");
Assert.AreEqual(1, live.Restarts);
Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work.");
// The trades are the backtest's: the faults delayed them by minutes, never changed or repeated them.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// No order twice: one order per client id, one execution per order key, one decision per run key.
var orders = await live.Rig.QueryAsync("SELECT client_order_id FROM orders", r => r.Text("client_order_id")).ConfigureAwait(false);
Assert.HasCount(orders.Distinct(StringComparer.Ordinal).Count(), orders);
foreach (var id in live.Sent.Select(r => r.ClientOrderId).Distinct(StringComparer.Ordinal))
{
Assert.Contains(id, orders, "Every order sent is in the ledger.");
}
var keys = await live.Rig.QueryAsync("SELECT order_key FROM executions", r => r.Text("order_key")).ConfigureAwait(false);
Assert.HasCount(keys.Distinct(StringComparer.Ordinal).Count(), keys);
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(14, runs.Distinct(StringComparer.Ordinal));
Assert.HasCount(14, runs);
// Ledger and account agree; the account may keep dust below the lot that the ledger wrote off (SPEC 7.2).
var report = await live.Reconciler.ReconcileAsync(live.Manager, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences));
var ledger = (await live.Rig.Ledger.PositionsAsync(live.Okx.AccountId, CancellationToken.None).ConfigureAwait(false))
.Where(p => p.Quantity != 0m)
.GroupBy(p => p.InstrumentId).ToDictionary(g => live.Instruments.Values.Single(i => i.Id == g.Key).Symbol, g => g.Sum(p => p.Quantity), StringComparer.Ordinal);
var account = (await live.Paper.GetPositionsAsync(CancellationToken.None).ConfigureAwait(false)).Where(p => p.Quantity != 0m)
.ToDictionary(p => p.Symbol, p => p.Quantity, StringComparer.Ordinal);
CollectionAssert.AreEquivalent(account.Where(a => a.Value >= (live.Instruments[a.Key].Spec.LotSize ?? 0m)).Select(a => a.Key).ToList(), ledger.Keys.ToList());
foreach (var (symbol, quantity) in account.Where(a => ledger.ContainsKey(a.Key)))
{
Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol);
}
}
}
+217
View File
@@ -0,0 +1,217 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>Every weekday is a session, 9:30–16:00 in New York (13:30–20:00 UTC in September and October).</summary>
internal sealed class WeekdayCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day) => day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday
? null
: new MarketSession(day, new DateTimeOffset(day.ToDateTime(new TimeOnly(13, 30)), TimeSpan.Zero), new DateTimeOffset(day.ToDateTime(new TimeOnly(20, 0)), TimeSpan.Zero));
public static IEnumerable<DateOnly> Sessions(DateOnly from, DateOnly to)
{
for (var day = from; day <= to; day = day.AddDays(1))
{
if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
{
yield return day;
}
}
}
}
/// <summary>
/// The stock side of the live engine on the internal Alpaca simulator (issue #47, SPEC 5.5): signals after the close,
/// the orders at the next open, the exits of equity_meanrev five minutes before the close, with synthetic stocks that
/// dip for three sessions and recover.
/// </summary>
internal sealed class StockRig : IAsyncDisposable
{
public static readonly string[] Stocks = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"];
/// <summary>Dollars for a euro: the capital is entrusted in euro (SPEC 7.1).</summary>
public const decimal Rate = 1.10m;
private readonly Dictionary<string, Instrument> _instruments = new(StringComparer.Ordinal);
private readonly WeekdayCalendar _calendar = new();
private StockRig(TradingRig rig) => Rig = rig;
public TradingRig Rig { get; }
public AccountContext Alpaca { get; private set; } = null!;
public PaperBroker Paper { get; private set; } = null!;
public OrderManager Manager { get; private set; } = null!;
public LiveEngine Engine { get; private set; } = null!;
public EquityBook Equity { get; private set; } = null!;
public Dictionary<string, List<DailyBar>> Bars { get; } = new(StringComparer.Ordinal);
public static async Task<StockRig> CreateAsync(DateOnly liveFrom, DateOnly last, string strategy = StrategyNames.EquityMeanrev, decimal capital = 10_000m)
{
var rig = new StockRig(await TradingRig.CreateAsync().ConfigureAwait(false));
await rig.SetUpAsync(liveFrom, last, strategy, capital).ConfigureAwait(false);
return rig;
}
private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, string strategy, decimal capital)
{
var none = CancellationToken.None;
Rig.Clock.Set(new DateTimeOffset(liveFrom.AddDays(-1).ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero));
Alpaca = await Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
var sessions = WeekdayCalendar.Sessions(last.AddDays(-700), last).ToList();
var store = new BarStore(Rig.Db, Rig.Clock);
var members = new List<UniverseMember>();
for (var i = 0; i < Stocks.Length; i++)
{
var symbol = Stocks[i];
_instruments[symbol] = await Rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false);
Bars[symbol] = Path(sessions, 50 + (i * 20), phase: i * 3, seed: (uint)(i + 11));
members.Add(new UniverseMember(_instruments[symbol].Id, symbol, i + 1, 1e9));
}
_instruments[StrategyNames.MarketSymbol] = await Rig.InstrumentAsync(TradingRig.Stock(StrategyNames.MarketSymbol) with { IsFund = true }).ConfigureAwait(false);
Bars[StrategyNames.MarketSymbol] = Path(sessions, 400, phase: 5, seed: 3, dips: false);
foreach (var (symbol, bars) in Bars)
{
await store.UpsertDailyAsync(_instruments[symbol].Id, bars.Where(b => b.Day < liveFrom), "test", none).ConfigureAwait(false);
}
await new UniverseStore(Rig.Db, Rig.Clock).SaveAsync(Universes.Equity, liveFrom.AddDays(-30), members, none).ConfigureAwait(false);
await Rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)",
none, ("id", Ids.NewId(Rig.Clock)), ("s", strategy), ("a", Alpaca.AccountId), ("st", StrategyStages.Simulation), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none)
.ConfigureAwait(false);
var fx = new FxStore(Rig.Db, Rig.Clock);
await fx.UpsertAsync(WeekdayCalendar.Sessions(liveFrom.AddDays(-10), last).Select(d => new FxRate("EUR", "USD", d, Rate, "test")), none).ConfigureAwait(false);
await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Alpaca, capital, "test", none).ConfigureAwait(false);
Paper = Rig.Paper(PaperOptions.Alpaca(), Alpaca.AccountId);
await Paper.DepositAsync(capital * Rate, "USD", none).ConfigureAwait(false);
Manager = Rig.Manager(Paper, Alpaca);
var stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar);
Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx);
}
/// <summary>
/// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the
/// close under its 5-session average, so equity_meanrev buys and sells a few sessions later.
/// </summary>
public static List<DailyBar> Path(IReadOnlyList<DateOnly> sessions, double start, int phase, uint seed, bool dips = true)
{
var bars = new List<DailyBar>(sessions.Count);
var price = start;
var state = (seed * 2654435761u) + 1u;
double Next()
{
state = (state * 1664525u) + 1013904223u;
return (state >> 8) / (double)(1 << 24);
}
for (var i = 0; i < sessions.Count; i++)
{
var cycle = (i + phase) % 17;
var change = dips && cycle >= 14 ? -0.025 : (dips ? 0.008 : 0.003) + ((Next() - 0.5) * 0.012);
var open = Math.Round(price * (1 + ((Next() - 0.5) * 0.004)), 2);
var close = Math.Round(open * (1 + change), 2);
var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.006)), 2);
var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.006)), 2);
bars.Add(new DailyBar(sessions[i], open, high, low, close, 5_000_000));
price = close;
}
return bars;
}
private DailyBar? Bar(string symbol, DateOnly day) => Bars[symbol].SingleOrDefault(b => b.Day == day);
private void Quotes(DateOnly day, Func<DailyBar, double> pick)
{
foreach (var symbol in Bars.Keys)
{
if (Bar(symbol, day) is { } bar)
{
var price = (decimal)pick(bar);
Rig.Quote(symbol, price - 0.01m, price + 0.01m, 1000m);
}
}
}
private async Task MinutesAsync(int count)
{
for (var i = 0; i < count; i++)
{
await Engine.PulseAsync(CancellationToken.None).ConfigureAwait(false);
await Rig.TurnsAsync(Manager, 1, TimeSpan.FromMinutes(1)).ConfigureAwait(false);
}
}
/// <summary>
/// One session: the orders decided last night go at 9:35 with the open as price; at midday the quotes touch the
/// low (stops); at 15:55 the price is the close and the meanrev exits leave; at 16:16 the bar of the day arrives and
/// at 16:20 the signals are computed; the day orders expire and the equity is photographed.
/// </summary>
public async Task SessionAsync(DateOnly day)
{
if (_calendar.SessionOn(day) is not { } session)
{
return;
}
var none = CancellationToken.None;
Rig.Clock.Set(session.OpenUtc.AddMinutes(5));
Quotes(day, b => b.Open);
await MinutesAsync(15).ConfigureAwait(false);
Rig.Clock.Set(session.OpenUtc.AddHours(3));
Quotes(day, b => b.Low);
await MinutesAsync(3).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(-5));
Quotes(day, b => b.Close);
await MinutesAsync(4).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(1));
await Paper.ExpireDayOrdersAsync(none).ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(16));
await Task.WhenAll(Bars.Select(b => new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[b.Key].Id, b.Value.Where(x => x.Day == day), "test", none)))
.ConfigureAwait(false);
Rig.Clock.Set(session.CloseUtc.AddMinutes(20));
await MinutesAsync(3).ConfigureAwait(false);
foreach (var symbol in Stocks)
{
await Rig.Ledger.MarkAsync(_instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false);
}
await Equity.TakeAsync(none).ConfigureAwait(false);
}
public BacktestRun Backtest(string strategy, DateOnly from, DateOnly to, decimal capital = 10_000m * Rate)
{
var instruments = Bars.Select(b => new BacktestInstrument(_instruments[b.Key].Spec, b.Value.Where(x => x.Day <= to && x.Day >= to.AddDays(-700)).ToList()));
var calendar = Bars[Stocks[0]].Select(b => b.Day).Where(d => d <= to.AddDays(14));
var data = new BacktestDataset(instruments, "USD", calendar, [StrategyNames.MarketSymbol]);
var options = StrategyPipeline.For(strategy, data, new BacktestOptions { InitialCapital = capital, From = from, To = to });
return BacktestEngine.Run(LiveEngine.CreateStrategy(strategy, null), data, options);
}
/// <summary>The live fills by New York day, symbol and side.</summary>
public async Task<IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)>> LiveFillsAsync()
{
var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at",
r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false);
return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))];
}
public ValueTask DisposeAsync()
{
Engine.Dispose();
return Rig.DisposeAsync();
}
}
+287
View File
@@ -0,0 +1,287 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The live engine on the internal simulator, driven by a manual clock through synthetic days (issue #47): the bars
/// of each day arrive at its end, the quotes follow the open, the low and the close of the day, and the engine and
/// the order manager work minute by minute. The same bars run through the backtest for the parity test; the broker,
/// the quotes and the database can fail, and the process can restart, for the fault run.
/// </summary>
internal sealed class LiveRig : IAsyncDisposable
{
public static readonly string[] Coins = ["BTC-EUR", "ETH-EUR", "SOL-EUR"];
private readonly Dictionary<string, Instrument> _instruments = new(StringComparer.Ordinal);
private readonly List<OrderRequest> _sent = [];
private LiveRig(TradingRig rig) => Rig = rig;
public TradingRig Rig { get; }
public AccountContext Okx { get; private set; } = null!;
public PaperBroker Paper { get; private set; } = null!;
/// <summary>The simulator behind a broker that can lose answers or go down (network faults).</summary>
public FaultyBroker Broker { get; private set; } = null!;
public OrderManager Manager { get; private set; } = null!;
public StageBook Stages { get; private set; } = null!;
public LiveEngine Engine { get; private set; } = null!;
public EquityBook Equity { get; private set; } = null!;
public Reconciler Reconciler { get; private set; } = null!;
public Dictionary<string, List<DailyBar>> Bars { get; } = new(StringComparer.Ordinal);
public IReadOnlyDictionary<string, Instrument> Instruments => _instruments;
/// <summary>Work that failed as the scheduler would see it: a pulse or a turn during a fault.</summary>
public int Failures { get; private set; }
public int Restarts { get; private set; }
/// <summary>Every order request that reached the broker, across restarts.</summary>
public IReadOnlyList<OrderRequest> Sent => [.. _sent, .. Broker.Sent];
/// <summary>Every new database connection fails while this is true.</summary>
public bool DatabaseDown
{
get => Rig.Db.Unreachable;
set => Rig.Db.Unreachable = value;
}
/// <summary>
/// <paramref name="days"/> synthetic daily bars for each coin up to <paramref name="last"/>; those before
/// <paramref name="liveFrom"/> are stored at once, the others arrive one per day.
/// </summary>
public static async Task<LiveRig> CreateAsync(DateOnly liveFrom, DateOnly last, int days = 700, string stage = StrategyStages.Simulation, decimal capital = 10_000m)
{
var rig = new LiveRig(await TradingRig.CreateAsync().ConfigureAwait(false));
await rig.SetUpAsync(liveFrom, last, days, stage, capital).ConfigureAwait(false);
return rig;
}
private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, int days, string stage, decimal capital)
{
var none = CancellationToken.None;
Rig.Clock.Set(new DateTimeOffset(liveFrom.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero));
Okx = await Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
var store = new BarStore(Rig.Db, Rig.Clock);
var seed = 7u;
foreach (var (symbol, start) in new[] { ("BTC-EUR", 30000.0), ("ETH-EUR", 2000.0), ("SOL-EUR", 60.0) })
{
var spec = MarketDataStoreTests.Okx(symbol) with { ListedAt = null };
_instruments[symbol] = await Rig.InstrumentAsync(spec).ConfigureAwait(false);
Bars[symbol] = Synthetic(last.AddDays(1 - days), days, start, seed++);
await store.UpsertDailyAsync(_instruments[symbol].Id, Bars[symbol].Where(b => b.Day < liveFrom.AddDays(-1)), "test", none).ConfigureAwait(false);
}
await Rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)",
none, ("id", Ids.NewId(Rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none)
.ConfigureAwait(false);
var fx = new FxStore(Rig.Db, Rig.Clock);
await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Okx, capital, "test", none).ConfigureAwait(false);
Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId);
await Paper.DepositAsync(capital, "EUR", none).ConfigureAwait(false);
Stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx);
Reconciler = new Reconciler(Rig.Db, Rig.Clock, Rig.Ledger);
Build();
}
private void Build()
{
Broker = new FaultyBroker(Paper);
Manager = Rig.Manager(Broker, Okx);
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync);
}
/// <summary>
/// The process dies and starts again: a new simulator on its saved book, a new order manager and engine on the same
/// database, the account reconciled before the first pulse as at a real start (SPEC 9.4).
/// </summary>
public async Task RestartAsync()
{
_sent.AddRange(Broker.Sent);
Engine.Dispose();
Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId);
Build();
Restarts++;
await Reconciler.ReconcileAsync(Manager, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// A deterministic path with regimes: long rises, falls and flat stretches with noise, so the trend strategy enters,
/// moves its stops and leaves. The open of each day is the close of the day before; the volume makes the coin
/// liquid enough for the universe.
/// </summary>
public static List<DailyBar> Synthetic(DateOnly first, int days, double start, uint seed)
{
var bars = new List<DailyBar>(days);
var price = start;
var state = (seed * 2654435761u) + 1u;
double Next()
{
state = (state * 1664525u) + 1013904223u;
return (state >> 8) / (double)(1 << 24);
}
for (var i = 0; i < days; i++)
{
var regime = ((i / 45) + (int)seed) % 4;
var drift = regime switch { 0 => 0.009, 1 => -0.008, 2 => 0.002, _ => 0.012 };
var change = drift + ((Next() - 0.5) * 0.04);
var open = price;
var close = Math.Round(price * (1 + change), 2);
var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.01)), 2);
var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.01)), 2);
bars.Add(new DailyBar(first.AddDays(i), open, high, low, close, 50_000_000 / close));
price = close;
}
return bars;
}
public DailyBar Bar(string symbol, DateOnly day) => Bars[symbol].Single(b => b.Day == day);
/// <summary>The bar of a day reaches the database, as the history step stores it after midnight.</summary>
public Task StoreBarAsync(DateOnly day) => Task.WhenAll(Coins.Select(c =>
new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[c].Id, Bars[c].Where(b => b.Day == day), "test", CancellationToken.None)));
public void Quotes(DateOnly day, Func<DailyBar, double> pick)
{
foreach (var coin in Coins)
{
var price = (decimal)pick(Bar(coin, day));
Rig.Quote(coin, price * 0.9999m, price * 1.0001m, 1000m);
}
}
/// <summary>
/// One UTC day, minute by minute where it matters: yesterday's bar arrives, from 00:05 the engine pulses every
/// minute with the open as price and the orders are worked; at noon the quotes go to the day's low (stops), at the
/// end of the day to the close, where positions are valued and the equity photographed. <paramref name="minute"/>
/// runs before each morning minute with its index: the fault tests break and mend things there.
/// </summary>
public async Task DayAsync(DateOnly day, Func<int, Task>? minute = null, int morning = 20)
{
var none = CancellationToken.None;
var midnight = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
Rig.Clock.Set(midnight.AddMinutes(1));
await StoreBarAsync(day.AddDays(-1)).ConfigureAwait(false);
Rig.Clock.Set(midnight.AddMinutes(5));
Quotes(day, b => b.Open);
for (var i = 0; i < morning; i++)
{
if (minute is not null)
{
await minute(i).ConfigureAwait(false);
}
await MinuteAsync().ConfigureAwait(false);
}
Rig.Clock.Set(midnight.AddHours(12));
Quotes(day, b => b.Low);
for (var i = 0; i < 3; i++)
{
await MinuteAsync().ConfigureAwait(false);
}
Rig.Clock.Set(midnight.AddHours(23).AddMinutes(55));
Quotes(day, b => b.Close);
for (var i = 0; i < 2; i++)
{
await MinuteAsync().ConfigureAwait(false);
}
foreach (var coin in Coins)
{
await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false);
}
await Equity.TakeAsync(none).ConfigureAwait(false);
}
/// <summary>One minute of the process: the engine's pulse, then a turn of the simulator and of the order manager.</summary>
private async Task MinuteAsync()
{
await SafeAsync(() => Engine.PulseAsync(CancellationToken.None)).ConfigureAwait(false);
await SafeAsync(async () =>
{
Rig.Refresh();
await Paper.PumpAsync(CancellationToken.None).ConfigureAwait(false);
await Manager.TickAsync(CancellationToken.None).ConfigureAwait(false);
}).ConfigureAwait(false);
Rig.Clock.Advance(TimeSpan.FromMinutes(1));
}
/// <summary>A failure the scheduler would log and retry at the next run: counted, never thrown.</summary>
private async Task SafeAsync(Func<Task> work)
{
try
{
await work().ConfigureAwait(false);
}
catch (Exception ex) when (ex is System.Data.Common.DbException or BrokerException)
{
Failures++;
}
}
/// <summary>Orders other than the protective stops still working at the simulator.</summary>
public async Task<int> WorkingOrdersAsync() =>
(await Paper.GetOpenOrdersAsync(CancellationToken.None).ConfigureAwait(false)).Count(o => o.StopPrice is null);
/// <summary>The same bars through the backtest, with the same correctives and risk stage, from <paramref name="from"/>.</summary>
public BacktestRun Backtest(DateOnly from, DateOnly to, decimal capital = 10_000m)
{
var data = new BacktestDataset(Coins.Select(c => new BacktestInstrument(_instruments[c].Spec, Bars[c].Where(b => b.Day <= to).ToList())), "EUR");
var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = capital, From = from, To = to });
return BacktestEngine.Run(LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, options);
}
/// <summary>The backtest fills from <paramref name="from"/>, by day, symbol and side.</summary>
public static List<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> Grouped(BacktestRun run, DateOnly from) =>
[.. run.Fills.Where(f => f.Day >= from).GroupBy(f => (f.Day, f.Symbol, f.Side)).Select(g => (g.Key.Day, g.Key.Symbol, g.Key.Side, g.Sum(f => f.Quantity)))];
/// <summary>The live fills by UTC day, symbol and side.</summary>
public async Task<IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)>> LiveFillsAsync()
{
var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at",
r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false);
return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))];
}
/// <summary>The live fills match the backtest's: the same days, symbols and sides, quantities within 1%.</summary>
public static void AssertSameTrades(IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> expected,
IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> actual)
{
var report = "backtest:\n" + string.Join("\n", expected.Select(e => " " + e)) + "\nlive:\n" + string.Join("\n", actual.Select(a => " " + a));
Console.WriteLine(report);
Assert.HasCount(expected.Count, actual, report);
foreach (var e in expected)
{
var match = actual.SingleOrDefault(a => a.Day == e.Day && a.Symbol == e.Symbol && a.Side == e.Side);
Assert.AreNotEqual(default, match, "Missing live fill " + e + "\n" + report);
Assert.IsLessThanOrEqualTo(0.01m, Math.Abs(match.Quantity - e.Quantity) / e.Quantity, "Quantity apart: " + e + " vs " + match + "\n" + report);
}
}
public ValueTask DisposeAsync()
{
DatabaseDown = false;
Engine.Dispose();
return Rig.DisposeAsync();
}
}