Test the order manager and reconciliation end to end (refs #27 #28 #30)

Order manager tests drive the internal simulator turn by turn: the chasing
limit with its post-only steps and aggressive cross, a buy given up, a sale
never given up with its alert, the pace of six sends a minute, Alpaca's
GTC + day stops, the stop-already-passed rule and splits, lost answers,
duplicate fills, refusals and residues. Reconciliation tests cover clean,
healed, prudent mode and its return, align/exclude, unknown orders, stop
coverage, withdraw-capable keys and an unreachable broker.

Two defects found by the tests are fixed: stops were not cleared before an
execution that starts aggressive (Alpaca refuses a buy with a sell stop open,
and a sale must free the quantity), and an order's creation is now recorded
as its first event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 20:40:21 +01:00
1 parent 1419457fe4
commit e3caa26207
5 files changed
+813 -6

No files matched your search

+100
View File
@@ -69,6 +69,15 @@ internal sealed class TradingRig : IAsyncDisposable
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);
@@ -89,6 +98,7 @@ internal sealed class TradingRig : IAsyncDisposable
{
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,
@@ -102,6 +112,7 @@ internal sealed class TradingRig : IAsyncDisposable
{
for (var i = 0; i < turns; i++)
{
Refresh();
if (manager.Broker is PaperBroker paper)
{
await paper.PumpAsync(CancellationToken.None).ConfigureAwait(false);
@@ -128,3 +139,92 @@ internal sealed class TradingRig : IAsyncDisposable
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();
}