Files
Alby96andClaude Opus 5.5 1419457fe4 Add the trading core: ledger, simulator, order manager, reconciliation (refs #26 #27 #28 #29 #30)
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>
2026-11-10 20:29:02 +01:00

256 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Core;
namespace Anubis.Tests;
[TestClass]
public sealed class CoreTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void IdsAreVersion7AndFollowTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var first = Ids.NewId(clock);
clock.Advance(TimeSpan.FromMilliseconds(5));
var second = Ids.NewId(clock);
Assert.AreEqual(7, first.Version);
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
// In the same millisecond they still come out in order (two lots of one order, LIFO), with the clock's time.
var burst = Enumerable.Range(0, 5000).Select(_ => Ids.NewId(clock).ToString()).ToList();
CollectionAssert.AreEqual(burst.Order(StringComparer.Ordinal).ToList(), burst);
Assert.AreEqual(burst.Count, burst.Distinct().Count());
var time = Convert.ToInt64(burst[0].Replace("-", "", StringComparison.Ordinal)[..12], 16);
Assert.AreEqual(clock.UtcNow.ToUnixTimeMilliseconds(), time);
Assert.AreEqual(7, Guid.Parse(burst[^1]).Version);
Assert.AreEqual(0x8, Guid.Parse(burst[^1]).Variant & 0xC);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ManualClockReleasesWaitersOnlyWhenMoved()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var waiting = clock.WaitUntilAsync(DateTimeOffset.UnixEpoch.AddMinutes(5), CancellationToken.None);
clock.Advance(TimeSpan.FromMinutes(4));
Assert.IsFalse(waiting.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(1));
await waiting.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task BusDeliversToEachSubscriberAndDropsOldestWhenFull()
{
var bus = new EventBus();
using var all = bus.Subscribe<object>();
using var small = bus.Subscribe<string>(capacity: 2);
bus.Publish("a");
bus.Publish("b");
bus.Publish("c");
bus.Publish(42);
var received = new List<string>();
while (small.TryRead(out var message))
{
received.Add(message!);
}
CollectionAssert.AreEqual(new[] { "b", "c" }, received, "un lettore lento perde i più vecchi, non blocca chi pubblica");
var count = 0;
while (all.TryRead(out _))
{
count++;
}
Assert.AreEqual(4, count);
all.Dispose();
Assert.AreEqual(1, bus.SubscriberCount);
await Task.CompletedTask.ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RedactorRemovesKeysSignaturesAndHeaders()
{
Redactor.Register("registered-secret-value-123");
var samples = new Dictionary<string, string>
{
["OK-ACCESS-SIGN: " + "abc123signature=="] = "abc123signature",
["APCA-API-SECRET-KEY: " + "Sk1234567890abcdef"] = "Sk1234567890abcdef",
["Authorization: Bearer " + "eyJhbGciOiJIUzI1NiJ9.payload"] = "eyJhbGciOiJIUzI1NiJ9",
["{\"api_key\": \"" + "AK12345678\"}"] = "AK12345678",
["password=" + "hunter2hunter2&x=1"] = "hunter2hunter2",
["postgres://anubis:" + "S3cretPw@db:5432/anubis"] = "S3cretPw",
["bot" + "123456789:" + "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq"] = "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq",
["value registered-secret-value-123 in text"] = "registered-secret-value-123",
};
foreach (var (input, secret) in samples)
{
var output = Redactor.Redact(input);
Assert.IsFalse(output.Contains(secret, StringComparison.Ordinal), $"Segreto rimasto in: {output}");
Assert.Contains(Redactor.Mask, output);
}
Assert.AreEqual("Ordine eseguito: 2 AAPL a 259,80 $", Redactor.Redact("Ordine eseguito: 2 AAPL a 259,80 $"));
}
}
/// <summary>The scheduler with a fake calendar (issue #10): fixed times, intervals, open and close, sleeps.</summary>
[TestClass]
public sealed class SchedulerTests
{
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
private static readonly TimeZoneInfo _newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
/// <summary>New York, 09:30–16:00 on weekdays, 13:00 close on the day after Thanksgiving 2026, closed on 3 July.</summary>
private sealed class FakeCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day)
{
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || day == new DateOnly(2026, 7, 3))
{
return null;
}
var close = day == new DateOnly(2026, 11, 27) ? new TimeOnly(13, 0) : new TimeOnly(16, 0);
return new MarketSession(day, At(day, new TimeOnly(9, 30)), At(day, close));
}
private static DateTimeOffset At(DateOnly day, TimeOnly time)
{
var local = day.ToDateTime(time);
return new DateTimeOffset(local, _newYork.GetUtcOffset(local)).ToUniversalTime();
}
}
private static DateTimeOffset Rome(int y, int mo, int d, int h, int mi)
{
var local = new DateTime(y, mo, d, h, mi, 0);
return new DateTimeOffset(local, _rome.GetUtcOffset(local));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MarketTimesFollowTheExchangeNotItalianTime()
{
var calendar = new FakeCalendar();
var afterOpen = Schedule.Market(MarketAnchor.Open, TimeSpan.FromMinutes(5), calendar);
// Normal week: 09:35 in New York is 15:35 in Rome.
Assert.AreEqual(Rome(2026, 10, 9, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 8, 21)));
// 16 March 2026: the USA already moved to summer time, Europe not yet: 09:35 NY is 14:35 in Rome.
Assert.AreEqual(Rome(2026, 3, 16, 14, 35), afterOpen.NextAfter(Rome(2026, 3, 16, 8, 0)));
// Friday after the open: the next run is Monday.
Assert.AreEqual(Rome(2026, 10, 12, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 16, 0)));
// Holiday skipped (Friday 3 July): Monday 6 July.
Assert.AreEqual(Rome(2026, 7, 6, 15, 35), afterOpen.NextAfter(Rome(2026, 7, 2, 16, 0)));
// Early close: 5 minutes before a 13:00 close is 12:55 in New York, 18:55 in Rome.
var beforeClose = Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(-5), calendar);
Assert.AreEqual(Rome(2026, 11, 27, 18, 55), beforeClose.NextAfter(Rome(2026, 11, 27, 9, 0)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DailyAndIntervalSchedules()
{
var backup = Schedule.Daily(new TimeOnly(3, 30), _rome);
Assert.AreEqual(Rome(2026, 10, 10, 3, 30), backup.NextAfter(Rome(2026, 10, 9, 8, 21)));
// The night summer time ends (25 October 2026) 03:30 exists once, in winter time.
Assert.AreEqual(Rome(2026, 10, 25, 3, 30), backup.NextAfter(Rome(2026, 10, 24, 12, 0)));
// 02:30 does not exist on 29 March 2026 in Rome: it moves to 03:00.
var skipped = Schedule.Daily(new TimeOnly(2, 30), _rome);
Assert.AreEqual(new DateTimeOffset(2026, 3, 29, 1, 0, 0, TimeSpan.Zero), skipped.NextAfter(Rome(2026, 3, 28, 12, 0)));
var crypto = Schedule.Daily(new TimeOnly(0, 5), TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 0, 5, 0, TimeSpan.Zero), crypto.NextAfter(Rome(2026, 10, 9, 8, 21)));
var every5 = Schedule.Every(TimeSpan.FromMinutes(5));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 30, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RunsDueJobsOnceAndSkipsRunsMissedDuringASleep()
{
var clock = new ManualClock(Rome(2026, 10, 9, 8, 21));
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(clock, bus);
var count = 0;
scheduler.Add(new ScheduledJob("backup", "Salvataggio", Schedule.Daily(new TimeOnly(3, 30), _rome), _ =>
{
count++;
return Task.CompletedTask;
}));
scheduler.Add(new ScheduledJob("broken", "Rotto", Schedule.Daily(new TimeOnly(3, 30), _rome), _ => throw new InvalidOperationException("guasto")));
Assert.HasCount(2, scheduler.Upcoming());
clock.Set(Rome(2026, 10, 10, 3, 30));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count, "un lavoro già eseguito non riparte");
// The computer slept two days: the 03:30 run is found late by hours and is skipped, not run blindly.
clock.Set(Rome(2026, 10, 11, 9, 0));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
var outcomes = new List<JobRun>();
while (runs.TryRead(out var run))
{
outcomes.Add(run!);
}
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Completed));
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Skipped));
Assert.IsTrue(outcomes.Any(r => r.Name == "broken" && r.Outcome == JobOutcome.Failed && r.Error == "guasto"));
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task LoopWaitsOnTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var scheduler = new Scheduler(clock, new EventBus());
var ran = new TaskCompletionSource();
scheduler.Add(new ScheduledJob("tick", "Prova", Schedule.Every(TimeSpan.FromMinutes(5)), _ =>
{
ran.TrySetResult();
return Task.CompletedTask;
}));
using var cts = new CancellationTokenSource();
var loop = scheduler.RunAsync(cts.Token);
await WaitUntil(() => clock.Waiting > 0).ConfigureAwait(false);
Assert.IsFalse(ran.Task.IsCompleted, "nessun lavoro prima dell'orario");
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
await ran.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsNotNull(scheduler.LastBeatUtc);
await cts.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => loop).ConfigureAwait(false);
}
internal static async Task WaitUntil(Func<bool> condition)
{
for (var i = 0; i < 500 && !condition(); i++)
{
await Task.Delay(10).ConfigureAwait(false);
}
Assert.IsTrue(condition(), "condizione non raggiunta in tempo");
}
}