From d97304d7b92929b4785a31cad652d211d710da66 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 09:29:01 +0100 Subject: [PATCH] Add the event-driven backtest engine and the strategy interface (refs #34) The strategy contract of SPEC 5.3 (IStrategy, StrategyContext, Intent) is shared by backtest and live: the context exposes bars only up to the decision, adjusted and anchored to that day, and reading past it throws. The engine runs each session as ordered events (corporate actions, open, session, close), decides on the close and executes at the next open with the simulator's price lists, slippage tiers, tick and lot rounding, minimums and no leverage. Corrective and risk hooks are wired in and pass everything through until Phase 5. One decision cycle can restart from a recorded book (SPEC 12.3). A scripted toy strategy reproduces a result computed by hand to the cent on OKX and Alpaca costs. The Phase 3 class Trading.Strategies becomes StrategyNames so the Anubis.Strategies namespace can exist. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/AccountsView.cs | 2 +- .../Components/Pages/Conti.razor | 2 +- .../Components/Pages/Impostazioni.razor | 2 +- src/Anubis/Backtest/Costs.cs | 94 +++ src/Anubis/Backtest/Dataset.cs | 186 ++++++ src/Anubis/Backtest/Engine.cs | 560 ++++++++++++++++++ src/Anubis/Strategies/Research.cs | 149 +++++ src/Anubis/Strategies/Strategy.cs | 232 ++++++++ src/Anubis/Trading/Capital.cs | 6 +- src/Anubis/Trading/TradingService.cs | 6 +- tests/Anubis.Tests/BacktestTests.cs | 285 +++++++++ tests/Anubis.Tests/BrokerConformanceTests.cs | 2 +- tests/Anubis.Tests/LedgerTests.cs | 46 +- tests/Anubis.Tests/OrderManagerTests.cs | 38 +- tests/Anubis.Tests/Property.cs | 8 + tests/Anubis.Tests/ReconcilerTests.cs | 14 +- tests/Anubis.Tests/TradingRulesTests.cs | 8 +- tests/Anubis.Tests/TradingServiceTests.cs | 28 +- tests/Anubis.Tests/TradingSupport.cs | 2 +- 19 files changed, 1592 insertions(+), 78 deletions(-) create mode 100644 src/Anubis/Backtest/Costs.cs create mode 100644 src/Anubis/Backtest/Dataset.cs create mode 100644 src/Anubis/Backtest/Engine.cs create mode 100644 src/Anubis/Strategies/Research.cs create mode 100644 src/Anubis/Strategies/Strategy.cs create mode 100644 tests/Anubis.Tests/BacktestTests.cs diff --git a/src/Anubis.Server/AccountsView.cs b/src/Anubis.Server/AccountsView.cs index 15f6f3b..5e7e8f0 100644 --- a/src/Anubis.Server/AccountsView.cs +++ b/src/Anubis.Server/AccountsView.cs @@ -136,7 +136,7 @@ internal sealed record AccountsView( var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol), positions, market.Open, market.Next, clock.UtcNow, zone); - var slices = Strategies.Base.Select(b => new StrategySlice(Strategies.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")", + var slices = StrategyNames.Base.Select(b => new StrategySlice(StrategyNames.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")", rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList(); decimal? fxEffect = null; if (cards.Count > 0) diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor index 9aa295e..8e3821a 100644 --- a/src/Anubis.Server/Components/Pages/Conti.razor +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -221,7 +221,7 @@ else @p.Symbol @p.Name @(p.Broker == Venues.Alpaca ? "Alpaca" : "OKX") - @Strategies.Label(p.Strategy) + @StrategyNames.Label(p.Strategy) @Format.Quantity(p.Quantity) @Format.Money(p.Average, p.Currency) @Format.Money(p.Last, p.Currency) diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 885e38d..52a35e8 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -118,7 +118,7 @@ } diff --git a/src/Anubis/Backtest/Costs.cs b/src/Anubis/Backtest/Costs.cs new file mode 100644 index 0000000..7f26ec2 --- /dev/null +++ b/src/Anubis/Backtest/Costs.cs @@ -0,0 +1,94 @@ +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// A fill of the backtest: quantity received or given, cash moved and fee, all in the dataset currency. +public sealed record CostedFill(decimal Quantity, decimal Price, decimal Gross, decimal CashFee, decimal CoinFee, decimal CashDelta) +{ + /// Every fee valued in the dataset currency: cash fees plus the coin kept by the venue at the fill price. + public decimal FeeValue => CashFee + DbValues.Money(CoinFee * Price); +} + +/// +/// The costs of SPEC 12.1 for a market order: the same price lists and slippage tiers as the internal simulator +/// (SPEC 7.3, ADR 0009 point 5), rounded the cautious way. scales fees and slippage +/// together, for the runs at double and triple costs of SPEC 12.2, step 3. +/// +public sealed record CostModel(decimal Multiplier = 1m) +{ + public static CostModel Standard { get; } = new(); + + /// The price list of the venue where the instrument would trade. Research archives trade like OKX. + public static PaperOptions PriceList(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + return spec.Venue == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(spec.QuoteCurrency); + } + + public decimal SlippageRate(InstrumentSpec spec) => PaperBroker.SlippageBp(spec) / 10_000m * Multiplier; + + /// The price paid or received: the reference moved by the slippage, rounded to the tick against us. + public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference) + { + ArgumentNullException.ThrowIfNull(spec); + var slip = SlippageRate(spec); + var price = side == OrderSide.Buy ? reference * (1m + slip) : reference * (1m - slip); + var tick = OrderRules.TickOf(spec, price); + price = tick is > 0m ? (side == OrderSide.Buy ? OrderRules.RoundUp(price, tick.Value) : OrderRules.RoundDown(price, tick.Value)) : price; + return DbValues.Money(price); + } + + /// The cost of a market order of at , as the venue would charge it. + public CostedFill Fill(InstrumentSpec spec, OrderSide side, decimal quantity, decimal price) + { + var list = PriceList(spec); + var taker = list.TakerFee * Multiplier; + var gross = DbValues.Money(quantity * price); + var share = list.ShareFee > 0m ? OrderRules.RoundUp(quantity * list.ShareFee * Multiplier, 0.01m) : 0m; + if (side == OrderSide.Buy) + { + if (list.FeeInKind) + { + var coin = DbValues.Money(quantity * taker); + return new CostedFill(quantity - coin, price, gross, 0m, coin, -gross); + } + + var fee = DbValues.Money(gross * taker) + share; + return new CostedFill(quantity, price, gross, fee, 0m, -(gross + fee)); + } + + var sellFee = DbValues.Money(gross * taker) + share + + (list.SellValueFee > 0m ? OrderRules.RoundUp(gross * list.SellValueFee * Multiplier, 0.01m) : 0m); + return new CostedFill(quantity, price, gross, sellFee, 0m, gross - sellFee); + } + + /// The largest quantity whose purchase, fees included, fits in : no leverage (SPEC 9.1). + public decimal Affordable(InstrumentSpec spec, decimal cash, decimal price) + { + ArgumentNullException.ThrowIfNull(spec); + if (cash <= 0m || price <= 0m) + { + return 0m; + } + + var list = PriceList(spec); + var perUnit = price * (1m + (list.FeeInKind ? 0m : list.TakerFee * Multiplier)) + (list.ShareFee * Multiplier); + var lot = OrderRules.LotOf(spec); + var quantity = OrderRules.RoundDown(cash / perUnit, lot); + // Fees rounded up to the cent can push the total a little past the cash: step back by the excess. + for (var guard = 0; guard < 8 && quantity > 0m; guard++) + { + var excess = -Fill(spec, OrderSide.Buy, quantity, price).CashDelta - cash; + if (excess <= 0m) + { + break; + } + + quantity = OrderRules.RoundDown(quantity - (excess / perUnit) - lot, lot); + } + + return Math.Max(quantity, 0m); + } +} diff --git a/src/Anubis/Backtest/Dataset.cs b/src/Anubis/Backtest/Dataset.cs new file mode 100644 index 0000000..1d2247e --- /dev/null +++ b/src/Anubis/Backtest/Dataset.cs @@ -0,0 +1,186 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Backtest; + +/// +/// One instrument of a backtest: its rules, its real daily bars (oldest first, one per day) and its corporate +/// actions. Signals read the bars adjusted and anchored to the decision day; executions use the real prices. +/// +public sealed class BacktestInstrument +{ + private readonly Dictionary _index; + + public BacktestInstrument(InstrumentSpec spec, IReadOnlyList bars, IReadOnlyList? actions = null, string source = "") + { + ArgumentNullException.ThrowIfNull(spec); + ArgumentNullException.ThrowIfNull(bars); + Spec = spec; + Bars = [.. bars.OrderBy(b => b.Day)]; + Actions = [.. (actions ?? []).Where(a => a.Symbol == spec.Symbol).OrderBy(a => a.ExDate)]; + Source = source; + _index = new Dictionary(Bars.Count); + for (var i = 0; i < Bars.Count; i++) + { + if (!_index.TryAdd(Bars[i].Day, i)) + { + throw new ArgumentException("Two bars on the same day for " + spec.Symbol, nameof(bars)); + } + } + + // Cumulative price factor of every bar: the product of the factors of the actions that come after it. A bar + // anchored to day A is the real bar times Factors[i] / Factors[A] (SPEC 6.10). + Factors = new double[Bars.Count]; + var running = 1d; + var next = Actions.Count - 1; + while (next >= 0 && Bars.Count > 0 && Actions[next].ExDate > Bars[^1].Day) + { + next--; + } + + for (var i = Bars.Count - 1; i >= 0; i--) + { + Factors[i] = running; + while (next >= 0 && Actions[next].ExDate > (i > 0 ? Bars[i - 1].Day : DateOnly.MinValue) && Actions[next].ExDate <= Bars[i].Day) + { + running *= Adjustments.PriceFactor(Actions[next], i > 0 ? Bars[i - 1].Close : null); + next--; + } + } + } + + public InstrumentSpec Spec { get; } + + public string Symbol => Spec.Symbol; + + public IReadOnlyList Bars { get; } + + public IReadOnlyList Actions { get; } + + /// Where the bars come from, in words for the report. + public string Source { get; } + + internal double[] Factors { get; } + + public int IndexOf(DateOnly day) => _index.TryGetValue(day, out var i) ? i : -1; + + /// Number of bars up to and including . + public int CountThrough(DateOnly day) + { + var lo = 0; + var hi = Bars.Count; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (Bars[mid].Day <= day) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo; + } + + public BarSeries SeriesThrough(DateOnly day) => new(Bars, Factors, CountThrough(day)); + + internal BacktestInstrument Through(DateOnly day) => + new(Spec, [.. Bars.Where(b => b.Day <= day)], [.. Actions.Where(a => a.ExDate <= day)], Source); +} + +/// +/// The data of a backtest: instruments in one currency, and the sessions (every day with at least one bar). Built +/// once and never changed, so the same dataset and parameters always give the same result (SPEC 12.1). +/// +public sealed class BacktestDataset +{ + private readonly Dictionary _bySymbol; + + public BacktestDataset(IEnumerable instruments, string currency) + { + ArgumentNullException.ThrowIfNull(instruments); + Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)]; + Currency = currency; + _bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal); + Sessions = [.. Instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Distinct().Order()]; + var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency); + if (wrong is not null) + { + throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments)); + } + } + + public IReadOnlyList Instruments { get; } + + public string Currency { get; } + + public IReadOnlyList Sessions { get; } + + public bool IsCrypto => Instruments.Count > 0 && Instruments.All(i => i.Spec.AssetClass == AssetClasses.Crypto); + + /// Sessions in a year, to annualise: crypto trades every day, stocks about 252 days. + public int PeriodsPerYear => IsCrypto ? 365 : 252; + + public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol); + + /// The same data cut after : what was known on that day (SPEC 12.2, step 2). + public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency); + + /// The same data between two days, both included. + public BacktestDataset Between(DateOnly from, DateOnly to) => new( + Instruments.Select(i => new BacktestInstrument(i.Spec, [.. i.Bars.Where(b => b.Day >= from && b.Day <= to)], [.. i.Actions.Where(a => a.ExDate > from && a.ExDate <= to)], i.Source)) + .Where(i => i.Bars.Count > 0), + Currency); + + /// + /// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were + /// computed on exactly the same data. + /// + public string Fingerprint() + { + var text = new StringBuilder(); + text.Append(Currency).Append('\n'); + foreach (var i in Instruments) + { + var s = i.Spec; + text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}\n"); + foreach (var b in i.Bars) + { + text.Append(CultureInfo.InvariantCulture, $"{b.Day:yyyy-MM-dd},{b.Open:R},{b.High:R},{b.Low:R},{b.Close:R},{b.Volume:R}\n"); + } + + foreach (var a in i.Actions) + { + text.Append(CultureInfo.InvariantCulture, $"{a.Kind},{a.ExDate:yyyy-MM-dd},{a.Ratio},{a.CashAmount}\n"); + } + } + + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } + + /// When a session opens and closes: crypto at midnight UTC (trap 23), stocks 09:30–16:00 in New York. + public (DateTimeOffset Opens, DateTimeOffset Closes) SessionTimes(DateOnly day) + { + if (IsCrypto) + { + var open = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + return (open, open.AddDays(1)); + } + + return (NewYork(day, new TimeOnly(9, 30)), NewYork(day, new TimeOnly(16, 0))); + } + + private static readonly TimeZoneInfo NewYorkZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + private static DateTimeOffset NewYork(DateOnly day, TimeOnly time) + { + var local = day.ToDateTime(time); + return new DateTimeOffset(local, NewYorkZone.GetUtcOffset(local)).ToUniversalTime(); + } +} diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs new file mode 100644 index 0000000..31be079 --- /dev/null +++ b/src/Anubis/Backtest/Engine.cs @@ -0,0 +1,560 @@ +using Anubis.Data; +using Anubis.Db; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// How a backtest runs (SPEC 12.1). +public sealed record BacktestOptions +{ + public decimal InitialCapital { get; init; } = 10_000m; + + public CostModel Costs { get; init; } = CostModel.Standard; + + /// First and last session simulated; null means the whole dataset. + public DateOnly? From { get; init; } + + public DateOnly? To { get; init; } + + /// The correctives of SPEC 8.5. Until Phase 5 they let everything through. + public IReadOnlyList Correctives { get; init; } = [PassThroughStage.Correctives]; + + /// The risk engine of SPEC 9. Until Phase 5 it lets everything through. + public IIntentStage Risk { get; init; } = PassThroughStage.Risk; +} + +/// A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3. +public sealed record PortfolioState(decimal Cash, IReadOnlyDictionary Holdings) +{ + public static PortfolioState OnlyCash(decimal cash) => new(cash, new Dictionary()); +} + +public sealed record EquityPoint(DateOnly Day, decimal Equity, decimal Cash, decimal Invested); + +/// An execution. is every fee valued in the dataset currency. +public sealed record BacktestFill(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity, decimal Price, decimal Gross, decimal Fee, string Reason); + +/// An operation from zero to zero (SPEC 7.5). is net of every cost; an open one is valued at the last close. +public sealed record BacktestTrade(string Symbol, DateOnly Opened, DateOnly? Closed, decimal Invested, decimal Result, decimal Fees) +{ + public bool IsClosed => Closed is not null; +} + +/// What the strategy proposed on a day, and what was left after correctives and risk. +public sealed record DecisionRecord(DateOnly Day, IReadOnlyList Proposed, IReadOnlyList Final); + +/// Something the engine did not do as asked, and why: an order below the minimum, no cash, no price. +public sealed record BacktestNote(DateOnly Day, string Symbol, string Reason); + +/// The outcome of one run of one strategy on one dataset. +public sealed record BacktestRun( + string Currency, + decimal InitialCapital, + IReadOnlyList Equity, + IReadOnlyList Fills, + IReadOnlyList Trades, + IReadOnlyList Decisions, + IReadOnlyList Notes) +{ + public decimal FinalEquity => Equity.Count > 0 ? Equity[^1].Equity : InitialCapital; + + public decimal NetResult => FinalEquity - InitialCapital; + + public decimal Fees => Fills.Sum(f => f.Fee); + + public decimal Dividends { get; init; } + + /// Value of the leftovers below the minimum written off after an exit (SPEC 7.2). + public decimal WrittenOff { get; init; } + + /// Daily returns of the equity, one per session after the first. + public double[] DailyReturns() + { + var result = new double[Math.Max(Equity.Count - 1, 0)]; + for (var i = 1; i < Equity.Count; i++) + { + var before = Equity[i - 1].Equity; + result[i - 1] = before > 0m ? (double)(Equity[i].Equity / before) - 1d : 0d; + } + + return result; + } +} + +/// Reasons the engine writes in fills and notes. +public static class BacktestReasons +{ + public const string Stop = "stop"; + public const string StopGap = "stop_gap"; + public const string WrittenOff = "residue_written_off"; + public const string NoCash = "no_cash"; + public const string NoPrice = "no_price"; + public const string UnknownSymbol = "unknown_symbol"; + public const string NoShortSelling = "no_short_selling"; + public const string Dividend = "dividend"; +} + +/// +/// The event-driven backtest engine (SPEC 12.1). Each session is a sequence of events in time order: corporate +/// actions before the open, the open (stops that open below their level, then the orders decided at the previous +/// close, sales first), the session (stops touched by the low), the close (valuation and decision). A decision sees +/// the data up to its close and its orders go at the next open: the delay between deciding and executing. The same +/// classes run live: the strategy cannot tell the difference. +/// +public static class BacktestEngine +{ + public static BacktestRun Run(IStrategy strategy, BacktestDataset data, BacktestOptions? options = null, PortfolioState? start = null) + { + ArgumentNullException.ThrowIfNull(strategy); + ArgumentNullException.ThrowIfNull(data); + options ??= new BacktestOptions(); + CheckSchedule(strategy); + var simulation = new Simulation(strategy, data, options, start ?? PortfolioState.OnlyCash(options.InitialCapital)); + // Ordered by time, then by day: a crypto close and the next open fall on the same midnight, and the close of + // the earlier day comes first. + var events = new PriorityQueue<(SessionEvent Kind, DateOnly Day), (DateTimeOffset At, int Day, int Order)>(); + foreach (var day in data.Sessions.Where(d => (options.From is null || d >= options.From) && (options.To is null || d <= options.To))) + { + var (opens, closes) = data.SessionTimes(day); + events.Enqueue((SessionEvent.CorporateActions, day), (opens, day.DayNumber, 0)); + events.Enqueue((SessionEvent.Open, day), (opens, day.DayNumber, 1)); + events.Enqueue((SessionEvent.Session, day), (opens, day.DayNumber, 2)); + events.Enqueue((SessionEvent.Close, day), (closes, day.DayNumber, 3)); + } + + while (events.TryDequeue(out var e, out var when)) + { + switch (e.Kind) + { + case SessionEvent.CorporateActions: + simulation.CorporateActions(e.Day); + break; + case SessionEvent.Open: + simulation.Open(e.Day); + break; + case SessionEvent.Session: + simulation.Session(e.Day); + break; + default: + simulation.Close(e.Day, when.At); + break; + } + } + + return simulation.Finish(); + } + + /// + /// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of + /// with the data known then and the book given, and nothing else runs. + /// + public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null) + { + ArgumentNullException.ThrowIfNull(strategy); + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(state); + CheckSchedule(strategy); + var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state); + simulation.MarkThrough(day); + return simulation.Decide(day, data.SessionTimes(day).Closes); + } + + private static void CheckSchedule(IStrategy strategy) + { + if (strategy.Schedule().Any(t => t.Anchor != DecisionAnchor.Close)) + { + throw new NotSupportedException($"{strategy.Id}: the daily backtest decides only on the close of a session"); + } + } + + private enum SessionEvent + { + CorporateActions, + Open, + Session, + Close, + } + + private sealed class Position + { + public decimal Quantity { get; set; } + + public decimal AveragePrice { get; set; } + + public decimal? Stop { get; set; } + + public DateOnly EnteredOn { get; init; } + + public required OpenTrade Trade { get; init; } + } + + private sealed class OpenTrade + { + public DateOnly Opened { get; init; } + + public decimal Bought { get; set; } + + public decimal CashFlow { get; set; } + + public decimal Fees { get; set; } + } + + private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason); + + private sealed class Simulation + { + private readonly IStrategy _strategy; + private readonly BacktestDataset _data; + private readonly BacktestOptions _options; + private readonly CostModel _costs; + private readonly SortedDictionary _positions = new(StringComparer.Ordinal); + private readonly SortedDictionary _pending = new(StringComparer.Ordinal); + private readonly Dictionary _lastClose = new(StringComparer.Ordinal); + private readonly Dictionary _actionsDoneThrough = new(StringComparer.Ordinal); + private readonly List _equity = []; + private readonly List _fills = []; + private readonly List _trades = []; + private readonly List _decisions = []; + private readonly List _notes = []; + private readonly decimal _initial; + private decimal _cash; + private decimal _dividends; + private decimal _writtenOff; + + public Simulation(IStrategy strategy, BacktestDataset data, BacktestOptions options, PortfolioState start) + { + _strategy = strategy; + _data = data; + _options = options; + _costs = options.Costs; + _cash = start.Cash; + var first = data.Sessions.FirstOrDefault(d => options.From is null || d >= options.From); + foreach (var (symbol, h) in start.Holdings.Where(h => h.Value.Quantity > 0m)) + { + var trade = new OpenTrade { Opened = h.EnteredOn, Bought = DbValues.Money(h.Quantity * h.AveragePrice), CashFlow = -DbValues.Money(h.Quantity * h.AveragePrice) }; + _positions[symbol] = new Position { Quantity = h.Quantity, AveragePrice = h.AveragePrice, Stop = h.Stop, EnteredOn = h.EnteredOn, Trade = trade }; + _lastClose[symbol] = h.AveragePrice; + } + + _initial = start.Cash + _positions.Values.Sum(p => p.Trade.Bought); + foreach (var i in data.Instruments) + { + _actionsDoneThrough[i.Symbol] = first == default ? DateOnly.MinValue : first.AddDays(-1); + } + } + + public void MarkThrough(DateOnly day) + { + foreach (var i in _data.Instruments) + { + var n = i.CountThrough(day); + if (n > 0) + { + _lastClose[i.Symbol] = Price(i.Bars[n - 1].Close); + } + } + } + + public void CorporateActions(DateOnly day) + { + foreach (var i in _data.Instruments) + { + var done = _actionsDoneThrough[i.Symbol]; + foreach (var action in i.Actions.Where(a => a.ExDate > done && a.ExDate <= day)) + { + Apply(i, action); + } + + _actionsDoneThrough[i.Symbol] = day; + } + } + + private void Apply(BacktestInstrument instrument, CorporateAction action) + { + var symbol = instrument.Symbol; + if (action.ChangesShares) + { + if (_positions.TryGetValue(symbol, out var p)) + { + p.Quantity = Adjustments.ConvertQuantity(p.Quantity, action); + p.AveragePrice = DbValues.Money(Adjustments.ConvertLevel(p.AveragePrice, action, null)); + p.Stop = p.Stop is { } s ? DbValues.Money(Adjustments.ConvertLevel(s, action, null)) : null; + } + + if (_pending.TryGetValue(symbol, out var order)) + { + _pending[symbol] = order with + { + Quantity = Adjustments.ConvertQuantity(order.Quantity, action), + Stop = order.Stop is { } s ? DbValues.Money(Adjustments.ConvertLevel(s, action, null)) : null, + }; + } + + if (_lastClose.TryGetValue(symbol, out var close)) + { + _lastClose[symbol] = DbValues.Money(Adjustments.ConvertLevel(close, action, null)); + } + } + else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m && _positions.TryGetValue(symbol, out var held) + && (action.Currency is null || action.Currency == _data.Currency)) + { + // To whoever held the shares at the close before the ex-date: that is the book now, before the open. + var amount = DbValues.Money(held.Quantity * action.CashAmount.Value); + _cash += amount; + _dividends += amount; + held.Trade.CashFlow += amount; + } + } + + public void Open(DateOnly day) + { + // Stops resting on the broker fill first when the price opens below them (SPEC 7.2, trap 24). + foreach (var (symbol, p) in _positions.ToList()) + { + if (Bar(symbol, day) is { } bar && p.Stop is { } stop && Price(bar.Open) <= stop) + { + Sell(day, symbol, p.Quantity, Price(bar.Open), BacktestReasons.StopGap, exit: true); + _pending.Remove(symbol); + } + } + + var due = _pending.Values.Where(o => Bar(o.Symbol, day) is not null).OrderBy(o => o.Side == OrderSide.Buy).ToList(); + foreach (var order in due) + { + _pending.Remove(order.Symbol); + var open = Price(Bar(order.Symbol, day)!.Open); + if (order.Side == OrderSide.Sell) + { + if (_positions.TryGetValue(order.Symbol, out var p)) + { + Sell(day, order.Symbol, order.Exit ? p.Quantity : Math.Min(order.Quantity, p.Quantity), open, order.Reason, order.Exit); + } + } + else + { + Buy(day, order, open); + } + } + } + + public void Session(DateOnly day) + { + foreach (var (symbol, p) in _positions.ToList()) + { + if (Bar(symbol, day) is { } bar && p.Stop is { } stop && Price(bar.Low) <= stop) + { + Sell(day, symbol, p.Quantity, Math.Min(stop, Price(bar.Open)), BacktestReasons.Stop, exit: true); + _pending.Remove(symbol); + } + } + } + + public void Close(DateOnly day, DateTimeOffset at) + { + MarkOn(day); + var invested = Invested(); + _equity.Add(new EquityPoint(day, _cash + invested, _cash, invested)); + var record = Decide(day, at); + _decisions.Add(record); + Plan(day, record.Final); + } + + public DecisionRecord Decide(DateOnly day, DateTimeOffset at) + { + var available = _data.Instruments.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList(); + var universe = _strategy.Universe(new UniverseContext(day, available)); + var equity = _cash + Invested(); + var holdings = _positions.ToDictionary(p => p.Key, p => new Holding(p.Value.Quantity, p.Value.AveragePrice, p.Value.Stop, p.Value.EnteredOn), StringComparer.Ordinal); + var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), + s => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty, s => _data[s]?.Spec); + var proposed = _strategy.Decide(context); + var final = proposed; + foreach (var stage in _options.Correctives) + { + final = stage.Apply(context, final); + } + + final = _options.Risk.Apply(context, final); + return new DecisionRecord(day, proposed, final); + } + + /// Turns the intents of a close into orders for the next open, sized on the equity of that close. + private void Plan(DateOnly day, IReadOnlyList intents) + { + var equity = _cash + Invested(); + foreach (var intent in intents.GroupBy(i => i.Symbol, StringComparer.Ordinal).Select(g => g.Last())) + { + var instrument = _data[intent.Symbol]; + if (instrument is null) + { + _notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.UnknownSymbol)); + continue; + } + + _positions.TryGetValue(intent.Symbol, out var p); + var stop = intent.Stop is { } level ? OrderRules.StopPrice(level, OrderRules.TickOf(instrument.Spec, level)) : (decimal?)null; + if (p is not null && stop is not null) + { + p.Stop = stop; + } + + if (intent.TargetWeight is not { } weight) + { + continue; + } + + if (weight < 0m) + { + _notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.NoShortSelling)); + continue; + } + + if (!_lastClose.TryGetValue(intent.Symbol, out var close) || close <= 0m) + { + _notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.NoPrice)); + continue; + } + + var current = p?.Quantity ?? 0m; + if (weight == 0m) + { + if (current > 0m) + { + _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Sell, current, Exit: true, null, intent.Reason); + } + else + { + _pending.Remove(intent.Symbol); + } + + continue; + } + + var target = weight * equity / close; + var difference = target - current; + if (difference > 0m) + { + _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason); + } + else if (difference < 0m) + { + _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Sell, -difference, Exit: false, null, intent.Reason); + } + } + } + + private void Buy(DateOnly day, Pending order, decimal reference) + { + var spec = _data[order.Symbol]!.Spec; + var price = _costs.ExecutionPrice(spec, OrderSide.Buy, reference); + var quantity = Math.Min(order.Quantity, _costs.Affordable(spec, _cash, price)); + if (quantity < order.Quantity) + { + // Less cash than the decision assumed (the open moved): the purchase shrinks, never borrows (SPEC 9.1). + _notes.Add(new BacktestNote(day, order.Symbol, BacktestReasons.NoCash)); + } + + var rounded = OrderRules.Round(spec, OrderSide.Buy, OrderKind.Market, quantity, price); + if (!rounded.IsValid) + { + if (quantity >= order.Quantity) + { + _notes.Add(new BacktestNote(day, order.Symbol, rounded.Rejection!)); + } + + return; + } + + var fill = _costs.Fill(spec, OrderSide.Buy, rounded.Quantity, price); + _cash += fill.CashDelta; + if (!_positions.TryGetValue(order.Symbol, out var p)) + { + p = new Position { EnteredOn = day, Trade = new OpenTrade { Opened = day } }; + _positions[order.Symbol] = p; + } + + p.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity)); + p.Quantity += fill.Quantity; + p.Stop = order.Stop ?? p.Stop; + p.Trade.Bought += fill.Gross; + p.Trade.CashFlow += fill.CashDelta; + p.Trade.Fees += fill.FeeValue; + _fills.Add(new BacktestFill(day, order.Symbol, OrderSide.Buy, rounded.Quantity, price, fill.Gross, fill.FeeValue, order.Reason)); + } + + private void Sell(DateOnly day, string symbol, decimal quantity, decimal reference, string reason, bool exit) + { + var p = _positions[symbol]; + var spec = _data[symbol]!.Spec; + var price = _costs.ExecutionPrice(spec, OrderSide.Sell, reference); + var rounded = OrderRules.Round(spec, OrderSide.Sell, OrderKind.Market, Math.Min(quantity, p.Quantity), price); + if (rounded.IsValid) + { + var fill = _costs.Fill(spec, OrderSide.Sell, rounded.Quantity, price); + _cash += fill.CashDelta; + p.Quantity -= rounded.Quantity; + p.Trade.CashFlow += fill.CashDelta; + p.Trade.Fees += fill.FeeValue; + _fills.Add(new BacktestFill(day, symbol, OrderSide.Sell, rounded.Quantity, price, fill.Gross, fill.FeeValue, reason)); + } + else if (!exit) + { + _notes.Add(new BacktestNote(day, symbol, rounded.Rejection!)); + return; + } + + // After an exit, what is below the minimum cannot be sold on its own: it is written off (SPEC 7.2). + if (p.Quantity > 0m && (exit || OrderRules.IsUnsellable(spec, p.Quantity, price))) + { + _writtenOff += DbValues.Money(p.Quantity * price); + _notes.Add(new BacktestNote(day, symbol, BacktestReasons.WrittenOff)); + p.Quantity = 0m; + } + + if (p.Quantity <= 0m) + { + _positions.Remove(symbol); + _trades.Add(new BacktestTrade(symbol, p.Trade.Opened, day, p.Trade.Bought, p.Trade.CashFlow, p.Trade.Fees)); + } + } + + public BacktestRun Finish() + { + foreach (var (symbol, p) in _positions) + { + var value = DbValues.Money(p.Quantity * _lastClose.GetValueOrDefault(symbol)); + _trades.Add(new BacktestTrade(symbol, p.Trade.Opened, null, p.Trade.Bought, p.Trade.CashFlow + value, p.Trade.Fees)); + } + + return new BacktestRun(_data.Currency, _initial, _equity, _fills, [.. _trades.OrderBy(t => t.Opened).ThenBy(t => t.Symbol, StringComparer.Ordinal)], _decisions, _notes) + { + Dividends = _dividends, + WrittenOff = _writtenOff, + }; + } + + private void MarkOn(DateOnly day) + { + foreach (var i in _data.Instruments) + { + if (Bar(i.Symbol, day) is { } bar) + { + _lastClose[i.Symbol] = Price(bar.Close); + } + } + } + + private decimal Invested() => _positions.Sum(p => DbValues.Money(p.Value.Quantity * _lastClose.GetValueOrDefault(p.Key))); + + private DailyBar? Bar(string symbol, DateOnly day) + { + var instrument = _data[symbol]; + var index = instrument?.IndexOf(day) ?? -1; + return index >= 0 ? instrument!.Bars[index] : null; + } + + /// Bars are analysis data in floating point; prices used for money become decimal here, once. + private static decimal Price(double value) => DbValues.Money((decimal)value); + } +} diff --git a/src/Anubis/Strategies/Research.cs b/src/Anubis/Strategies/Research.cs new file mode 100644 index 0000000..b74ee69 --- /dev/null +++ b/src/Anubis/Strategies/Research.cs @@ -0,0 +1,149 @@ +namespace Anubis.Strategies; + +/// +/// Buy at the first close in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2, +/// step 6. It decides only from its own book, so it can restart from any recorded state. +/// +public sealed class BuyAndHold : IStrategy +{ + /// A little cash stays aside for the fees, so the last purchase is not cut short. + public const decimal Invested = 0.995m; + + public string Id => BuyAndHoldFamily.FamilyId; + + public string Version => "1"; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.Available; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Portfolio.Holdings.Count > 0 || context.Universe.Count == 0) + { + return []; + } + + var weight = Invested / context.Universe.Count; + return [.. context.Universe.Select(s => new Intent(s, weight, "buy_and_hold"))]; + } +} + +public sealed class BuyAndHoldFamily : IStrategyFamily +{ + public const string FamilyId = "buy_and_hold"; + + public static BuyAndHoldFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => "1"; + + public string Name => "Comprare e tenere"; + + public string Description => "Compra in parti uguali alla prima chiusura e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla."; + + public IReadOnlyList Parameters => []; + + public IStrategy Create(StrategyParameters parameters) => new BuyAndHold(); +} + +/// +/// An example strategy to try the laboratory, not one of the bot's (those arrive with Phase 5): it holds an +/// instrument while the short average of its closes is above the long one. It has no strategy code, so it can never +/// send an order (SPEC 7.2). +/// +public sealed class MovingAverageCross(int fast, int slow) : IStrategy +{ + public string Id => MovingAverageCrossFamily.FamilyId; + + public string Version => "1"; + + public int Fast { get; } = fast; + + public int Slow { get; } = slow; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.Available; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var intents = new List(); + var weight = 1m / Math.Max(context.Universe.Count, 1); + foreach (var symbol in context.Universe) + { + var bars = context.Bars(symbol); + if (bars.Count < Slow) + { + continue; + } + + var closes = bars.Closes(Slow); + var slowAverage = closes.Average(); + var fastAverage = closes[^Fast..].Average(); + var held = context.Portfolio.Holds(symbol); + if (!held && fastAverage > slowAverage) + { + intents.Add(new Intent(symbol, weight, "average_cross_up")); + } + else if (held && fastAverage < slowAverage) + { + intents.Add(new Intent(symbol, 0m, "average_cross_down")); + } + } + + return intents; + } +} + +public sealed class MovingAverageCrossFamily : IStrategyFamily +{ + public const string FamilyId = "sma_cross"; + + public static MovingAverageCrossFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => "1"; + + public string Name => "Incrocio di medie (esempio)"; + + public string Description => "Strategia d'esempio per provare il laboratorio, non una di quelle del bot: tiene uno strumento finché la media breve dei prezzi di chiusura sta sopra la media lunga, in parti uguali tra gli strumenti scelti. Non manda mai ordini."; + + public IReadOnlyList Parameters => + [ + new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m), + new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m), + ]; + + public bool Accepts(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return parameters.Whole("fast") < parameters.Whole("slow"); + } + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return new MovingAverageCross(parameters.Whole("fast"), parameters.Whole("slow")); + } +} + +/// The strategies the laboratory can test. The bot's own strategies join with Phase 5. +public static class StrategyCatalog +{ + public static IReadOnlyList All { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance]; + + public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id); +} diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs new file mode 100644 index 0000000..5ac5241 --- /dev/null +++ b/src/Anubis/Strategies/Strategy.cs @@ -0,0 +1,232 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Strategies; + +/// Where in the market's day a decision is taken (SPEC 5.3: decision times follow the market calendar). +public enum DecisionAnchor +{ + /// After the close of the session, on its finished bar. Orders go at the next open. + Close, + + /// A given time after the open (live engine, Phase 6). The backtest of daily bars does not support it. + Open, +} + +/// When a strategy decides, expressed against the market calendar, never as a fixed clock time. +public sealed record DecisionTime(DecisionAnchor Anchor, TimeSpan Offset) +{ + public static DecisionTime AfterClose { get; } = new(DecisionAnchor.Close, TimeSpan.Zero); +} + +/// +/// What a strategy wants for one instrument (SPEC 5.2). is the share of the strategy's +/// equity to hold in the instrument after the next execution: 0 means exit. Null keeps the size and only updates the +/// stop. is a protective stop level in today's prices; null keeps the current one. +/// +public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason) +{ + public decimal? Stop { get; init; } + + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Symbol} {(TargetWeight is { } w ? w.ToString(CultureInfo.InvariantCulture) : "keep")} stop {(Stop is { } s ? s.ToString(CultureInfo.InvariantCulture) : "-")} ({Reason})"); +} + +/// Kinds of intent, as the one-step comparison of SPEC 12.3 reads them. +public enum IntentAction +{ + Enter, + Exit, + Resize, + Keep, +} + +/// A position as the strategy sees it: quantity, average entry price and stop in today's prices. +public sealed record Holding(decimal Quantity, decimal AveragePrice, decimal? Stop, DateOnly EnteredOn); + +/// The strategy's own book at the moment of the decision. +public sealed class PortfolioView(decimal cash, decimal equity, IReadOnlyDictionary holdings) +{ + public decimal Cash { get; } = cash; + + /// Cash plus positions at the last close. + public decimal Equity { get; } = equity; + + public IReadOnlyDictionary Holdings { get; } = holdings; + + public Holding? Of(string symbol) => Holdings.GetValueOrDefault(symbol); + + public bool Holds(string symbol) => Holdings.TryGetValue(symbol, out var h) && h.Quantity > 0m; +} + +/// +/// Daily bars of one instrument up to the moment of the decision and not beyond (SPEC 5.3). Prices are adjusted +/// for splits and dividends and anchored to the decision day, so the last bar shows the prices of today: signals +/// read adjusted prices, orders use real ones (trap 9). Index 0 is the oldest bar, − 1 today's. +/// Reading past today throws: there is no way to look ahead through this object. +/// +public sealed class BarSeries +{ + private readonly IReadOnlyList _bars; + private readonly double[] _factors; + private readonly double _anchor; + + internal BarSeries(IReadOnlyList bars, double[] factors, int count) + { + _bars = bars; + _factors = factors; + Count = count; + _anchor = count > 0 ? factors[count - 1] : 1d; + } + + public static BarSeries Empty { get; } = new([], [], 0); + + public int Count { get; } + + public DateOnly Day(int index) => Bar(index).Day; + + public Ohlc Prices(int index) => Bar(index).Prices.Scale(_factors[index] / _anchor); + + public double Close(int index) => Bar(index).Close * (_factors[index] / _anchor); + + public double High(int index) => Bar(index).High * (_factors[index] / _anchor); + + public double Low(int index) => Bar(index).Low * (_factors[index] / _anchor); + + public double Volume(int index) => Bar(index).Volume; + + /// The last closes, oldest first (fewer when the history is shorter). + public double[] Closes(int length) + { + var n = Math.Min(length, Count); + var result = new double[n]; + for (var i = 0; i < n; i++) + { + result[i] = Close(Count - n + i); + } + + return result; + } + + private DailyBar Bar(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + return _bars[index]; + } +} + +/// What a strategy may read to choose its instruments for a decision. +public sealed record UniverseContext(DateOnly Day, IReadOnlyList Available); + +/// Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly. +public sealed class StrategyParameters +{ + private readonly SortedDictionary _values; + + public StrategyParameters(IEnumerable> values) + { + _values = new SortedDictionary(StringComparer.Ordinal); + foreach (var (key, value) in values) + { + _values[key] = value; + } + } + + public static StrategyParameters None { get; } = new([]); + + public IReadOnlyDictionary Values => _values; + + public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name); + + public int Whole(string name) => (int)this[name]; + + /// A stable text such as fast=20;slow=100: equal parameters give equal text. + public override string ToString() => string.Join(';', _values.Select(p => p.Key + "=" + p.Value.ToString(CultureInfo.InvariantCulture))); +} + +/// +/// Everything a strategy may know when it decides (SPEC 5.3): data up to the decision and not beyond, its own book, +/// the instruments' rules. The same object in the backtest, in simulation and with real money: a strategy cannot +/// tell where it runs. +/// +public sealed class StrategyContext( + DateOnly day, + DateTimeOffset now, + IReadOnlyList universe, + PortfolioView portfolio, + Func bars, + Func spec) +{ + public DateOnly Day { get; } = day; + + public DateTimeOffset Now { get; } = now; + + /// Instruments the strategy chose for this decision. + public IReadOnlyList Universe { get; } = universe; + + public PortfolioView Portfolio { get; } = portfolio; + + public BarSeries Bars(string symbol) => bars(symbol); + + public InstrumentSpec? Spec(string symbol) => spec(symbol); +} + +/// A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else. +public interface IStrategy +{ + string Id { get; } + + string Version { get; } + + IReadOnlyList Schedule(); + + IReadOnlyList Universe(UniverseContext context); + + IReadOnlyList Decide(StrategyContext context); +} + +/// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results). +public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max); + +/// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. +public interface IStrategyFamily +{ + string Id { get; } + + string Version { get; } + + /// The name shown to the user, in Italian. + string Name { get; } + + /// What the strategy does, in plain Italian (SPEC 13.3). + string Description { get; } + + IReadOnlyList Parameters { get; } + + /// False for a point of the grid that makes no sense (a short average longer than the long one). + bool Accepts(StrategyParameters parameters) => true; + + IStrategy Create(StrategyParameters parameters); +} + +/// +/// A step between the strategy and the orders: the correctives of SPEC 8.5 and the risk engine of SPEC 9 plug in +/// here. Until Phase 5 both let everything through (SPEC 17, Phase 4). +/// +public interface IIntentStage +{ + string Name { get; } + + IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents); +} + +public sealed class PassThroughStage(string name) : IIntentStage +{ + public static PassThroughStage Correctives { get; } = new("correctives"); + + public static PassThroughStage Risk { get; } = new("risk"); + + public string Name { get; } = name; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) => intents; +} diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 66ba715..1aa5df5 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -5,7 +5,7 @@ using Anubis.Db; namespace Anubis.Trading; /// The three base strategies, their broker and their default share of its capital (SPEC 8.6). -public static class Strategies +public static class StrategyNames { public const string CryptoTrend = "crypto_trend"; public const string EquityMomentum = "equity_momentum"; @@ -82,7 +82,7 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false); var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); return rows.Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency, - r.Share ?? Strategies.Base.FirstOrDefault(b => b.Name == r.Strategy).Share, + r.Share ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Strategy).Share, given.Where(g => g.Account == r.Account && g.Strategy == r.Strategy).Sum(g => g.Amount), equities.Where(e => e.AccountId == r.Account && e.Strategy == r.Strategy).Sum(e => e.Cash))).ToList(); } @@ -95,7 +95,7 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx throw new CapitalException("Il capitale affidato non può essere negativo."); } - var currency = Strategies.CurrencyOf(broker); + var currency = StrategyNames.CurrencyOf(broker); var previous = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false); if (previous is not null && previous.AmountEur == amountEur) { diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index db316aa..6db06f5 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -96,7 +96,7 @@ public static class AccountSetup if (await s.CountAsync("SELECT COUNT(*) FROM accounts WHERE broker = @b AND environment = @e", ("b", broker), ("e", environment)).ConfigureAwait(false) == 0) { await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", cancellationToken, - ("id", Ids.NewId(clock)), ("n", NameOf(broker, environment)), ("b", broker), ("e", environment), ("c", Strategies.CurrencyOf(broker)), ("now", now)) + ("id", Ids.NewId(clock)), ("n", NameOf(broker, environment)), ("b", broker), ("e", environment), ("c", StrategyNames.CurrencyOf(broker)), ("now", now)) .ConfigureAwait(false); } } @@ -106,7 +106,7 @@ public static class AccountSetup // By default crypto runs in the internal simulator and stocks in the demo account (SPEC 7.1). A strategy // whose ledger is still empty follows the default when a demo account appears; one with a history stays. - foreach (var (strategy, broker, share) in Strategies.Base) + foreach (var (strategy, broker, share) in StrategyNames.Base) { var environment = broker == Venues.Alpaca && alpacaDemo ? TradingEnvironments.Demo : TradingEnvironments.Simulation; var target = accounts.First(a => a.Broker == broker && a.Environment == environment).AccountId; @@ -115,7 +115,7 @@ public static class AccountSetup if (current is null && await s.CountAsync("SELECT COUNT(*) FROM strategy_state WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) == 0) { await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, @sh)", - cancellationToken, ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", Strategies.Observation), ("j", new DbJson("{}")), ("now", now), ("sh", share)) + cancellationToken, ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", StrategyNames.Observation), ("j", new DbJson("{}")), ("now", now), ("sh", share)) .ConfigureAwait(false); } else if (current != target diff --git a/tests/Anubis.Tests/BacktestTests.cs b/tests/Anubis.Tests/BacktestTests.cs new file mode 100644 index 0000000..46038fd --- /dev/null +++ b/tests/Anubis.Tests/BacktestTests.cs @@ -0,0 +1,285 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// A strategy that says what it is told on given days: its result can be computed by hand. +internal sealed class ScriptedStrategy(IReadOnlyDictionary> script) : IStrategy +{ + public string Id => "scripted"; + + public string Version => "1"; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) => context.Available; + + public IReadOnlyList Decide(StrategyContext context) => script.GetValueOrDefault(context.Day) ?? []; +} + +internal static class BacktestData +{ + public static readonly DateOnly D1 = new(2026, 1, 5); + + public static InstrumentSpec Btc() => new(Venues.Okx, "BTC-EUR", "Bitcoin", AssetClasses.Crypto, "EUR") + { + BaseCurrency = "BTC", + TickSize = 0.1m, + LotSize = 0.00000001m, + MinSize = 0.00001m, + Status = "live", + }; + + public static InstrumentSpec Stock(string symbol = "AAPL") => new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD") + { + Fractionable = true, + Status = "active", + Exchange = "NASDAQ", + }; + + /// Five sessions (open, high, low, close) on consecutive days from . + public static IReadOnlyList FiveDays() => + [ + new(D1, 100, 101, 99, 100, 1000), + new(D1.AddDays(1), 100, 102, 99, 101, 1000), + new(D1.AddDays(2), 102, 104, 101, 103, 1000), + new(D1.AddDays(3), 103, 106, 102, 105, 1000), + new(D1.AddDays(4), 106, 107, 104, 106, 1000), + ]; + + public static BacktestDataset One(InstrumentSpec spec, IReadOnlyList bars, IReadOnlyList? actions = null) => + new([new BacktestInstrument(spec, bars, actions)], spec.QuoteCurrency); + + /// A random walk with a fixed seed: the same series at every run. + public static IReadOnlyList Walk(int days, ulong seed, double start = 100, double drift = 0.0003, double volatility = 0.02, DateOnly? from = null) + { + var gen = new Gen((int)(seed % int.MaxValue)); + var bars = new List(days); + var close = start; + var day = from ?? new DateOnly(2018, 1, 1); + for (var i = 0; i < days; i++) + { + var open = close; + var change = drift + (volatility * gen.Normal()); + close = Math.Round(open * Math.Exp(change), 2); + var high = Math.Round(Math.Max(open, close) * (1 + (0.005 * gen.Double())), 2); + var low = Math.Round(Math.Min(open, close) * (1 - (0.005 * gen.Double())), 2); + bars.Add(new DailyBar(day.AddDays(i), open, high, low, close, 1000)); + } + + return bars; + } +} + +/// The event engine, its costs and its records (issue #34, SPEC 12.1). +[TestClass] +public sealed class BacktestTests +{ + private static readonly DateOnly D1 = BacktestData.D1; + + private static ScriptedStrategy Script(params (DateOnly Day, Intent[] Intents)[] steps) => + new(steps.ToDictionary(s => s.Day, s => (IReadOnlyList)s.Intents)); + + [TestMethod] + [TestCategory(Category.Unit)] + public void AToyStrategyGivesExactlyTheResultComputedByHand() + { + // Half the capital in bitcoin at the first close, everything out at the third. By hand, with OKX's + // price list (0,20% taker kept in the coin bought, 5 bp of slippage, 0,1 € tick): + // buy at the open of day 2: 100 × 1,0005 = 100,05 → tick up → 100,1; 50 BTC = 5.005,00 €; fee 0,1 BTC + // received 49,9 BTC; cash 10.000 − 5.005 = 4.995,00 € + // sell at the open of day 4: 103 × 0,9995 = 102,9485 → tick down → 102,9; 49,9 × 102,9 = 5.134,71 €; + // fee 0,2% = 10,26942 €; cash 4.995 + 5.124,44058 = 10.119,44058 € + var strategy = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")]), (D1.AddDays(2), [new Intent("BTC-EUR", 0m, "exit")])); + var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestOptions { InitialCapital = 10_000m }); + + Assert.AreEqual(10_119.44058m, run.FinalEquity); + Assert.AreEqual(119.44058m, run.NetResult); + Assert.HasCount(2, run.Fills); + Assert.AreEqual(new BacktestFill(D1.AddDays(1), "BTC-EUR", OrderSide.Buy, 50m, 100.1m, 5_005m, 10.01m, "enter"), run.Fills[0]); + Assert.AreEqual(new BacktestFill(D1.AddDays(3), "BTC-EUR", OrderSide.Sell, 49.9m, 102.9m, 5_134.71m, 10.26942m, "exit"), run.Fills[1]); + Assert.AreEqual(20.27942m, run.Fees); + + var trade = run.Trades.Single(); + Assert.AreEqual(new BacktestTrade("BTC-EUR", D1.AddDays(1), D1.AddDays(3), 5_005m, 119.44058m, 20.27942m), trade); + + // Valued at every close: cash plus 49,9 BTC at 101 and 103 while held. + CollectionAssert.AreEqual( + new[] { 10_000m, 10_034.9m, 10_134.7m, 10_119.44058m, 10_119.44058m }, + run.Equity.Select(e => e.Equity).ToArray()); + Assert.IsEmpty(run.Notes); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheSameToyOnAStockPaysTheRegulatoryFeesRoundedUp() + { + // Alpaca: no commission, CAT 0,000003 $ a share on both sides and SEC 0,0000206 on sales, each rounded + // up to the cent; price step 0,01 $ above 1 $. By hand: + // buy 50 at 100 × 1,0005 = 100,05: 5.002,50 $ + CAT 0,01 → cash 4.997,49 $ + // sell 50 at 103 × 0,9995 = 102,9485 → 102,94: 5.147,00 $ − SEC 0,11 − CAT 0,01 → cash 10.144,37 $ + var strategy = Script((D1, [new Intent("AAPL", 0.5m, "enter")]), (D1.AddDays(2), [new Intent("AAPL", 0m, "exit")])); + var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Stock(), BacktestData.FiveDays())); + + Assert.AreEqual(10_144.37m, run.FinalEquity); + Assert.AreEqual(0.13m, run.Fees); + Assert.AreEqual(new BacktestTrade("AAPL", D1.AddDays(1), D1.AddDays(3), 5_002.5m, 144.37m, 0.13m), run.Trades.Single()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void StopsFillAtTheirLevelOrAtTheOpenWhenThePriceGapsBelow() + { + // Touched during the session: the low of day 2 (99) reaches the stop at 99,5, sold at 99,5 less slippage. + var touched = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter") { Stop = 99.5m }])); + var run = BacktestEngine.Run(touched, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays())); + var sale = run.Fills.Single(f => f.Side == OrderSide.Sell); + Assert.AreEqual((D1.AddDays(1), 99.4m, BacktestReasons.Stop), (sale.Day, sale.Price, sale.Reason)); + Assert.AreEqual(4_995m + 4_960.06m - 9.92012m, run.FinalEquity); + + // Opened below: the stop raised to 102,5 at the close of day 2 meets an open of 102 and sells there (trap 24). + var gapped = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")]), (D1.AddDays(1), [new Intent("BTC-EUR", null, "raise_stop") { Stop = 102.5m }])); + run = BacktestEngine.Run(gapped, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays())); + sale = run.Fills.Single(f => f.Side == OrderSide.Sell); + Assert.AreEqual((D1.AddDays(2), 101.9m, BacktestReasons.StopGap), (sale.Day, sale.Price, sale.Reason)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ASplitChangesSharesAndStopsButNotTheValueAndSignalsSeeOneSeries() + { + // A 2-for-1 split with ex-date on day 4: real prices halve, the adjusted series does not jump. + var bars = BacktestData.FiveDays().Select((b, i) => i >= 3 ? b with { Open = b.Open / 2, High = b.High / 2, Low = b.Low / 2, Close = b.Close / 2 } : b).ToList(); + var split = new CorporateAction("AAPL", CorporateActionKinds.Split, D1.AddDays(3), "test", "s1") { Ratio = 2m }; + var seen = new List(); + var strategy = new Recording(seen, Script((D1, [new Intent("AAPL", 0.5m, "enter") { Stop = 90m }]))); + var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Stock(), bars, [split])); + + // 50 shares became 100, the stop 90 became 45: nothing was sold and the value went on with the price. + Assert.HasCount(1, run.Fills); + Assert.AreEqual(4_997.49m + (100m * 53m), run.FinalEquity); + + // What the strategy saw on the last day: one continuous series in today's prices, no halving. + CollectionAssert.AreEqual(new[] { 50d, 50.5, 51.5, 52.5, 53 }, seen.ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void PurchasesNeverBorrowAndOrdersBelowTheMinimumAreNotSent() + { + // Two instruments at weight 0,8 each: the second purchase is cut to the cash left, never past it. + var data = new BacktestDataset( + [new BacktestInstrument(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestInstrument(BacktestData.Btc() with { Symbol = "ETH-EUR", BaseCurrency = "ETH" }, BacktestData.FiveDays())], + "EUR"); + var run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.8m, "a"), new Intent("ETH-EUR", 0.8m, "b")])), data); + Assert.IsTrue(run.Equity.All(e => e.Cash >= 0m), "Cash never goes below zero."); + Assert.IsTrue(run.Notes.Any(n => n.Symbol == "ETH-EUR" && n.Reason == BacktestReasons.NoCash)); + + // A purchase worth less than the minimum size is not sent and the note says why. + run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.00000001m, "tiny")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays())); + Assert.IsEmpty(run.Fills); + Assert.AreEqual(OrderReasons.BelowMinimumSize, run.Notes.Single().Reason); + + // Short selling is refused (SPEC 9.1). + run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", -0.5m, "short")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays())); + Assert.IsEmpty(run.Fills); + Assert.AreEqual(BacktestReasons.NoShortSelling, run.Notes.Single().Reason); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void DoubleCostsCostMoreAndTheSameInputsGiveTheSameRun() + { + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 7)); + var strategy = new MovingAverageCross(10, 40); + var once = BacktestEngine.Run(strategy, data); + var again = BacktestEngine.Run(new MovingAverageCross(10, 40), data); + CollectionAssert.AreEqual(once.Equity.ToArray(), again.Equity.ToArray()); + CollectionAssert.AreEqual(once.Fills.ToArray(), again.Fills.ToArray()); + Assert.IsGreaterThan(4, once.Trades.Count); + + var doubled = BacktestEngine.Run(strategy, data, new BacktestOptions { Costs = new CostModel(2m) }); + Assert.IsGreaterThan(once.Fees, doubled.Fees); + Assert.IsLessThan(once.FinalEquity, doubled.FinalEquity); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCorrectivesAndRiskHooksSeeEveryIntentAndCanChangeIt() + { + var seen = new List(); + var block = new Hook("risk", (ctx, intents) => + { + seen.AddRange(intents.Select(i => i.Symbol)); + return []; + }); + var run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestOptions { Risk = block }); + CollectionAssert.AreEqual(new[] { "BTC-EUR" }, seen); + Assert.IsEmpty(run.Fills); + Assert.HasCount(1, run.Decisions[0].Proposed); + Assert.IsEmpty(run.Decisions[0].Final); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OneCycleRestartsFromARecordedBook() + { + // The live book holds 49,9 BTC since day 2: the strategy decides on day 3 as if the backtest had run till then. + var book = new PortfolioState(4_995m, new Dictionary { ["BTC-EUR"] = new(49.9m, 100.3m, null, D1.AddDays(1)) }); + var exitWhenHeld = new ExitIfHeld(); + var record = BacktestEngine.DecideOnce(exitWhenHeld, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), book, D1.AddDays(2)); + Assert.AreEqual(D1.AddDays(2), record.Day); + Assert.AreEqual(new Intent("BTC-EUR", 0m, "held"), record.Proposed.Single()); + Assert.AreEqual(4_995m + (49.9m * 103m), exitWhenHeld.Equity, "The book is valued at that day's close."); + } + + private sealed class Recording(List seen, IStrategy inner) : IStrategy + { + public string Id => inner.Id; + + public string Version => inner.Version; + + public IReadOnlyList Schedule() => inner.Schedule(); + + public IReadOnlyList Universe(UniverseContext context) => inner.Universe(context); + + public IReadOnlyList Decide(StrategyContext context) + { + var bars = context.Bars("AAPL"); + if (bars.Count == 5) + { + seen.AddRange(bars.Closes(5)); + } + + return inner.Decide(context); + } + } + + private sealed class Hook(string name, Func, IReadOnlyList> apply) : IIntentStage + { + public string Name => name; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) => apply(context, intents); + } + + private sealed class ExitIfHeld : IStrategy + { + public decimal Equity { get; private set; } + + public string Id => "exit_if_held"; + + public string Version => "1"; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) => context.Available; + + public IReadOnlyList Decide(StrategyContext context) + { + Equity = context.Portfolio.Equity; + return [.. context.Universe.Where(context.Portfolio.Holds).Select(s => new Intent(s, 0m, "held"))]; + } + } +} diff --git a/tests/Anubis.Tests/BrokerConformanceTests.cs b/tests/Anubis.Tests/BrokerConformanceTests.cs index f3f7cc0..6ed6653 100644 --- a/tests/Anubis.Tests/BrokerConformanceTests.cs +++ b/tests/Anubis.Tests/BrokerConformanceTests.cs @@ -29,7 +29,7 @@ public abstract class BrokerConformance protected abstract string Environment { get; } private string ClientId() => - ClientOrderIds.Build(TradingRig.Installation, Environment, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1); + ClientOrderIds.Build(TradingRig.Installation, Environment, StrategyNames.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1); [TestMethod] public async Task TheVenueAnswersWithItsTimeAndItsCash() diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs index 34ed16d..57e8ab3 100644 --- a/tests/Anubis.Tests/LedgerTests.cs +++ b/tests/Anubis.Tests/LedgerTests.cs @@ -17,7 +17,7 @@ public sealed class LedgerTests await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); - const string strategy = Strategies.EquityMomentum; + const string strategy = StrategyNames.EquityMomentum; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false); var first = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 10m, 400m, 0.03m) with { ReferencePrice = 399.8m }, _none).ConfigureAwait(false); @@ -65,7 +65,7 @@ public sealed class LedgerTests await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); - const string strategy = Strategies.CryptoTrend; + const string strategy = StrategyNames.CryptoTrend; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 5000m, "EUR", "test", _none).ConfigureAwait(false); // OKX keeps the fee of a purchase in the bought coin (SPEC 4.2): 0.01 bought, 0.00001 kept. @@ -99,14 +99,14 @@ public sealed class LedgerTests var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false); var aapl = await rig.InstrumentAsync(TradingRig.Stock("AAPL")).ConfigureAwait(false); - await rig.Ledger.RecordCapitalAsync(okx.AccountId, Strategies.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false); - await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, Strategies.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(okx.AccountId, StrategyNames.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false); // A residue below the minimum is written off at market value as a cost: the trade closes (SPEC 7.2). - await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false); - await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false); - await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false); - Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false); + await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false); + await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false); + Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); var residue = (await rig.QueryAsync("SELECT quantity, value FROM residues", r => (Q: r.Money("quantity"), V: r.Money("value"))).ConfigureAwait(false)).Single(); Assert.AreEqual((50_000m, 0.55m), (residue.Q, residue.V)); var trade = (await rig.QueryAsync("SELECT status, realized FROM trades WHERE instrument_id = @i", r => (S: r.Text("status"), R: r.Money("realized")), ("i", pepe.Id)) @@ -116,23 +116,23 @@ public sealed class LedgerTests Assert.AreEqual(okxEquity.Result, trade.R, "The written-off value is a loss of the trade, nothing else."); // A dividend goes to whoever held the stock before the ex-date. - await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, Strategies.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false); + await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromDays(3)); - Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false)); - Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false)); - await rig.Ledger.RecordDividendAsync(alpaca.AccountId, Strategies.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false); + Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false)); + Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false)); + await rig.Ledger.RecordDividendAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false); // A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once. - await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false); + await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, 180m, _none).ConfigureAwait(false); var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); // A split whose ex-date came before the purchase changes nothing: those shares were new shares already. Assert.AreEqual(0m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-old", 2m, TradingRig.Start.AddDays(-30), _none).ConfigureAwait(false)); - Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); Assert.AreEqual(10m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false)); Assert.IsNull(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false), "Never twice."); - var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; + var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!; Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice)); - Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining)); + Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining)); var after = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); Assert.AreEqual(before.Equity, after.Equity); Assert.AreEqual(3002.5m, after.Equity, "Capital, plus the dividend; the position at its own price."); @@ -152,7 +152,7 @@ public sealed class LedgerTests var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR")).ConfigureAwait(false); - const string strategy = Strategies.CryptoTrend; + const string strategy = StrategyNames.CryptoTrend; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 100_000m, "EUR", "test", _none).ConfigureAwait(false); var gen = new Gen(Property.DefaultSeed); @@ -213,7 +213,7 @@ public sealed class LedgerTests var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false); await rig.Db.WriteAsync(async s => { - foreach (var (strategy, account, share) in new[] { (Strategies.CryptoTrend, okx, 1m), (Strategies.EquityMomentum, alpaca, 0.75m), (Strategies.EquityMeanrev, alpaca, 0.25m) }) + foreach (var (strategy, account, share) in new[] { (StrategyNames.CryptoTrend, okx, 1m), (StrategyNames.EquityMomentum, alpaca, 0.75m), (StrategyNames.EquityMeanrev, alpaca, 0.25m) }) { await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)", _none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share)) @@ -227,15 +227,15 @@ public sealed class LedgerTests var alpacaCapital = await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false); Assert.AreEqual(6600m, alpacaCapital.Amount); var strategies = await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false); - Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == Strategies.EquityMomentum).Capital); - Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == Strategies.EquityMeanrev).Capital); + Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == StrategyNames.EquityMomentum).Capital); + Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == StrategyNames.EquityMeanrev).Capital); var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx); await book.TakeAsync(_none).ConfigureAwait(false); // A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain. var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); - await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, Strategies.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false); + await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, StrategyNames.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false); await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(5)); await book.TakeAsync(_none).ConfigureAwait(false); @@ -244,7 +244,7 @@ public sealed class LedgerTests await book.TakeAsync(_none).ConfigureAwait(false); var series = await rig.QueryAsync("SELECT equity, flows, twr_index, drawdown_pct FROM equity_snapshots WHERE scope = 'strategy' AND strategy = @s ORDER BY taken_at", - r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", Strategies.CryptoTrend)).ConfigureAwait(false); + r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", StrategyNames.CryptoTrend)).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { 4000m, 4400m, 8400m }, series.Select(p => p.E).ToArray()); Assert.AreEqual(1.1m, series[^1].I); Assert.AreEqual(0.1m, Returns.TimeWeighted(series.Select(p => (p.E, p.F)).ToList())); @@ -260,6 +260,6 @@ public sealed class LedgerTests var error = await Assert.ThrowsExactlyAsync(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false); Assert.Contains("crypto_trend", error.Message); await Assert.ThrowsExactlyAsync(() => - capital.SetSharesAsync(Venues.Alpaca, new Dictionary { [Strategies.EquityMomentum] = 0.8m, [Strategies.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false); + capital.SetSharesAsync(Venues.Alpaca, new Dictionary { [StrategyNames.EquityMomentum] = 0.8m, [StrategyNames.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false); } } diff --git a/tests/Anubis.Tests/OrderManagerTests.cs b/tests/Anubis.Tests/OrderManagerTests.cs index 4844f2a..3aede63 100644 --- a/tests/Anubis.Tests/OrderManagerTests.cs +++ b/tests/Anubis.Tests/OrderManagerTests.cs @@ -38,10 +38,10 @@ public sealed class OrderManagerTests return new Setup(rig, account, instrument, paper, rig.Manager(paper, account, pendingSplit: pendingSplit)); } - private static TradeIntent Buy(Setup s, decimal quantity, decimal? stop = null, bool aggressive = false, string strategy = Strategies.CryptoTrend) => + private static TradeIntent Buy(Setup s, decimal quantity, decimal? stop = null, bool aggressive = false, string strategy = StrategyNames.CryptoTrend) => new(s.Instrument.Id, strategy, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StopLevel = stop, StartAggressive = aggressive }; - private static TradeIntent Sell(Setup s, decimal quantity, string strategy = Strategies.CryptoTrend) => + private static TradeIntent Sell(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend) => new(s.Instrument.Id, strategy, OrderSide.Sell, quantity, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)); private static Task> OrdersAsync(TradingRig rig) => @@ -75,7 +75,7 @@ public sealed class OrderManagerTests CollectionAssert.AreEqual(new[] { ">created", "created>submitted", "submitted>canceled" }, events.ToArray(), "Every transition is recorded."); // Held: 0.01 less the taker fee kept in coin. The slippage against the mid of the first order is measured. - var position = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!; + var position = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!; Assert.AreEqual((0.00998m, 57000m), (position.Quantity, position.StopPrice)); var slippage = (await s.Rig.QueryAsync("SELECT slippage_bp FROM fills", r => r.Money("slippage_bp")).ConfigureAwait(false)).Single(); Assert.IsTrue(slippage is > 0m and < 10m, slippage.ToString(System.Globalization.CultureInfo.InvariantCulture)); @@ -98,7 +98,7 @@ public sealed class OrderManagerTests var orders = await OrdersAsync(s.Rig).ConfigureAwait(false); Assert.HasCount(4, orders); Assert.IsTrue(orders.All(o => o.Status == "canceled")); - Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); Assert.IsEmpty(await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false), "Nothing left working."); } @@ -109,7 +109,7 @@ public sealed class OrderManagerTests await using var s = await OkxAsync().ConfigureAwait(false); await s.Manager.SubmitAsync(Buy(s, 0.01m, stop: 40000m, aggressive: true), _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); - var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; // No price at all: the sale waits, and the stops stay on the broker until it can really leave. s.Rig.QuotesDown = true; @@ -151,12 +151,12 @@ public sealed class OrderManagerTests } TradeIntent BuyOf(Instrument coin, bool aggressive = false) => - new(coin.Id, Strategies.CryptoTrend, OrderSide.Buy, 1m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StartAggressive = aggressive, StopLevel = 90m }; + new(coin.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 1m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StartAggressive = aggressive, StopLevel = 90m }; // A position to sell later. await s.Manager.SubmitAsync(BuyOf(coins[8], aggressive: true), _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 2, TimeSpan.FromMinutes(2)).ConfigureAwait(false); - var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, coins[8].Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, coins[8].Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; var buys = new List(); foreach (var coin in coins.Take(8)) @@ -164,7 +164,7 @@ public sealed class OrderManagerTests buys.Add((await s.Manager.SubmitAsync(BuyOf(coin), _none).ConfigureAwait(false)).Execution!.Value); } - var sale = (await s.Manager.SubmitAsync(new TradeIntent(coins[8].Id, Strategies.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)), _none) + var sale = (await s.Manager.SubmitAsync(new TradeIntent(coins[8].Id, StrategyNames.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)), _none) .ConfigureAwait(false)).Execution!.Value; await s.Rig.TurnsAsync(s.Manager, 1, TimeSpan.FromSeconds(30)).ConfigureAwait(false); @@ -193,7 +193,7 @@ public sealed class OrderManagerTests public async Task AlpacaStopsAreGtcForWholeSharesAndDayForTheFractionAndFollowEveryChange() { await using var s = await AlpacaAsync().ConfigureAwait(false); - await s.Manager.SubmitAsync(Buy(s, 10.5m, stop: 380m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false); + await s.Manager.SubmitAsync(Buy(s, 10.5m, stop: 380m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); var stops = (await OrdersAsync(s.Rig).ConfigureAwait(false)).Where(o => o.Purpose == "stop" && o.Status == "submitted").OrderBy(o => o.Quantity).ToList(); Assert.AreEqual(2, stops.Count); @@ -202,7 +202,7 @@ public sealed class OrderManagerTests Assert.IsTrue(stops.All(o => o.Stop == 380m && o.Kind == "stop")); // Adding to the position: Alpaca refuses a buy with a sell stop open, so the stops leave, the buy goes, they come back. - await s.Manager.SubmitAsync(Buy(s, 5m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false); + await s.Manager.SubmitAsync(Buy(s, 5m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); var all = await OrdersAsync(s.Rig).ConfigureAwait(false); Assert.IsTrue(stops.All(old => all.Single(o => o.ClientId == old.ClientId).Status == "canceled")); @@ -215,7 +215,7 @@ public sealed class OrderManagerTests s.Rig.Quote("MSFT", 379m, 379.20m); await s.Paper.PumpAsync(_none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false); - Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false)); var protective = (await OrdersAsync(s.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "protective"); Assert.AreEqual(("market", 0.5m, "filled"), (protective.Kind, protective.Quantity, protective.Status)); Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single()); @@ -231,9 +231,9 @@ public sealed class OrderManagerTests await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); // The level to place is already above the price: the stop counts as fired (SPEC 7.2). - await s.Rig.Ledger.SetStopAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, 61000m, _none).ConfigureAwait(false); + await s.Rig.Ledger.SetStopAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, 61000m, _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false); - Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); Assert.AreEqual("market", (await OrdersAsync(s.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "protective").Kind); Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single()); Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'stop_already_passed'", r => r.Id("id")).ConfigureAwait(false)); @@ -248,15 +248,15 @@ public sealed class OrderManagerTests applied = true; return Task.FromResult(first ? new CorporateAction(instrument.Symbol, CorporateActionKinds.Split, new DateOnly(2026, 11, 11), "test", "split-msft") { Ratio = 4m } : null); }).ConfigureAwait(false); - await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false); + await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false); await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false); a.Rig.Clock.Advance(TimeSpan.FromDays(1)); a.Rig.Quote("MSFT", 100m, 100.05m); - await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, Strategies.EquityMomentum, 380m, _none).ConfigureAwait(false); + await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, StrategyNames.EquityMomentum, 380m, _none).ConfigureAwait(false); await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false); Assert.IsTrue(applied); - var position = (await a.Rig.Ledger.PositionAsync(a.Account.AccountId, a.Instrument.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; + var position = (await a.Rig.Ledger.PositionAsync(a.Account.AccountId, a.Instrument.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!; Assert.AreEqual((40m, 95m), (position.Quantity, position.StopPrice)); Assert.IsFalse((await OrdersAsync(a.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "protective")); var stop = (await OrdersAsync(a.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "stop" && o.Status == "submitted"); @@ -282,7 +282,7 @@ public sealed class OrderManagerTests Assert.HasCount(1, faulty.Sent.Where(r => r.ClientOrderId == lost.ClientId).ToList(), "Sent once."); Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false)); Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM fills", r => r.Id("id")).ConfigureAwait(false), "Every fill was reported twice, recorded once."); - Assert.AreEqual(0.00998m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(0.00998m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); // A refused buy ends, with its reason in the diary. faulty.RejectNext = "insufficient"; @@ -305,14 +305,14 @@ public sealed class OrderManagerTests await using var s = await OkxAsync(TradingRig.Pepe, bid: 0.00001m, ask: 0.00001001m).ConfigureAwait(false); await s.Manager.SubmitAsync(Buy(s, 10_000_000m, aggressive: true), _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); - var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; Assert.AreEqual(9_980_000m, held); s.Rig.Quote("PEPE-EUR", 0.0000099m, 0.00000991m); var (execution, _) = await s.Manager.SubmitAsync(Sell(s, 9_900_000m) with { StartAggressive = true }, _none).ConfigureAwait(false); await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false); Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false)); - Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); var residue = (await s.Rig.QueryAsync("SELECT quantity, reason FROM residues", r => (Q: r.Money("quantity"), R: r.Text("reason"))).ConfigureAwait(false)).Single(); Assert.AreEqual((80_000m, "below_minimum"), (residue.Q, residue.R)); Assert.AreEqual(("closed", "residue"), (await s.Rig.QueryAsync("SELECT status, exit_reason FROM trades", r => (r.Text("status"), r.Text("exit_reason"))).ConfigureAwait(false)).Single()); diff --git a/tests/Anubis.Tests/Property.cs b/tests/Anubis.Tests/Property.cs index 9e32c7f..51bbca6 100644 --- a/tests/Anubis.Tests/Property.cs +++ b/tests/Anubis.Tests/Property.cs @@ -69,6 +69,14 @@ internal sealed class Gen(int seed) /// Uniform value in [0, 1). public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53)); + /// A standard normal value (Box–Muller), for synthetic price series and returns. + public double Normal() + { + var u = 1.0 - Double(); + var v = Double(); + return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v); + } + /// A decimal in [, ] with at most decimals. public decimal Decimal(decimal min, decimal max, int scale) { diff --git a/tests/Anubis.Tests/ReconcilerTests.cs b/tests/Anubis.Tests/ReconcilerTests.cs index baeac8b..181934f 100644 --- a/tests/Anubis.Tests/ReconcilerTests.cs +++ b/tests/Anubis.Tests/ReconcilerTests.cs @@ -25,11 +25,11 @@ public sealed class ReconcilerTests var instrument = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false); - await rig.Ledger.RecordCapitalAsync(account.AccountId, Strategies.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false); rig.Quote(instrument.Symbol, 60000m, 60010m); var broker = new FaultyBroker(paper, environment); var manager = rig.Manager(broker, account); - await manager.SubmitAsync(new TradeIntent(instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) + await manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 57000m, StartAggressive = true, @@ -52,7 +52,7 @@ public sealed class ReconcilerTests private static Task> CodesAsync(TradingRig rig, string code) => rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", code)); - private static TradeIntent Entry(Setup s) => new(s.Instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)); + private static TradeIntent Entry(Setup s) => new(s.Instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)); [TestMethod] [TestCategory(Category.Simulation)] @@ -77,11 +77,11 @@ public sealed class ReconcilerTests s.Rig.Quote("BTC-EUR", 56000m, 56010m); await s.Paper.PumpAsync(_none).ConfigureAwait(false); Assert.IsEmpty(await s.Paper.GetPositionsAsync(_none).ConfigureAwait(false)); - Assert.IsNotNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.IsNotNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); Assert.AreEqual((ReconcileOutcomes.Healed, AccountModes.Normal), (report.Outcome, report.Mode), string.Join("; ", report.Differences.Select(d => d.Message))); - Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single()); Assert.HasCount(1, await CodesAsync(s.Rig, "reconcile_healed").ConfigureAwait(false)); Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM reconciliations WHERE outcome = 'healed'", r => r.Id("id")).ConfigureAwait(false)); @@ -132,7 +132,7 @@ public sealed class ReconcilerTests // Align: the ledger takes the account's number with an adjustment, and the account is normal again. await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false); - Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); Assert.AreEqual((AccountModes.Normal, ReconcileOutcomes.UserAligned), (state.Mode, state.LastOutcome)); Assert.HasCount(1, await CodesAsync(s.Rig, "account_resolved").ConfigureAwait(false)); @@ -148,7 +148,7 @@ public sealed class ReconcilerTests public async Task AnUnknownOrderOfThisInstallationIsReportedAndCanBeLeftOut() { await using var s = await HoldingAsync().ConfigureAwait(false); - var stray = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(Guid.NewGuid()), 1); + var stray = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(Guid.NewGuid()), 1); await s.Paper.SubmitOrderAsync(new OrderRequest(stray, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50000m }, _none).ConfigureAwait(false); // Someone else's order on the same account is none of the bot's business. diff --git a/tests/Anubis.Tests/TradingRulesTests.cs b/tests/Anubis.Tests/TradingRulesTests.cs index 1af0f4d..c2ad216 100644 --- a/tests/Anubis.Tests/TradingRulesTests.cs +++ b/tests/Anubis.Tests/TradingRulesTests.cs @@ -22,7 +22,7 @@ public sealed class TradingRulesTests Assert.AreEqual(installation, ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"))); Assert.AreEqual(key, ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001"))); - var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297); + var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297); Assert.AreEqual(ClientOrderIds.Length, id.Length); Assert.IsLessThanOrEqualTo(32, id.Length); Assert.IsTrue(id.StartsWith("ANU", StringComparison.Ordinal)); @@ -31,16 +31,16 @@ public sealed class TradingRulesTests // From the id alone: strategy, environment, purpose and progressive (SPEC 7.2, 15.1). var parts = ClientOrderIds.Parse(id); Assert.IsNotNull(parts); - Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297), parts); + Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297), parts); Assert.IsTrue(ClientOrderIds.IsOurs(id, installation)); Assert.IsFalse(ClientOrderIds.IsOurs(id, "ZZZZ"), "Another installation's order is not ours."); Assert.IsFalse(ClientOrderIds.IsOurs("my-own-order-123", installation), "The user's own orders are never touched."); Assert.IsNull(ClientOrderIds.Parse(null)); // Every progressive gives a different id; the next one is a different order. - Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1298)); + Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1298)); Assert.ThrowsExactly(() => - ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1)); + ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1)); Assert.ThrowsExactly(() => ClientOrderIds.Build(installation, TradingEnvironments.Demo, "unknown", OrderPurpose.Entry, key, 1)); } diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs index bd943d8..95b2db1 100644 --- a/tests/Anubis.Tests/TradingServiceTests.cs +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -36,9 +36,9 @@ public sealed class TradingServiceTests // Every strategy starts in observation, crypto on OKX and stocks on Alpaca. CollectionAssert.AreEqual(new[] { - (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), - (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), - (Strategies.EquityMomentum, "Alpaca simulatore", Strategies.Observation), + (StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation), + (StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation), + (StrategyNames.EquityMomentum, "Alpaca simulatore", StrategyNames.Observation), }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray()); // A second start finds what is there. @@ -55,16 +55,16 @@ public sealed class TradingServiceTests await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none).ConfigureAwait(false); var simulator = accounts.Single(a => a.Broker == Venues.Alpaca); - await rig.Ledger.RecordCapitalAsync(simulator.AccountId, Strategies.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(simulator.AccountId, StrategyNames.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false); accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: true, okxDemo: false, _none).ConfigureAwait(false); Assert.HasCount(3, accounts); Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2)."); CollectionAssert.AreEqual(new[] { - (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), - (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), - (Strategies.EquityMomentum, "Alpaca paper", Strategies.Observation), + (StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation), + (StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation), + (StrategyNames.EquityMomentum, "Alpaca paper", StrategyNames.Observation), }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is."); } @@ -91,7 +91,7 @@ public sealed class TradingServiceTests Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false)); Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call."); var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false); - CollectionAssert.AreEqual(new[] { (Strategies.CryptoTrend, 1000m), (Strategies.EquityMeanrev, 550m), (Strategies.EquityMomentum, 1650m) }, shares.ToArray()); + CollectionAssert.AreEqual(new[] { (StrategyNames.CryptoTrend, 1000m), (StrategyNames.EquityMeanrev, 550m), (StrategyNames.EquityMomentum, 1650m) }, shares.ToArray()); // The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate. await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 10), 1.05m, "ecb")], _none).ConfigureAwait(false); @@ -110,8 +110,8 @@ public sealed class TradingServiceTests var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); await service.StartAsync(_none).ConfigureAwait(false); var account = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca).Account; - await service.Ledger.RecordCapitalAsync(account.AccountId, Strategies.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); - await service.Ledger.RecordFillAsync(rig.Fill(account, msft, Strategies.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); + await service.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); // Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. A split of last // month is still in the table: it came before the purchase and must change nothing. @@ -129,18 +129,18 @@ public sealed class TradingServiceTests await service.CorporateActionsAsync(_none).ConfigureAwait(false); Assert.IsEmpty(await DividendsAsync().ConfigureAwait(false), "Nothing before the ex-date."); - Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares."); + Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares."); rig.Clock.Advance(TimeSpan.FromDays(1)); await service.CorporateActionsAsync(_none).ConfigureAwait(false); await service.CorporateActionsAsync(_none).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { 7.5m }, (await DividendsAsync().ConfigureAwait(false)).ToArray()); - Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); rig.Clock.Advance(TimeSpan.FromDays(1)); await service.CorporateActionsAsync(_none).ConfigureAwait(false); await service.CorporateActionsAsync(_none).ConfigureAwait(false); - var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; + var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!; Assert.AreEqual((20m, 200m), (position.Quantity, position.AveragePrice)); Assert.HasCount(1, await DividendsAsync().ConfigureAwait(false)); Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false)); @@ -149,6 +149,6 @@ public sealed class TradingServiceTests // Every photograph values the positions at the market, not at their last fill. service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow)); await service.PhotographAsync(_none).ConfigureAwait(false); - Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice); + Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice); } } diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index f214f53..9456b3a 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -46,7 +46,7 @@ internal sealed class TradingRig : IAsyncDisposable public async Task 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)); + 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;