Replay the past of a rebuilt account in its order
What an account did while the bot was off is now written before the splits and the dividends of those days, once and without acting on it; an attempt cut halfway is taken up from the same point. Until then the account is not valued at today's price, the guard keeps the last figures it knew with their time, and a stop order only cancels what is open. Protective sales of the archive are not continued, and the rest of a stop that fired in part is sold. Also the decisions of the phase (ADR 0020), the manuals and the dates under the equity chart. refs #69 #72 #75 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e58a26e8fa
commit
76b64ef147
31 files changed
+957
-130
No files matched your search
@@ -152,7 +152,8 @@ internal sealed partial class AnubisHost(
|
||||
|
||||
/// <summary>
|
||||
/// A choice that failed or was cut halfway leaves nothing open that could create the missing file, and what it had
|
||||
/// begun to write steps aside: moved and not deleted, because in the meantime the true file may have come back.
|
||||
/// begun to write steps aside, moved and not deleted. In the meantime the true file may have come back: that one is
|
||||
/// not touched, and the loop finds it.
|
||||
/// </summary>
|
||||
internal async Task AbandonChoiceAsync()
|
||||
{
|
||||
@@ -165,6 +166,11 @@ internal sealed partial class AnubisHost(
|
||||
_db = null;
|
||||
_createdByChoice = false;
|
||||
var path = Config.Db!.SqlitePath!;
|
||||
if (!File.Exists(path) || !await IsLeftoverAsync().ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var aside = path + ".incompleto-" + clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture);
|
||||
foreach (var part in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
@@ -182,6 +188,31 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file a choice left halfway: without an installation, or with the sealed one of an import not renewed yet. One
|
||||
/// that cannot be read is not certainly that.
|
||||
/// </summary>
|
||||
private async Task<bool> IsLeftoverAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(Config.Db!, allowCreate: false);
|
||||
if ((await Migrations.StatusAsync(db, CancellationToken.None).ConfigureAwait(false)).IsEmpty)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var row = await Installation.ReadRowAsync(db, CancellationToken.None).ConfigureAwait(false);
|
||||
return row is null ? !await Installation.HasDataAsync(db, CancellationToken.None).ConfigureAwait(false)
|
||||
: row.ProtectedRestart && row.Fingerprint != Installation.ReadFile(Config.Data)?.Fingerprint;
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException)
|
||||
{
|
||||
LogStepFailed(logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The choice is done: the database it opened is the one in use.</summary>
|
||||
internal void KeepChoice() => _createdByChoice = false;
|
||||
|
||||
|
||||
@@ -310,6 +310,9 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.chart-axis { position: relative; }
|
||||
.chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; }
|
||||
.chart-plot { position: relative; }
|
||||
.chart-days { position: relative; height: 18px; margin: 8px 84px 0 64px; }
|
||||
.chart-days span { position: absolute; transform: translateX(-50%); color: var(--text-3); font-size: 13px; white-space: nowrap; }
|
||||
.chart-days span:first-child { transform: none; }
|
||||
.chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
||||
.chart .grid { stroke: var(--rule-inner); stroke-width: 1; }
|
||||
.chart .area { fill: var(--text); opacity: .05; }
|
||||
@@ -796,7 +799,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; }
|
||||
.half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; }
|
||||
.half + .half { border-left: 1px solid var(--rule); }
|
||||
.segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; }
|
||||
.segmented, .cell-change, .cell-extra, .long, .chart-axis, .chart-days { display: none; }
|
||||
.lead { margin-top: 12px; }
|
||||
.big-result { gap: 12px; }
|
||||
.big-number { font-size: 46px; line-height: 48px; }
|
||||
|
||||
@@ -48,6 +48,12 @@
|
||||
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Text(Points[^1].Equity, 0)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-days" aria-hidden="true">
|
||||
@foreach (var i in Days())
|
||||
{
|
||||
<span style="left:@Pct(X(i) / 10)">@Format.AxisDay(Points[i].Day, Points[^1].Day.DayNumber - Points[0].Day.DayNumber)</span>
|
||||
}
|
||||
</div>
|
||||
<figcaption class="legend">
|
||||
<span class="key key-equity">@EquityLabel</span>
|
||||
@if (benchLine.Length > 0)
|
||||
@@ -102,6 +108,9 @@
|
||||
|
||||
private string Text(decimal amount, int decimals = 2) => Native ? Format.Money(amount, Currency, decimals: decimals) : Shell.Money(amount, Currency, decimals: decimals);
|
||||
|
||||
// Five dates at even distances, first and last included; fewer when there are not enough days.
|
||||
private IEnumerable<int> Days() => Enumerable.Range(0, 5).Select(i => i * (Points.Count - 1) / 4).Distinct();
|
||||
|
||||
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||
|
||||
@@ -166,6 +166,11 @@ public static class Format
|
||||
public static string LongDate(DateOnly date) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{date.Day} {_monthsLong[date.Month - 1]} {date.Year}");
|
||||
|
||||
/// <summary>A day under a chart that covers <paramref name="span"/> days: <c>12 ago</c>, or <c>ago 2024</c> over more than a year.</summary>
|
||||
public static string AxisDay(DateOnly day, int span) => span > 370
|
||||
? string.Create(CultureInfo.InvariantCulture, $"{_months[day.Month - 1]} {day.Year}")
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{day.Day} {_months[day.Month - 1]}");
|
||||
|
||||
/// <summary>How long ago, in words: <c>4 secondi fa</c>, <c>3 minuti fa</c>.</summary>
|
||||
public static string Ago(TimeSpan elapsed)
|
||||
{
|
||||
|
||||
@@ -561,8 +561,11 @@ public sealed partial class MarketDataService : IDisposable
|
||||
await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Splits and dividends of the stock universe from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10).</summary>
|
||||
public async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken)
|
||||
/// <summary>Splits and dividends of the stocks the bot follows or still owes for, from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10).</summary>
|
||||
public Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) => RefreshCorporateActionsAsync([], null, cancellationToken);
|
||||
|
||||
/// <summary>The same with more symbols, at least back to <paramref name="since"/>: what a rebuild of an account is about to write.</summary>
|
||||
public async Task RefreshCorporateActionsAsync(IReadOnlyCollection<string> more, DateOnly? since, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca)
|
||||
{
|
||||
@@ -570,8 +573,15 @@ public sealed partial class MarketDataService : IDisposable
|
||||
}
|
||||
|
||||
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
|
||||
var universe = await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false);
|
||||
if (universe.Count == 0)
|
||||
var symbols = (await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false)).Select(m => m.Symbol).Concat(more)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
// Also what is held or was sold lately and left the universe: its splits and dividends are still owed.
|
||||
symbols.UnionWith(await _db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (EXISTS (SELECT 1 FROM positions p WHERE p.instrument_id = i.id) " +
|
||||
"OR EXISTS (SELECT 1 FROM fills f WHERE f.instrument_id = i.id AND f.executed_at >= @at))", r => r.Text("symbol"),
|
||||
("v", Venues.Alpaca), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false));
|
||||
if (symbols.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -580,11 +590,18 @@ public sealed partial class MarketDataService : IDisposable
|
||||
var last = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT created_at FROM corporate_actions ORDER BY created_at DESC LIMIT 1", r => r.Moment("created_at"))
|
||||
.ConfigureAwait(false)).Select(m => (DateTimeOffset?)m).FirstOrDefault(), cancellationToken).ConfigureAwait(false);
|
||||
var from = last is { } known && DateOnly.FromDateTime(known.UtcDateTime) < today ? DateOnly.FromDateTime(known.UtcDateTime) : today;
|
||||
var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (since is { } far && far < from)
|
||||
{
|
||||
from = far;
|
||||
}
|
||||
|
||||
var actions = await alpaca.FetchCorporateActionsAsync(symbols.Order(StringComparer.Ordinal).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken).ConfigureAwait(false);
|
||||
await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>How long a stock sold still owes the dividends of when it was held: a rebuild or a long stop brings them late.</summary>
|
||||
public static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90);
|
||||
|
||||
private async Task PruneAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await new BarStore(_db, _clock).PruneMinutesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -108,7 +108,7 @@ public static class Installation
|
||||
|
||||
private static readonly string[] _dataTables = ["users", "accounts", "orders", "fills", "cash_ledger"];
|
||||
|
||||
private static Task<bool> HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s =>
|
||||
public static Task<bool> HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s =>
|
||||
{
|
||||
foreach (var table in _dataTables)
|
||||
{
|
||||
@@ -179,7 +179,7 @@ public static class Installation
|
||||
|
||||
// Sessions of the old database do not survive: everyone signs in again.
|
||||
await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false);
|
||||
await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false);
|
||||
await DisarmAsync(s, clock, null, cancellationToken).ConfigureAwait(false);
|
||||
await Trading.Diary.NotifyAsync(s, clock, "protected_restart",
|
||||
$"{reason}: il database ha una nuova impronta e il bot riparte protetto, con \"Ferma tutto\" acceso. Guarda cosa ho ricostruito e riparti dalla pagina Rischio.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
@@ -191,24 +191,27 @@ public static class Installation
|
||||
|
||||
/// <summary>
|
||||
/// Switches the protected restart on without changing the fingerprint: the accounts hold orders this database never
|
||||
/// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says.
|
||||
/// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. What was asked or
|
||||
/// begun from <paramref name="before"/> on is of today, not of the copy, and stays.
|
||||
/// </summary>
|
||||
public static Task ProtectAsync(Database db, IClock clock, CancellationToken cancellationToken = default)
|
||||
public static Task ProtectAsync(Database db, IClock clock, DateTimeOffset before, string message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
return db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE installation SET protected_restart = @p, renewed_at = @r", cancellationToken, ("p", true), ("r", clock.UtcNow)).ConfigureAwait(false);
|
||||
await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false);
|
||||
await DisarmAsync(s, clock, before, cancellationToken).ConfigureAwait(false);
|
||||
await Trading.Diary.NotifyAsync(s, clock, "protected_restart", message, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SPEC 15.1: "Ferma tutto" on, every strategy with real money in exit only until it is confirmed again, and no
|
||||
/// order planned before the restore still waiting to leave (it may already have left, after the archive).
|
||||
/// order planned before the restore still waiting to leave (it may already have left, after the archive). The same
|
||||
/// for the protective sales of the archive: what still needs one is decided again on the rebuilt position.
|
||||
/// </summary>
|
||||
private static async Task DisarmAsync(DbSession s, IClock clock, CancellationToken cancellationToken)
|
||||
private static async Task DisarmAsync(DbSession s, IClock clock, DateTimeOffset? before, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var key = Core.SettingsStore.BotState.Key;
|
||||
@@ -237,9 +240,18 @@ public static class Installation
|
||||
await s.ExecuteAsync("UPDATE planned_orders SET status = @d, outcome = @o, updated_at = @t WHERE status = @p", cancellationToken,
|
||||
("d", Trading.PlannedStates.Dropped), ("o", ProtectedRestartReason), ("t", now), ("p", Trading.PlannedStates.Pending)).ConfigureAwait(false);
|
||||
|
||||
var until = before ?? DateTimeOffset.MaxValue;
|
||||
foreach (var sale in (await s.QueryAsync("SELECT e.id, e.started_at FROM executions e JOIN accounts a ON a.id = e.account_id WHERE e.status = @w AND e.purpose = 'protective' AND a.environment <> @sim",
|
||||
r => (Id: r.Id("id"), Started: r.Moment("started_at")), ("w", Trading.ExecutionStates.Working), ("sim", Trading.TradingEnvironments.Simulation)).ConfigureAwait(false))
|
||||
.Where(e => e.Started < until))
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE executions SET status = @c, reason = @r, finished_at = @t, updated_at = @t WHERE id = @id", cancellationToken,
|
||||
("c", Trading.ExecutionStates.Canceled), ("r", ProtectedRestartReason), ("t", now), ("id", sale.Id)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A "close all positions" of before the restore may be done already: going on with it would sell what came after.
|
||||
var bot = await s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Json("state").Text, ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false);
|
||||
if (bot is not null && JsonSerializer.Deserialize<Trading.BotRiskState>(bot, Trading.RiskEngine.Json) is { CloseAll: true })
|
||||
if (bot is not null && JsonSerializer.Deserialize<Trading.BotRiskState>(bot, Trading.RiskEngine.Json) is { CloseAll: true } pending && !(pending.CloseAllSince >= until))
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken,
|
||||
("j", new DbJson(JsonSerializer.Serialize(new Trading.BotRiskState(), Trading.RiskEngine.Json))), ("t", now), ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false);
|
||||
|
||||
@@ -49,8 +49,9 @@ public static class GuardRepair
|
||||
}
|
||||
|
||||
// 2. What the bot holds now: the state's quantity plus the fills of its own orders since then, never more than the account has.
|
||||
var fills = (await broker.GetFillsAsync(state.WrittenAt, cancellationToken).ConfigureAwait(false))
|
||||
.Where(f => f.ExecutedAt > state.WrittenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList();
|
||||
var writtenAt = account.WrittenAt ?? state.WrittenAt;
|
||||
var fills = (await broker.GetFillsAsync(writtenAt, cancellationToken).ConfigureAwait(false))
|
||||
.Where(f => f.ExecutedAt > writtenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList();
|
||||
var positions = await broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false);
|
||||
var stops = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false))
|
||||
.Where(o => o.IsOpen && o.Side == OrderSide.Sell && ClientOrderIds.Parse(o.ClientOrderId) is { Purpose: OrderPurpose.Stop } parts && parts.Installation == state.Installation)
|
||||
|
||||
@@ -11,7 +11,11 @@ namespace Anubis.Supervision;
|
||||
public sealed record GuardState(DateTimeOffset WrittenAt, string Installation, IReadOnlyList<GuardAccount> Accounts);
|
||||
|
||||
public sealed record GuardAccount(Guid AccountId, string Name, string Broker, string Environment, bool FractionalStopsAreDayOnly,
|
||||
IReadOnlyList<GuardPosition> Positions, IReadOnlyList<GuardOrder> Orders);
|
||||
IReadOnlyList<GuardPosition> Positions, IReadOnlyList<GuardOrder> Orders)
|
||||
{
|
||||
/// <summary>When these figures were read, if earlier than the file: an account whose ledger is not up to date yet keeps those of before.</summary>
|
||||
public DateTimeOffset? WrittenAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A position of a strategy: quantity, stop level already on the tick, lot, and what the guard needs to name a stop
|
||||
|
||||
@@ -428,9 +428,9 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Writes the latest price of an instrument on the positions that hold it, for their value.</summary>
|
||||
public Task MarkAsync(Guid instrumentId, decimal price, CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE instrument_id = @i", cancellationToken,
|
||||
("p", price), ("now", clock.UtcNow), ("i", instrumentId)), cancellationToken);
|
||||
public Task MarkAsync(Guid accountId, Guid instrumentId, decimal price, CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i", cancellationToken,
|
||||
("p", price), ("now", clock.UtcNow), ("a", accountId), ("i", instrumentId)), cancellationToken);
|
||||
|
||||
/// <summary>Sets the protective level shown with a position.</summary>
|
||||
public Task SetStopAsync(Guid accountId, Guid instrumentId, string strategy, decimal? stop, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -86,12 +86,30 @@ public sealed partial class OrderManager
|
||||
}
|
||||
}
|
||||
|
||||
var onlyStops = written == 0 && unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0);
|
||||
if (protect is not null && (unclear.Count > 0 || (unknown.Count > 0 && !onlyStops)))
|
||||
var recordedBefore = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT execution_id FROM fills WHERE account_id = @a", r => r.Text("execution_id"),
|
||||
("a", _account.AccountId)).ConfigureAwait(false)).ToHashSet(StringComparer.Ordinal), cancellationToken).ConfigureAwait(false);
|
||||
if (RefreshSplits is not null && (begun is not null || unknown.Count > 0 || fills.Any(f => !recordedBefore.Contains(f.ExecutionId))))
|
||||
{
|
||||
var symbols = fills.Select(f => f.Symbol).Concat(open.Select(o => o.Symbol)).ToHashSet(StringComparer.Ordinal);
|
||||
await RefreshSplits(symbols, DateOnly.FromDateTime(since.UtcDateTime), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// What an interrupted attempt wrote does not count here: if it had to, it protected before its first row.
|
||||
var onlyStops = unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0);
|
||||
if (protect is not null && (unclear.Count > 0 || !onlyStops))
|
||||
{
|
||||
await protect(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var row in await HalfWrittenAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Cut between the row and its state: the broker is asked again.
|
||||
var symbol = (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!.Symbol;
|
||||
var own = fills.Where(f => f.ClientOrderId == row.ClientOrderId).ToList();
|
||||
var remote = open.FirstOrDefault(o => o.ClientOrderId == row.ClientOrderId) ?? await _broker.GetOrderAsync(row.ClientOrderId, symbol, cancellationToken).ConfigureAwait(false);
|
||||
await SettleRebuiltAsync(row, symbol, remote, own, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (clientId, parts, instrumentId, own, resting) in unknown)
|
||||
{
|
||||
var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol;
|
||||
@@ -107,42 +125,89 @@ public sealed partial class OrderManager
|
||||
written++;
|
||||
}
|
||||
|
||||
if (written > 0)
|
||||
// The same for one the database knows of an execution that is over: the restore ended the archive's protective sales.
|
||||
foreach (var resting in open.Where(o => ClientOrderIds.Parse(o.ClientOrderId)!.Purpose != OrderPurpose.Stop))
|
||||
{
|
||||
var recorded = await SyncFillsFromAsync(since, cancellationToken, replay: true).ConfigureAwait(false);
|
||||
var positions = await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var instrumentId in positions.Select(p => p.InstrumentId).Distinct())
|
||||
if (await OrderByClientIdAsync(resting.ClientOrderId, cancellationToken).ConfigureAwait(false) is { ExecutionId: { } execution } row
|
||||
&& await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE id = @id AND status = @w", ("id", execution), ("w", ExecutionStates.Working)), cancellationToken)
|
||||
.ConfigureAwait(false) == 0)
|
||||
{
|
||||
await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||
await CancelAndReadAsync(row, (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!, "execution_over", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null))
|
||||
{
|
||||
var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?";
|
||||
unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire.");
|
||||
}
|
||||
|
||||
var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." +
|
||||
(unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since);
|
||||
await _db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken,
|
||||
("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false);
|
||||
await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return new RebuildReport(written, recorded, unclear, onlyStops);
|
||||
}
|
||||
|
||||
if (unclear.Count > 0)
|
||||
// Also when every order was known: the executions of while the bot was off meet the splits of their time, and
|
||||
// only then a split or a dividend of today finds the quantities it needs.
|
||||
var replay = new Replay(Quiet: written > 0);
|
||||
var recorded = await SyncFillsFromAsync(since, cancellationToken, replay).ConfigureAwait(false);
|
||||
if (written == 0)
|
||||
{
|
||||
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await SellRestOfStopsAsync(replay, cancellationToken).ConfigureAwait(false);
|
||||
if (recorded > 0 && AfterFills is not null)
|
||||
{
|
||||
await AfterFills(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (unclear.Count > 0)
|
||||
{
|
||||
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new RebuildReport(0, recorded, unclear);
|
||||
}
|
||||
|
||||
return new RebuildReport(0, 0, unclear);
|
||||
foreach (var instrumentId in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct())
|
||||
{
|
||||
await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null))
|
||||
{
|
||||
var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?";
|
||||
unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire.");
|
||||
}
|
||||
|
||||
unclear.AddRange(replay.Refused.DistinctBy(f => f.ExecutionId).Select(f =>
|
||||
$"{f.Symbol}: {(f.Side == OrderSide.Buy ? "un acquisto" : "una vendita")} di {Format.Quantity(f.Quantity)} non torna con il registro, controlla la posizione prima di ripartire."));
|
||||
if (AfterFills is not null)
|
||||
{
|
||||
await AfterFills(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." +
|
||||
(unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since);
|
||||
await _db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken,
|
||||
("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false);
|
||||
await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return new RebuildReport(written, recorded, unclear, onlyStops && written == unknown.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A stop of while the bot was off that fired only in part, or one of Alpaca's two: the rest is sold at once (SPEC 7.2).
|
||||
/// Only where the stop is the last thing that happened to the position.
|
||||
/// </summary>
|
||||
private async Task SellRestOfStopsAsync(Replay replay, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var ((instrumentId, strategy), _) in replay.Last.Where(l => l.Value == OrderPurpose.Stop))
|
||||
{
|
||||
if (await _ledger.PositionAsync(_account.AccountId, instrumentId, strategy, cancellationToken).ConfigureAwait(false) is { Quantity: > 0m } rest)
|
||||
{
|
||||
await ProtectiveSaleAsync(instrumentId, strategy, rest.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Task<List<OrderRow>> HalfWrittenAsync(CancellationToken cancellationToken) =>
|
||||
_db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status = 'created' AND reason = @r", ReadOrder, ("a", _account.AccountId), ("r", RebuiltReason)),
|
||||
cancellationToken);
|
||||
|
||||
private const string RebuiltReason = "rebuilt from the broker";
|
||||
|
||||
/// <summary>The splits with an ex-date up to <paramref name="until"/>, in the ledger only: each is applied once.</summary>
|
||||
private async Task ReplaySplitsAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -157,7 +222,7 @@ public sealed partial class OrderManager
|
||||
? []
|
||||
: [.. (await Splits(instrument, cancellationToken).ConfigureAwait(false)).Where(s => s.ChangesShares && ExDate(s) <= until).OrderBy(s => s.ExDate).Select(s => (instrument, s))];
|
||||
|
||||
private static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
internal static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
|
||||
private string Beyond(DateTimeOffset since) => _broker.FillHistory is { } reach && since < _clock.UtcNow - reach
|
||||
? $" Il broker racconta solo gli ultimi {reach.Days} giorni: quello che è successo prima va confrontato a mano."
|
||||
@@ -207,8 +272,8 @@ public sealed partial class OrderManager
|
||||
await s.ExecuteAsync("UPDATE account_status SET rebuild_since = @since, rebuild_orders = COALESCE(rebuild_orders, 0) + 1, updated_at = @now WHERE account_id = @a",
|
||||
cancellationToken, ("since", since), ("now", now), ("a", _account.AccountId)).ConfigureAwait(false);
|
||||
await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = 'rebuilt from the broker' WHERE id = @id", cancellationToken,
|
||||
("b", remote?.BrokerOrderId), ("at", created), ("id", row.Id)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = @r WHERE id = @id", cancellationToken,
|
||||
("b", remote?.BrokerOrderId), ("at", created), ("r", RebuiltReason), ("id", row.Id)).ConfigureAwait(false);
|
||||
if (_account.Environment == TradingEnvironments.Live)
|
||||
{
|
||||
// The archive may be older than the promotion: what the bot holds on the real account gets its stops and
|
||||
@@ -217,11 +282,18 @@ public sealed partial class OrderManager
|
||||
("a", _account.AccountId), ("x", true), ("now", now), ("s", parts.Strategy)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt)
|
||||
await SettleRebuiltAsync(row, remote?.Symbol ?? own[0].Symbol, remote, own, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The state of a rebuilt order: the broker's, or what its executions say when the broker forgot it.</summary>
|
||||
private Task SettleRebuiltAsync(OrderRow row, string symbol, BrokerOrder? remote, List<BrokerFill> own, CancellationToken cancellationToken)
|
||||
{
|
||||
var filled = own.Sum(f => f.Quantity);
|
||||
return ApplyRemoteAsync(row, remote ?? new BrokerOrder(row.ClientOrderId, null, symbol, row.Side, row.Kind, row.Quantity,
|
||||
filled > 0m ? OrderStatus.Filled : OrderStatus.Canceled, filled, own.Count > 0 ? own[^1].ExecutedAt : _clock.UtcNow)
|
||||
{
|
||||
AverageFillPrice = DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled),
|
||||
};
|
||||
await ApplyRemoteAsync(row, remote, "rebuilt from the broker", cancellationToken).ConfigureAwait(false);
|
||||
AverageFillPrice = filled > 0m ? DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled) : null,
|
||||
}, RebuiltReason, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -141,6 +141,12 @@ public sealed partial class OrderManager : IDisposable
|
||||
/// </summary>
|
||||
public bool AwaitingRebuild { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Asks the splits of these symbols since a day again, before executions of the past are written: without them a
|
||||
/// sale of new shares would be refused. A failure leaves the account waiting (SPEC 15.1).
|
||||
/// </summary>
|
||||
public Func<IReadOnlyCollection<string>, DateOnly, CancellationToken, Task>? RefreshSplits { get; init; }
|
||||
|
||||
/// <summary>Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5).</summary>
|
||||
public Func<CancellationToken, Task>? AfterFills { get; init; }
|
||||
|
||||
@@ -408,6 +414,12 @@ public sealed partial class OrderManager : IDisposable
|
||||
await CancelAndReadAsync(current, instrument, reason, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (AwaitingRebuild)
|
||||
{
|
||||
// Its executions cannot be read yet: the startup ends it after the rebuild, with the stop of what was bought.
|
||||
continue;
|
||||
}
|
||||
|
||||
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false);
|
||||
canceled.Add(exec.Id);
|
||||
@@ -752,7 +764,7 @@ public sealed partial class OrderManager : IDisposable
|
||||
/// With <paramref name="replay"/> the executions are history (SPEC 15.1): they are written with the splits of their
|
||||
/// time, and nothing is done about them. What to do today is decided afterwards, on the position that results.
|
||||
/// </summary>
|
||||
private async Task<int> SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, bool replay = false)
|
||||
private async Task<int> SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, Replay? replay = null)
|
||||
{
|
||||
var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false);
|
||||
var recorded = 0;
|
||||
@@ -769,7 +781,7 @@ public sealed partial class OrderManager : IDisposable
|
||||
continue;
|
||||
}
|
||||
|
||||
if (replay)
|
||||
if (replay is not null)
|
||||
{
|
||||
await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -789,6 +801,7 @@ public sealed partial class OrderManager : IDisposable
|
||||
{
|
||||
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_refused_fill",
|
||||
$"Un'esecuzione su {_account.Name} non torna con il mio registro: la controllo nella riconciliazione. ({ex.Message})", cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
replay?.Refused.Add(fill);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -798,6 +811,11 @@ public sealed partial class OrderManager : IDisposable
|
||||
}
|
||||
|
||||
recorded++;
|
||||
if (replay is not null)
|
||||
{
|
||||
replay.Last[(row.InstrumentId, row.Strategy)] = row.Purpose;
|
||||
}
|
||||
|
||||
var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false);
|
||||
await _db.WriteAsync(async s =>
|
||||
{
|
||||
@@ -818,20 +836,20 @@ public sealed partial class OrderManager : IDisposable
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
|
||||
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!replay)
|
||||
if (replay is null or { Quiet: false })
|
||||
{
|
||||
// Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14).
|
||||
await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (!replay && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
|
||||
if (replay is null && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
|
||||
{
|
||||
// A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2).
|
||||
await ProtectiveSaleAsync(row.InstrumentId, row.Strategy, outcome.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (recorded > 0 && AfterFills is not null)
|
||||
if (replay is null && recorded > 0 && AfterFills is not null)
|
||||
{
|
||||
await AfterFills(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -839,6 +857,17 @@ public sealed partial class OrderManager : IDisposable
|
||||
return recorded;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A reading of the past: what the ledger refused, and the purpose of the last execution recorded of each position.
|
||||
/// Quiet when the executions are those of after an archive, days old: they do not reach the phone as new.
|
||||
/// </summary>
|
||||
private sealed record Replay(bool Quiet)
|
||||
{
|
||||
public List<BrokerFill> Refused { get; } = [];
|
||||
|
||||
public Dictionary<(Guid Instrument, string Strategy), OrderPurpose> Last { get; } = [];
|
||||
}
|
||||
|
||||
private async Task RefreshOpenOrdersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)),
|
||||
|
||||
@@ -446,13 +446,20 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
||||
/// <summary>
|
||||
/// After an absence (SPEC 7.3): waiting purchases are cancelled; stops and sales that would have triggered are
|
||||
/// filled at their level, or at the open of the bar that already passed it. Bars come from the one-minute store.
|
||||
/// With <paramref name="to"/> only the stretch before it, the rest at the next call.
|
||||
/// </summary>
|
||||
public async Task<int> CatchUpAsync(Func<string, DateTimeOffset, DateTimeOffset, CancellationToken, Task<IReadOnlyList<Bar>>> minuteBars, CancellationToken cancellationToken)
|
||||
public async Task<int> CatchUpAsync(Func<string, DateTimeOffset, DateTimeOffset, CancellationToken, Task<IReadOnlyList<Bar>>> minuteBars, CancellationToken cancellationToken,
|
||||
DateTimeOffset? to = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(minuteBars);
|
||||
var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false);
|
||||
var from = book.SeenUntil;
|
||||
var until = _clock.UtcNow;
|
||||
var until = to ?? _clock.UtcNow;
|
||||
if (until < from)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var bars = new Dictionary<string, IReadOnlyList<Bar>>(StringComparer.Ordinal);
|
||||
foreach (var symbol in book.Orders.Where(o => IsOpen(o) && o.Request.Side == OrderSide.Sell).Select(o => o.Request.Symbol).Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
|
||||
@@ -172,6 +172,7 @@ public sealed partial class TradingService : IDisposable
|
||||
{
|
||||
_db = db ?? throw new ArgumentNullException(nameof(db));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_since = clock.UtcNow;
|
||||
_bus = bus ?? throw new ArgumentNullException(nameof(bus));
|
||||
_secrets = secrets ?? throw new ArgumentNullException(nameof(secrets));
|
||||
_market = market;
|
||||
@@ -362,6 +363,7 @@ public sealed partial class TradingService : IDisposable
|
||||
MarketOpen = MarketOpenAsync,
|
||||
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
|
||||
Splits = SplitsAsync,
|
||||
RefreshSplits = _market is null || account.Broker != Venues.Alpaca ? null : (symbols, since, ct) => _market.RefreshCorporateActionsAsync(symbols, since, ct),
|
||||
AwaitingRebuild = account.Environment != TradingEnvironments.Simulation,
|
||||
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
|
||||
Gate = Risk is null ? null : Risk.GateAsync,
|
||||
@@ -411,9 +413,20 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
|
||||
var accounts = new List<GuardAccount>();
|
||||
GuardState? before = null;
|
||||
foreach (var manager in _managers.Values)
|
||||
{
|
||||
accounts.Add(await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false));
|
||||
var account = await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (manager.AwaitingRebuild)
|
||||
{
|
||||
// Its ledger may be older than the account: the guard keeps what the last state said, at its time, or nothing.
|
||||
before ??= Supervision.GuardFiles.ReadState(GuardFiles);
|
||||
account = before is not null && before.Installation == InstallationCode && before.Accounts.FirstOrDefault(a => a.AccountId == account.AccountId) is { } known
|
||||
? known with { WrittenAt = known.WrittenAt ?? before.WrittenAt }
|
||||
: account with { Positions = [] };
|
||||
}
|
||||
|
||||
accounts.Add(account);
|
||||
}
|
||||
|
||||
Supervision.GuardFiles.WriteState(GuardFiles, new GuardState(_clock.UtcNow, InstallationCode, accounts));
|
||||
@@ -443,19 +456,18 @@ public sealed partial class TradingService : IDisposable
|
||||
{
|
||||
if (manager.Broker is PaperBroker paper)
|
||||
{
|
||||
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
|
||||
await CatchUpAsync(manager, paper, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
Guard?.Step("esecuzioni dal broker " + name);
|
||||
await RebuildAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// After the rebuild: a split or a dividend needs the quantities held at its date (SPEC 15.1).
|
||||
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// After the executions of meanwhile: a split or a dividend needs the quantities held at its date (SPEC 15.1).
|
||||
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Guard?.Step("riconciliazione " + name);
|
||||
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
Guard?.Step("ordini rimasti aperti " + name);
|
||||
@@ -469,33 +481,84 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The simulator's absence (SPEC 7.3), one stretch per split: the orders of before it meet the prices of before it.</summary>
|
||||
internal async Task CatchUpAsync(OrderManager manager, PaperBroker paper, CancellationToken cancellationToken)
|
||||
{
|
||||
var splits = new List<(Instrument Instrument, CorporateAction Split)>();
|
||||
foreach (var id in (await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct())
|
||||
{
|
||||
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { IsCrypto: false } instrument)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var split in await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!await AppliedAsync(manager.Account.AccountId, split.SourceKey, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
splits.Add((instrument, split));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (instrument, split) in splits.OrderBy(s => s.Split.ExDate))
|
||||
{
|
||||
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken, OrderManager.ExDate(split)).ConfigureAwait(false);
|
||||
await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false);
|
||||
await manager.ApplySplitAsync(instrument, split, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
|
||||
await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SPEC 15.1: what the account did after the archive is written back before anything compares ledger and account.
|
||||
/// Finding something on a database nobody declared restored means it is an old copy put back by hand, or a dump:
|
||||
/// the protected restart starts here, as it would have after an import.
|
||||
/// </summary>
|
||||
internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) =>
|
||||
manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct));
|
||||
internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken)
|
||||
{
|
||||
var protectedNow = false;
|
||||
try
|
||||
{
|
||||
await manager.RebuildAsync(cancellationToken, async ct =>
|
||||
{
|
||||
await ProtectAsync(manager, ct).ConfigureAwait(false);
|
||||
protectedNow = true;
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// "Ferma tutto" also where the other accounts are already at work.
|
||||
foreach (var other in _managers.Values.Where(m => protectedNow && m != manager && AccountReady(m.Account.AccountId)))
|
||||
{
|
||||
await GuardAsync("ordini " + other.Account.Name, () => other.CancelWorkingAsync(Platform.Installation.ProtectedRestartReason, cancellationToken: cancellationToken),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What was asked or begun before this moment may be of an old copy of the database; what comes after is of now.
|
||||
private readonly DateTimeOffset _since;
|
||||
|
||||
private async Task ProtectAsync(OrderManager manager, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true }
|
||||
&& await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken)
|
||||
.ConfigureAwait(false) == "\"stopped\"")
|
||||
if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true }
|
||||
|| await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken)
|
||||
.ConfigureAwait(false) != "\"stopped\"")
|
||||
{
|
||||
return;
|
||||
await Platform.Installation.ProtectAsync(_db, _clock, _since,
|
||||
$"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Platform.Installation.ProtectAsync(_db, _clock, cancellationToken).ConfigureAwait(false);
|
||||
// Also when an attempt cut right after the write had already protected: the names of the stops depend on it.
|
||||
var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false);
|
||||
foreach (var each in _managers.Values)
|
||||
foreach (var each in _managers.Values.Append(manager))
|
||||
{
|
||||
each.StopGeneration = generation;
|
||||
}
|
||||
|
||||
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "protected_restart",
|
||||
$"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.",
|
||||
cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Zero until the first restore, then the moment of the last one.</summary>
|
||||
@@ -807,21 +870,32 @@ public sealed partial class TradingService : IDisposable
|
||||
/// </summary>
|
||||
public async Task MarkPositionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var held = (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct().ToList();
|
||||
foreach (var id in held)
|
||||
foreach (var held in (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).GroupBy(p => p.InstrumentId))
|
||||
{
|
||||
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } instrument)
|
||||
if (await _catalog.GetAsync(held.Key, cancellationToken).ConfigureAwait(false) is not { } instrument
|
||||
|| await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is not { Bid: > 0m, Ask: > 0m } quote || quote.Ask < quote.Bid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote && quote.Ask >= quote.Bid)
|
||||
foreach (var account in held.GroupBy(p => p.AccountId))
|
||||
{
|
||||
await Ledger.MarkAsync(id, quote.Mid, cancellationToken).ConfigureAwait(false);
|
||||
if (!await SharesOfAnotherTimeAsync(account.Key, instrument, account.Min(p => p.OpenedAt), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await Ledger.MarkAsync(account.Key, held.Key, quote.Mid, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The quantity in the ledger is not the one today's price is about: an account not rebuilt yet, or a split still to be
|
||||
/// applied. Valued all the same it would show a loss that is not there, and the limits of SPEC 9.2 would act on it.
|
||||
/// </summary>
|
||||
private async Task<bool> SharesOfAnotherTimeAsync(Guid accountId, Instrument instrument, DateTimeOffset openedAt, CancellationToken cancellationToken) =>
|
||||
_managers.TryGetValue(accountId, out var manager) && (manager.AwaitingRebuild || (!instrument.IsCrypto
|
||||
&& await PendingSplitAsync(accountId, instrument, cancellationToken).ConfigureAwait(false) is { } split && openedAt < OrderManager.ExDate(split)));
|
||||
|
||||
public async Task TickAllAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await RetryAccountsAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -891,7 +965,7 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken)
|
||||
internal async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken)
|
||||
{
|
||||
if (manager.Account.Broker != Venues.Alpaca)
|
||||
{
|
||||
@@ -912,21 +986,28 @@ public sealed partial class TradingService : IDisposable
|
||||
|
||||
// What was sold since still owes the dividends of when it was held: a rebuild or a long stop brings them late.
|
||||
var traded = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT instrument_id FROM fills WHERE account_id = @a AND executed_at >= @at", r => r.Id("instrument_id"),
|
||||
("a", manager.Account.AccountId), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false);
|
||||
var held = new Dictionary<string, Instrument>(StringComparer.Ordinal);
|
||||
("a", manager.Account.AccountId), ("at", _clock.UtcNow - MarketDataService.SoldStillOwed)), cancellationToken).ConfigureAwait(false);
|
||||
var owed = new Dictionary<string, Instrument>(StringComparer.Ordinal);
|
||||
foreach (var id in positions.Select(p => p.InstrumentId).Concat(traded).Distinct())
|
||||
{
|
||||
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument)
|
||||
{
|
||||
held[instrument.Symbol] = instrument;
|
||||
owed[instrument.Symbol] = instrument;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol)))
|
||||
var held = positions.Select(p => p.InstrumentId).ToHashSet();
|
||||
foreach (var action in actions.Where(a => owed.ContainsKey(a.Symbol)))
|
||||
{
|
||||
var instrument = held[action.Symbol];
|
||||
var instrument = owed[action.Symbol];
|
||||
if (action.ChangesShares)
|
||||
{
|
||||
// Only where something is held: a purchase not read yet must still find its split.
|
||||
if (!held.Contains(instrument.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The ledger and, on the simulator, the broker's book, together and once.
|
||||
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -937,8 +1018,6 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90);
|
||||
|
||||
private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = "div:" + action.SourceKey;
|
||||
|
||||
Reference in new issue
Block a user