A restore, an import or an adopted database restarts protected: the engine stays stopped, reads from the broker what the archive does not know (orders, stops, executions, also from the OKX history up to 89 days), cancels orders left working, protects what it finds and waits for the user. Strategies with real money stay exit only until confirmed again. The database of before the restore, put back by mistake, is refused by its fingerprint. A failed migration leaves the engine off with one backup and a way to try again; an archive is checked whole before the database is touched; a changed secret key no longer crashes anything, and "anubis access reset" gives the access back to whoever holds the computer. The image runs the db and access commands without the guard. refs #69 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
251 lines
11 KiB
C#
251 lines
11 KiB
C#
using System.Collections.Concurrent;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Db;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>
|
|
/// A migrated database on the engine of this run with what trading tests need: a manual clock, quotes set by the
|
|
/// test, accounts and instruments, the internal simulator and order managers. Tuesday 10 November 2026, 10:00 in New York.
|
|
/// </summary>
|
|
internal sealed class TradingRig : IAsyncDisposable
|
|
{
|
|
public const string Installation = "TST1";
|
|
|
|
public static readonly DateTimeOffset Start = new(2026, 11, 10, 15, 0, 0, TimeSpan.Zero);
|
|
|
|
private readonly ConcurrentDictionary<string, Quote> _quotes = new(StringComparer.Ordinal);
|
|
private readonly ConcurrentDictionary<string, InstrumentSpec> _specs = new(StringComparer.Ordinal);
|
|
private readonly ConcurrentDictionary<Guid, Instrument> _instruments = new();
|
|
private readonly List<IDisposable> _owned = [];
|
|
|
|
private TradingRig(TestDb test)
|
|
{
|
|
Test = test;
|
|
Clock = new ManualClock(Start);
|
|
Ledger = new Ledger(test.Db, Clock);
|
|
Catalog = new InstrumentCatalog(test.Db, Clock);
|
|
}
|
|
|
|
// The same market and the same clock on another database: the account goes on while the ledger went back (SPEC 15.1).
|
|
private TradingRig(TestDb test, TradingRig before)
|
|
{
|
|
Test = test;
|
|
Clock = before.Clock;
|
|
Ledger = new Ledger(test.Db, Clock);
|
|
Catalog = new InstrumentCatalog(test.Db, Clock);
|
|
_quotes = before._quotes;
|
|
_specs = before._specs;
|
|
_instruments = before._instruments;
|
|
}
|
|
|
|
/// <summary>An archive of this rig loaded in a new database of <paramref name="engine"/> (that of the run when null).</summary>
|
|
public async Task<TradingRig> RestoreAsync(string archive, Anubis.Platform.DbEngine? engine = null)
|
|
{
|
|
var test = engine is { } e ? await TestDb.CreateAsync(e).ConfigureAwait(false) : await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Archive.ImportAsync(test.Db, archive, Clock).ConfigureAwait(false);
|
|
return new TradingRig(test, this);
|
|
}
|
|
|
|
public TestDb Test { get; }
|
|
|
|
public Database Db => Test.Db;
|
|
|
|
public ManualClock Clock { get; }
|
|
|
|
public Ledger Ledger { get; }
|
|
|
|
public InstrumentCatalog Catalog { get; }
|
|
|
|
/// <summary>Quotes are refused while this is true: the price feed is "down".</summary>
|
|
public bool QuotesDown { get; set; }
|
|
|
|
public static async Task<TradingRig> CreateAsync() => new(await DatabaseTests.MigratedAsync().ConfigureAwait(false));
|
|
|
|
public async Task<AccountContext> AccountAsync(string broker, string environment, string? name = null)
|
|
{
|
|
var account = new AccountContext(Ids.NewId(Clock), name ?? AccountSetup.NameOf(broker, environment), broker, environment, StrategyNames.CurrencyOf(broker));
|
|
await Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", CancellationToken.None,
|
|
("id", account.AccountId), ("n", account.Name), ("b", broker), ("e", environment), ("c", account.Currency), ("now", Clock.UtcNow)), CancellationToken.None).ConfigureAwait(false);
|
|
return account;
|
|
}
|
|
|
|
public async Task<Instrument> InstrumentAsync(InstrumentSpec spec)
|
|
{
|
|
var instrument = await Catalog.EnsureAsync(spec, CancellationToken.None).ConfigureAwait(false);
|
|
_specs[spec.Symbol] = instrument.Spec;
|
|
_instruments[instrument.Id] = instrument;
|
|
return instrument;
|
|
}
|
|
|
|
public static InstrumentSpec Btc => MarketDataStoreTests.Okx("BTC-EUR") with { TickSize = 0.1m, LotSize = 0.00000001m, MinSize = 0.00001m };
|
|
|
|
public static InstrumentSpec Pepe => MarketDataStoreTests.Okx("PEPE-EUR") with { TickSize = 0.00000001m, LotSize = 1m, MinSize = 100000m };
|
|
|
|
public static InstrumentSpec Stock(string symbol, bool fractionable = true) => TradingRulesTests.Stock(symbol, fractionable);
|
|
|
|
public void Quote(string symbol, decimal bid, decimal ask, decimal? size = null) =>
|
|
_quotes[symbol] = new Quote(symbol, bid, ask, Clock.UtcNow) { BidSize = size, AskSize = size };
|
|
|
|
/// <summary>The same prices, read again now: the feed is alive and the market has not moved.</summary>
|
|
public void Refresh()
|
|
{
|
|
foreach (var (symbol, quote) in _quotes)
|
|
{
|
|
_quotes[symbol] = quote with { At = Clock.UtcNow };
|
|
}
|
|
}
|
|
|
|
public Task<Quote?> QuoteAsync(string symbol, CancellationToken cancellationToken) =>
|
|
Task.FromResult(QuotesDown ? null : _quotes.TryGetValue(symbol, out var quote) ? quote : null);
|
|
|
|
public Task<Instrument?> FindAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(_instruments.GetValueOrDefault(id));
|
|
|
|
public InstrumentSpec? Spec(string symbol) => _specs.GetValueOrDefault(symbol);
|
|
|
|
public PaperBroker Paper(PaperOptions options, Guid accountId, bool persist = true)
|
|
{
|
|
var broker = new PaperBroker(options with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, Clock, QuoteAsync, Spec,
|
|
persist ? new PaperBookStore(Db, Clock, accountId) : null);
|
|
_owned.Add(broker);
|
|
return broker;
|
|
}
|
|
|
|
public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func<Instrument, CancellationToken, Task<bool>>? marketOpen = null,
|
|
Func<Instrument, CancellationToken, Task<CorporateAction?>>? pendingSplit = null)
|
|
{
|
|
var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync)
|
|
{
|
|
StepTime = TimeSpan.FromSeconds(60),
|
|
ConfirmPrice = QuoteAsync,
|
|
MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)),
|
|
PendingSplit = pendingSplit,
|
|
};
|
|
_owned.Add(manager);
|
|
return manager;
|
|
}
|
|
|
|
/// <summary>Several turns of the order manager, the clock moving between them (the simulator's latency, the steps).</summary>
|
|
public async Task TurnsAsync(OrderManager manager, int turns, TimeSpan every)
|
|
{
|
|
for (var i = 0; i < turns; i++)
|
|
{
|
|
Refresh();
|
|
if (manager.Broker is PaperBroker paper)
|
|
{
|
|
await paper.PumpAsync(CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
|
|
await manager.TickAsync(CancellationToken.None).ConfigureAwait(false);
|
|
Clock.Advance(every);
|
|
}
|
|
}
|
|
|
|
public Task<IReadOnlyList<T>> QueryAsync<T>(string sql, Func<DbRow, T> read, params (string, object?)[] args) =>
|
|
Db.ReadAsync<IReadOnlyList<T>>(async s => await s.QueryAsync(sql, read, args).ConfigureAwait(false), CancellationToken.None);
|
|
|
|
public LedgerFill Fill(AccountContext account, Instrument instrument, string strategy, OrderSide side, decimal quantity, decimal price, decimal fee = 0m, string? feeCurrency = null) =>
|
|
new(account.AccountId, instrument.Id, strategy, "X" + Ids.NewId(Clock).ToString("N"), side, quantity, price, fee, feeCurrency ?? instrument.Spec.QuoteCurrency, Clock.UtcNow);
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
foreach (var owned in _owned)
|
|
{
|
|
owned.Dispose();
|
|
}
|
|
|
|
await Test.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>A broker in front of another one that can lose answers, refuse orders, repeat fills or go silent (fault tests, SPEC 7.4).</summary>
|
|
internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = null) : IBrokerAccount
|
|
{
|
|
/// <summary>Quantities the account no longer shows, by symbol: a difference the ledger cannot explain.</summary>
|
|
public Dictionary<string, decimal> Missing { get; } = new(StringComparer.Ordinal);
|
|
|
|
/// <summary>The key reports that it may withdraw.</summary>
|
|
public bool KeyCanWithdraw { get; set; }
|
|
|
|
/// <summary>The next order reaches the broker but its answer is lost.</summary>
|
|
public bool LoseNextAnswer { get; set; }
|
|
|
|
/// <summary>The next order is refused with this code.</summary>
|
|
public string? RejectNext { get; set; }
|
|
|
|
/// <summary>Every fill is reported twice.</summary>
|
|
public bool DuplicateFills { get; set; }
|
|
|
|
/// <summary>Every call fails as if the network were down.</summary>
|
|
public bool Down { get; set; }
|
|
|
|
public List<OrderRequest> Sent { get; } = [];
|
|
|
|
public string Venue => inner.Venue;
|
|
|
|
public string Environment => environment ?? inner.Environment;
|
|
|
|
public BrokerCapabilities Capabilities => inner.Capabilities;
|
|
|
|
public Task<DateTimeOffset> ServerTimeAsync(CancellationToken cancellationToken) => Guard(() => inner.ServerTimeAsync(cancellationToken));
|
|
|
|
public Task<AccountSnapshot> GetAccountAsync(CancellationToken cancellationToken) => Guard(() => inner.GetAccountAsync(cancellationToken));
|
|
|
|
public async Task<IReadOnlyList<BrokerPosition>> GetPositionsAsync(CancellationToken cancellationToken)
|
|
{
|
|
var positions = await Guard(() => inner.GetPositionsAsync(cancellationToken)).ConfigureAwait(false);
|
|
return [.. positions.Select(p => p with { Quantity = p.Quantity - Missing.GetValueOrDefault(p.Symbol) })];
|
|
}
|
|
|
|
public Task<IReadOnlyList<BrokerOrder>> GetOpenOrdersAsync(CancellationToken cancellationToken) => Guard(() => inner.GetOpenOrdersAsync(cancellationToken));
|
|
|
|
public async Task<BrokerOrder> SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken)
|
|
{
|
|
if (Down)
|
|
{
|
|
throw new BrokerException("rete giù", retryable: true);
|
|
}
|
|
|
|
if (RejectNext is { } code)
|
|
{
|
|
RejectNext = null;
|
|
throw new OrderRejectedException("rifiutato", code);
|
|
}
|
|
|
|
Sent.Add(request);
|
|
var answer = await inner.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false);
|
|
if (LoseNextAnswer)
|
|
{
|
|
LoseNextAnswer = false;
|
|
throw new BrokerException("risposta persa", retryable: true);
|
|
}
|
|
|
|
return answer;
|
|
}
|
|
|
|
public Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) => Guard(async () =>
|
|
{
|
|
await inner.CancelOrderAsync(clientOrderId, symbol, cancellationToken).ConfigureAwait(false);
|
|
return true;
|
|
});
|
|
|
|
public Task<BrokerOrder?> GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) => Guard(() => inner.GetOrderAsync(clientOrderId, symbol, cancellationToken));
|
|
|
|
public async Task<IReadOnlyList<BrokerFill>> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken)
|
|
{
|
|
var fills = await Guard(() => inner.GetFillsAsync(since, cancellationToken)).ConfigureAwait(false);
|
|
return DuplicateFills ? [.. fills, .. fills] : fills;
|
|
}
|
|
|
|
public Task<IReadOnlyList<CashActivity>> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken) => Guard(() => inner.GetCashActivitiesAsync(since, cancellationToken));
|
|
|
|
public Task<KeyPermissions> GetKeyPermissionsAsync(CancellationToken cancellationToken) =>
|
|
KeyCanWithdraw ? Task.FromResult(new KeyPermissions(true, true, true, "lettura, ordini, prelievi")) : Guard(() => inner.GetKeyPermissionsAsync(cancellationToken));
|
|
|
|
public IAsyncEnumerable<OrderUpdate> StreamOrderUpdatesAsync(CancellationToken cancellationToken) => inner.StreamOrderUpdatesAsync(cancellationToken);
|
|
|
|
private Task<T> Guard<T>(Func<Task<T>> call) => Down ? throw new BrokerException("rete giù", retryable: true) : call();
|
|
}
|