Fase 6 — Motore dal vivo in simulazione #92
No files matched your search
@@ -162,9 +162,12 @@ public static class BacktestEngine
|
||||
|
||||
/// <summary>
|
||||
/// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of
|
||||
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs.
|
||||
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs. The live engine
|
||||
/// decides with this same call (SPEC 5.2): <paramref name="history"/> is the strategy's equity at each close up to
|
||||
/// <paramref name="day"/>, which the risk stage walks as it does in a whole run.
|
||||
/// </summary>
|
||||
public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null)
|
||||
public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null,
|
||||
IReadOnlyList<EquityMark>? history = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(strategy);
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
@@ -172,6 +175,7 @@ public static class BacktestEngine
|
||||
CheckSchedule(strategy);
|
||||
var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state);
|
||||
simulation.MarkThrough(day);
|
||||
simulation.SeedHistory(history ?? []);
|
||||
return simulation.Decide(day, data.SessionTimes(day).Closes);
|
||||
}
|
||||
|
||||
@@ -263,6 +267,8 @@ public static class BacktestEngine
|
||||
}
|
||||
}
|
||||
|
||||
public void SeedHistory(IReadOnlyList<EquityMark> history) => _history.AddRange(history);
|
||||
|
||||
public void MarkThrough(DateOnly day)
|
||||
{
|
||||
foreach (var i in _data.Instruments)
|
||||
|
||||
@@ -118,6 +118,9 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche
|
||||
/// skipped and reported instead of executed blindly (trap 21, SPEC 5.6).
|
||||
/// </summary>
|
||||
public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15);
|
||||
|
||||
/// <summary>A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job.</summary>
|
||||
public bool IsMove { get; init; }
|
||||
}
|
||||
|
||||
public enum JobOutcome
|
||||
@@ -131,7 +134,10 @@ public enum JobOutcome
|
||||
public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error);
|
||||
|
||||
/// <summary>A run coming up, for "Prossime mosse" and the jobs list.</summary>
|
||||
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc);
|
||||
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc)
|
||||
{
|
||||
public bool IsMove { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs jobs at fixed times, at intervals, or relative to market open and close (SPEC 5.5).
|
||||
@@ -164,7 +170,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
|
||||
return _jobs.Values.Where(j => j.Due is not null)
|
||||
.OrderBy(j => j.Due)
|
||||
.Take(count)
|
||||
.Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value))
|
||||
.Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove })
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,8 @@ public sealed partial class MarketDataService : IDisposable
|
||||
{
|
||||
await UsCalendar.LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||
_work.Release();
|
||||
await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), FreshnessAsync(cancellationToken)).ConfigureAwait(false);
|
||||
await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), StockLiveAsync(cancellationToken), FreshnessAsync(cancellationToken))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task WakeWorker()
|
||||
@@ -491,6 +492,90 @@ public sealed partial class MarketDataService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stock feed (IEX, issue #47): during the US session only, the stocks held, those with an order planned and the
|
||||
/// market index, at most <see cref="StockStreamLimit"/> symbols as the free feed allows. Outside the session the
|
||||
/// quotes come by REST when asked, and no stock is followed for freshness.
|
||||
/// </summary>
|
||||
private async Task StockLiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var now = _clock.UtcNow;
|
||||
var today = DateOnly.FromDateTime(now.UtcDateTime);
|
||||
var session = UsCalendar.Sessions(today.AddDays(-1), today.AddDays(10)).FirstOrDefault(s => s.CloseUtc + StockStreamMargin > now);
|
||||
if (session is null || session.OpenUtc - StockStreamMargin > now)
|
||||
{
|
||||
var next = session is null ? now.AddHours(1) : Min(session.OpenUtc - StockStreamMargin, now.AddHours(1));
|
||||
await _clock.WaitUntilAsync(next, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
var alpaca = await AlpacaAsync(cancellationToken).ConfigureAwait(false);
|
||||
var instruments = alpaca is null ? [] : await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (alpaca is null || instruments.Count == 0)
|
||||
{
|
||||
await _clock.WaitUntilAsync(now.AddMinutes(5), cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
var end = session.CloseUtc + StockStreamMargin;
|
||||
using var round = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var collector = new MarketCollector(alpaca, _db, _clock, _bus, Freshness, logger: _logger);
|
||||
var run = collector.RunLiveAsync(instruments, round.Token);
|
||||
var ids = instruments.Select(i => i.Id).ToHashSet();
|
||||
while (!run.IsCompleted)
|
||||
{
|
||||
using var nap = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var wait = _clock.WaitUntilAsync(Min(_clock.UtcNow.AddMinutes(5), end), nap.Token);
|
||||
await Task.WhenAny(run, wait).ConfigureAwait(false);
|
||||
await nap.CancelAsync().ConfigureAwait(false);
|
||||
if (!run.IsCompleted && (_clock.UtcNow >= end
|
||||
|| !(await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false)).Select(i => i.Id).ToHashSet().SetEquals(ids)))
|
||||
{
|
||||
await round.CancelAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await run.ConfigureAwait(false);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
Freshness.Unfollow(id);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogStepFailed(_logger, ex, "live azioni");
|
||||
await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The free IEX feed follows at most 30 symbols.</summary>
|
||||
public const int StockStreamLimit = 30;
|
||||
|
||||
private static readonly TimeSpan StockStreamMargin = TimeSpan.FromMinutes(5);
|
||||
|
||||
private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a <= b ? a : b;
|
||||
|
||||
private async Task<IReadOnlyList<Instrument>> StockLiveInstrumentsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var symbols = await _db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (i.symbol = @m"
|
||||
+ " OR i.id IN (SELECT instrument_id FROM positions WHERE quantity <> 0)"
|
||||
+ " OR i.id IN (SELECT instrument_id FROM planned_orders WHERE status = @p)) ORDER BY i.symbol",
|
||||
r => r.Text("symbol"), ("v", Venues.Alpaca), ("m", Trading.StrategyNames.MarketSymbol), ("p", "pending")), cancellationToken).ConfigureAwait(false);
|
||||
var wanted = symbols.OrderBy(s => s == Trading.StrategyNames.MarketSymbol ? 0 : 1).ThenBy(s => s, StringComparer.Ordinal).Take(StockStreamLimit).ToHashSet(StringComparer.Ordinal);
|
||||
var all = await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false);
|
||||
return all.Where(i => wanted.Contains(i.Symbol) && i.IsLive).ToList();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Instrument>> LiveInstrumentsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
|
||||
|
||||
@@ -117,8 +117,16 @@ public sealed class Database : IAsyncDisposable
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Fault tests only (issue #47): while true every new connection fails as if the server could not be reached.</summary>
|
||||
internal bool Unreachable { get; set; }
|
||||
|
||||
public async Task<DbConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Unreachable)
|
||||
{
|
||||
throw new DatabaseUnreachableException();
|
||||
}
|
||||
|
||||
if (_postgres is not null)
|
||||
{
|
||||
return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -239,6 +247,25 @@ public sealed class Database : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>One open transaction. Parameters are named <c>@name</c> on both engines.</summary>
|
||||
/// <summary>The database could not be reached (fault tests).</summary>
|
||||
public sealed class DatabaseUnreachableException : DbException
|
||||
{
|
||||
public DatabaseUnreachableException()
|
||||
: base("Database non raggiungibile.")
|
||||
{
|
||||
}
|
||||
|
||||
public DatabaseUnreachableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public DatabaseUnreachableException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DbSession(DbEngine engine, DbConnection connection, DbTransaction transaction)
|
||||
{
|
||||
public DbEngine Engine => engine;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
-- Phase 6 schema (SPEC 5.5, 5.6, 9.3, 9.4, 14, ADR 0012): the live engine, recovery after an absence, Telegram.
|
||||
|
||||
-- One row for each decision the live engine makes: run_key names the strategy and the close it decides on, so a
|
||||
-- decision is made once even across restarts. The row is written in the same transaction as its planned orders,
|
||||
-- its decision rows and its diary lines: either all of it exists or none. state is the book the strategy decided
|
||||
-- from, for the one-step comparison of SPEC 12.3 the next day.
|
||||
CREATE TABLE engine_runs (
|
||||
id {uuid} PRIMARY KEY,
|
||||
strategy TEXT NOT NULL,
|
||||
run_key TEXT NOT NULL UNIQUE,
|
||||
decision_day TEXT NOT NULL,
|
||||
decision_id {uuid} NOT NULL,
|
||||
mode TEXT NOT NULL,
|
||||
state {json},
|
||||
proposed {json},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX engine_runs_strategy ON engine_runs (strategy, decision_day);
|
||||
|
||||
-- Orders decided and not yet handed to the order manager (SPEC 5.5: the stock orders decided after the close go at
|
||||
-- the next open; SPEC 5.6: an entry has a deadline and a reference price it must not drift from). The planned
|
||||
-- order's id is the decision id of the trade intent: the order key derives from it, so a restart that finds the
|
||||
-- execution already there never sends it twice.
|
||||
CREATE TABLE planned_orders (
|
||||
id {uuid} PRIMARY KEY,
|
||||
decision_id {uuid} NOT NULL,
|
||||
strategy TEXT NOT NULL,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
|
||||
side TEXT NOT NULL,
|
||||
purpose TEXT NOT NULL,
|
||||
quantity {money} NOT NULL,
|
||||
exit_all {bool} NOT NULL,
|
||||
stop_level {money},
|
||||
stop_offset {money},
|
||||
reference_price {money} NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
due_at {timestamp} NOT NULL,
|
||||
valid_until {timestamp},
|
||||
status TEXT NOT NULL,
|
||||
outcome TEXT,
|
||||
execution_id {uuid},
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX planned_orders_due ON planned_orders (status, due_at);
|
||||
|
||||
-- Absences (SPEC 5.6): measured at the restart from the last heartbeat. One longer than 24 hours is declared on the
|
||||
-- Panoramica until the user acknowledges it.
|
||||
CREATE TABLE absences (
|
||||
id {uuid} PRIMARY KEY,
|
||||
started_at {timestamp} NOT NULL,
|
||||
ended_at {timestamp} NOT NULL,
|
||||
acknowledged_at {timestamp},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
-- Every notification has its state (SPEC 14): pending, sent or failed, with the attempts and the last error.
|
||||
ALTER TABLE notifications ADD COLUMN attempts INTEGER;
|
||||
ALTER TABLE notifications ADD COLUMN next_attempt_at {timestamp};
|
||||
ALTER TABLE notifications ADD COLUMN last_error TEXT;
|
||||
|
||||
CREATE INDEX notifications_status ON notifications (status, created_at);
|
||||
@@ -11,6 +11,9 @@ public static class StrategyNames
|
||||
public const string EquityMomentum = "equity_momentum";
|
||||
public const string EquityMeanrev = "equity_meanrev";
|
||||
|
||||
/// <summary>The market filter of the stock strategies (SPEC 8.2): read, never traded unless it is in the universe.</summary>
|
||||
public const string MarketSymbol = "SPY";
|
||||
|
||||
public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base =
|
||||
[
|
||||
(CryptoTrend, Venues.Okx, 1m),
|
||||
|
||||
@@ -81,6 +81,9 @@ public static class DiaryText
|
||||
public static string StopRaised(string symbol, decimal from, decimal to, string currency) =>
|
||||
$"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale.";
|
||||
|
||||
public static string StopLowered(string symbol, decimal from, decimal to, string currency) =>
|
||||
$"Spostato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}.";
|
||||
|
||||
public static string StopsReplaced(int count) => count == 1
|
||||
? "Rimesso 1 stop giornaliero sulle frazioni di azione."
|
||||
: $"Rimessi {count} stop giornalieri sulle frazioni di azione.";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -75,6 +75,15 @@ public static class ReasonCatalog
|
||||
["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.",
|
||||
["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
|
||||
["dividend"] = "Dividendo accreditato.",
|
||||
// Live engine.
|
||||
["late_exits_only"] = "Decisione in ritardo: solo uscite e stop, gli ingressi aspettano la prossima chiusura.",
|
||||
["entry_expired"] = "Ingresso scaduto: oltre l'orario in cui era valido.",
|
||||
["price_moved"] = "Il prezzo si è mosso troppo dall'orario previsto: ingresso scartato.",
|
||||
["missing_bars"] = "Mancano le barre di chiusura: niente nuove posizioni.",
|
||||
["superseded"] = "Sostituito da una decisione più recente.",
|
||||
["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.",
|
||||
["nothing_held"] = "Niente da vendere: la posizione era già chiusa.",
|
||||
["recovered"] = "Recuperato dopo un'assenza.",
|
||||
};
|
||||
|
||||
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
|
||||
|
||||
@@ -183,8 +183,18 @@ public sealed partial class TradingService : IDisposable
|
||||
Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false)));
|
||||
Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile };
|
||||
_settings = settings;
|
||||
Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger)
|
||||
{
|
||||
WantData = market is null ? null : _ => market.WakeWorker(),
|
||||
Ready = () => _started,
|
||||
};
|
||||
}
|
||||
|
||||
private volatile bool _started;
|
||||
|
||||
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
|
||||
public LiveEngine Engine { get; }
|
||||
|
||||
private readonly SettingsStore? _settings;
|
||||
|
||||
public StageBook Stages { get; }
|
||||
@@ -271,6 +281,7 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
|
||||
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
_started = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -295,8 +306,29 @@ public sealed partial class TradingService : IDisposable
|
||||
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
||||
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
|
||||
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
|
||||
.. Engine.Jobs(),
|
||||
.. _market is null ? Array.Empty<ScheduledJob>() :
|
||||
[
|
||||
new ScheduledJob("fine-seduta", "Scadenza degli ordini giornalieri del simulatore azioni",
|
||||
Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(1), _market.UsCalendar), ExpireDayOrdersAsync) { MaxLateness = TimeSpan.FromHours(12) },
|
||||
],
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The day orders of the stock simulator end at the close, as on the broker: the daily stops on fractions go back
|
||||
/// at the next open (SPEC 5.5, 7.2).
|
||||
/// </summary>
|
||||
public async Task ExpireDayOrdersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca))
|
||||
{
|
||||
if (manager.Broker is PaperBroker paper)
|
||||
{
|
||||
await paper.ExpireDayOrdersAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file.</summary>
|
||||
public async Task CheckRiskAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -707,6 +739,7 @@ public sealed partial class TradingService : IDisposable
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Engine.Dispose();
|
||||
foreach (var manager in _managers.Values)
|
||||
{
|
||||
manager.Dispose();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user