Phase 3 needs books the bot can trust before any strategy trades. This adds: - schema 0003: executions, order events, trades, residues, account status, reconciliations, capital changes, applied corporate actions, simulator books; - the broker interface with the internal simulator and the Alpaca paper and OKX demo adapters, all behind the live guard (SPEC 2.2); - the append-only ledger with lots, trades from zero to zero, residues, dividends, splits and reversals; capital entrusted per broker and equity photographs with time-weighted return and FX effect; - the order manager (chasing limit, pacing, sells never abandoned, server stops, breached-stop rule) and the reconciler with prudent mode; - the trading service wired into the host, off in demo mode and in tests. Ids made with one clock in the same millisecond now carry a counter (RFC 9562 method 1): two lots of one order kept a random order, which broke LIFO. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
74d4c4fa6f
commit
1419457fe4
50 files changed
+7327
-5
No files matched your search
@@ -0,0 +1,130 @@
|
||||
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);
|
||||
}
|
||||
|
||||
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, Strategies.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 };
|
||||
|
||||
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)
|
||||
{
|
||||
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++)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user