Fix the defects found by the Phase 3 review (refs #33 #26 #27 #28 #29 #30 #31 #32)
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
- Splits multiply only the shares held before the ex-date. Old splits in the table no longer inflate positions bought later; the simulator's book follows the same split once, together with the ledger. - Dividends pay the simulator once on the ex-date holdings, and each payment is marked in the same write, so a failure never pays twice. - Positions are marked to market before every equity photograph; until now equity, drawdown and the Conti screen stayed at the last fill. - A sale with no price keeps its broker stops until it can really leave; a purchase with no price is dropped. - A refused sale is retried with pauses of 1, 2, 4, 8 and 15 minutes instead of every tick, and one failing execution no longer stops the stop alignment of the whole account. - On Alpaca a purchase clears the sell stops of every strategy on the symbol and holds them until it ends. - OKX order lookups treat only 51603 as unknown; any other failure is an error, so a lost order is never sent twice. - The reconcile choice and key removal forms now require the antiforgery token; the choice re-runs the comparison and is only offered after the 15 minutes; stale differences are dropped. - A replaced key that cannot withdraw releases the prudent mode. - Re-entering the same euro capital for Alpaca changes nothing; a new amount converts only the euro difference at today's rate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
60d5ebbc05
commit
1a0912e436
17 files changed
+358
-89
No files matched your search
@@ -355,6 +355,7 @@ else
|
||||
("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true),
|
||||
(_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false),
|
||||
(_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false),
|
||||
(_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false),
|
||||
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
|
||||
_ => (null, false),
|
||||
};
|
||||
|
||||
@@ -177,7 +177,8 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
|
||||
private static async Task<IResult> ResolveAccountAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
||||
private static async Task<IResult> ResolveAccountAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (choice is not ("allinea" or "escludi"))
|
||||
{
|
||||
@@ -195,6 +196,12 @@ internal static partial class Forms
|
||||
return Results.Redirect("/conti?errore=chiave");
|
||||
}
|
||||
|
||||
if (!state.WaitsForUser(clock.UtcNow, trading.Reconciler.Grace))
|
||||
{
|
||||
// The choice exists only after the 15 minutes (SPEC 7.4): before, the difference may still explain itself.
|
||||
return Results.Redirect("/conti?errore=presto");
|
||||
}
|
||||
|
||||
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
|
||||
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/conti?ok=" + choice);
|
||||
@@ -263,7 +270,7 @@ internal static partial class Forms
|
||||
return Results.Redirect(back + "?ok=chiavi#conti");
|
||||
}
|
||||
|
||||
private static async Task<IResult> RemoveKeysAsync(string broker, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services)
|
||||
|
||||
@@ -96,6 +96,13 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
}
|
||||
|
||||
var currency = Strategies.CurrencyOf(broker);
|
||||
var previous = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false);
|
||||
if (previous is not null && previous.AmountEur == amountEur)
|
||||
{
|
||||
// The same amount again changes nothing, whatever the exchange rate did meanwhile.
|
||||
return previous;
|
||||
}
|
||||
|
||||
var rate = 1m;
|
||||
if (currency != "EUR")
|
||||
{
|
||||
@@ -105,7 +112,12 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
?? throw new CapitalException($"Manca il cambio EUR/{currency}: lo scarico ogni giorno dalla BCE, riprova più tardi.");
|
||||
}
|
||||
|
||||
var entrusted = new EntrustedCapital(broker, amountEur, currency, rate, Math.Round(amountEur * rate, 2, MidpointRounding.ToZero), changedBy, clock.UtcNow);
|
||||
// Only the change in euro is converted at today's rate: the dollars already given stay as they are, so a
|
||||
// move of the exchange rate is never booked as a deposit or a withdrawal. The rate kept is the overall one.
|
||||
var amount = Math.Round((previous?.Amount ?? 0m) + ((amountEur - (previous?.AmountEur ?? 0m)) * rate), 2, MidpointRounding.ToZero);
|
||||
amount = amountEur == 0m ? 0m : Math.Max(amount, 0m);
|
||||
var overall = amountEur > 0m && currency != "EUR" ? Math.Round(amount / amountEur, 6) : rate;
|
||||
var entrusted = new EntrustedCapital(broker, amountEur, currency, overall, amount, changedBy, clock.UtcNow);
|
||||
var plan = await PlanAsync(broker, entrusted.Amount, null, cancellationToken).ConfigureAwait(false);
|
||||
await db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, @by, @now)", cancellationToken,
|
||||
|
||||
@@ -232,8 +232,27 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
}
|
||||
|
||||
/// <summary>A cash dividend for a strategy, recorded on the ex-date (SPEC 7.5).</summary>
|
||||
public Task RecordDividendAsync(Guid accountId, string strategy, decimal amount, string currency, DateTimeOffset exDate, string note, CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Dividend, null, note, exDate, cancellationToken), cancellationToken);
|
||||
/// <summary>
|
||||
/// A cash dividend for a strategy. With <paramref name="appliedKey"/> the payment and its mark are one write, and a
|
||||
/// second call with the same key does nothing.
|
||||
/// </summary>
|
||||
public Task RecordDividendAsync(Guid accountId, string strategy, decimal amount, string currency, DateTimeOffset exDate, string note, CancellationToken cancellationToken,
|
||||
string? appliedKey = null) =>
|
||||
db.WriteAsync(async s =>
|
||||
{
|
||||
if (appliedKey is not null)
|
||||
{
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", appliedKey)).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("a", accountId), ("k", appliedKey), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Dividend, null, note, exDate, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Writes a residue off the ledger at market value (SPEC 7.2): a sale at that price that brings no money, whose
|
||||
@@ -286,31 +305,55 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// A split in an account's ledger (SPEC 6.10): quantities times the ratio, average prices, stops and open lots
|
||||
/// divided by it; values and results do not change. False when the action was already applied.
|
||||
/// A split in an account's ledger (SPEC 6.10). Only what was held before the ex-date is multiplied: shares bought
|
||||
/// on or after it are already new shares. The cost of each position stays the same, so values and results do not
|
||||
/// change. Returns how many old shares were held across the strategies (0 when none), or null when the action was
|
||||
/// already applied.
|
||||
/// </summary>
|
||||
public Task<bool> ApplySplitAsync(Guid accountId, Guid instrumentId, string sourceKey, decimal ratio, CancellationToken cancellationToken)
|
||||
public Task<decimal?> ApplySplitAsync(Guid accountId, Guid instrumentId, string sourceKey, decimal ratio, DateTimeOffset exDate, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(ratio, 0m);
|
||||
return db.WriteAsync(async s =>
|
||||
return db.WriteAsync<decimal?>(async s =>
|
||||
{
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey)).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
var now = clock.UtcNow;
|
||||
var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false);
|
||||
var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions WHERE account_id = @a AND instrument_id = @i",
|
||||
ReadPosition, ("a", accountId), ("i", instrumentId)).ConfigureAwait(false)).ToList();
|
||||
foreach (var p in positions)
|
||||
var oldShares = 0m;
|
||||
foreach (var p in positions.Where(p => p.Quantity > 0m))
|
||||
{
|
||||
// What the fills since the ex-date added or removed is in new shares already; the rest is old.
|
||||
var since = await s.QueryAsync("SELECT side, quantity, fee, fee_currency FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at >= @at",
|
||||
r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency")),
|
||||
("a", accountId), ("i", instrumentId), ("s", p.Strategy), ("at", exDate)).ConfigureAwait(false);
|
||||
var after = since.Sum(r =>
|
||||
{
|
||||
var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m;
|
||||
return r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind);
|
||||
});
|
||||
var old = p.Quantity - after;
|
||||
if (old <= Dust)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
oldShares += old;
|
||||
var quantity = p.Quantity + (old * (ratio - 1m));
|
||||
var unchanged = since.Count == 0;
|
||||
await s.ExecuteAsync("UPDATE positions SET quantity = @q, average_price = @p, last_price = @l, stop_price = @st, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s",
|
||||
cancellationToken, ("q", p.Quantity * ratio), ("p", DbValues.Money(p.AveragePrice / ratio)), ("l", p.LastPrice / ratio), ("st", p.StopPrice / ratio), ("now", now),
|
||||
cancellationToken, ("q", quantity), ("p", DbValues.Money(p.Quantity * p.AveragePrice / quantity)),
|
||||
("l", unchanged ? p.LastPrice / ratio : p.LastPrice), ("st", unchanged ? p.StopPrice / ratio : p.StopPrice), ("now", now),
|
||||
("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false);
|
||||
var lots = await s.QueryAsync("SELECT id, fill_id, quantity, price, closes_id FROM lots WHERE account_id = @a AND instrument_id = @i AND strategy = @s",
|
||||
r => (Id: r.Id("id"), Fill: r.Id("fill_id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id")),
|
||||
var lots = await s.QueryAsync(
|
||||
"SELECT l.id, l.fill_id, l.quantity, l.price, l.closes_id, f.executed_at FROM lots l JOIN fills f ON f.id = l.fill_id WHERE l.account_id = @a AND l.instrument_id = @i AND l.strategy = @s",
|
||||
r => (Id: r.Id("id"), Fill: r.Id("fill_id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id"), At: r.Moment("executed_at")),
|
||||
("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false);
|
||||
foreach (var lot in lots.Where(l => l.Closes is null && l.Quantity > 0m))
|
||||
foreach (var lot in lots.Where(l => l.Closes is null && l.Quantity > 0m && l.At < exDate))
|
||||
{
|
||||
var remaining = lot.Quantity + lots.Where(c => c.Closes == lot.Id).Sum(c => c.Quantity);
|
||||
if (remaining <= Dust)
|
||||
@@ -328,16 +371,16 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
|
||||
if (await OpenTradeAsync(s, accountId, instrumentId, p.Strategy).ConfigureAwait(false) is { } trade)
|
||||
{
|
||||
var row = await s.FirstOrDefaultAsync("SELECT bought_quantity, sold_quantity FROM trades WHERE id = @id", r => (B: r.Money("bought_quantity"), S: r.Money("sold_quantity")), ("id", trade))
|
||||
.ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE trades SET bought_quantity = @b, sold_quantity = @s, updated_at = @now WHERE id = @id", cancellationToken,
|
||||
("b", row.B * ratio), ("s", row.S * ratio), ("now", now), ("id", trade)).ConfigureAwait(false);
|
||||
// The old shares count as bought again in new shares: bought minus sold still equals the position.
|
||||
var row = await s.FirstOrDefaultAsync("SELECT bought_quantity FROM trades WHERE id = @id", r => r.Money("bought_quantity"), ("id", trade)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE trades SET bought_quantity = @b, updated_at = @now WHERE id = @id", cancellationToken,
|
||||
("b", row + (old * (ratio - 1m))), ("now", now), ("id", trade)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("a", accountId), ("k", sourceKey), ("now", now)).ConfigureAwait(false);
|
||||
return true;
|
||||
return oldShares;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
@@ -165,8 +165,11 @@ public sealed class OkxTrading : IBrokerAccount
|
||||
var (code, _, data) = Envelope(answer);
|
||||
if (code != "0" || data.Count == 0)
|
||||
{
|
||||
// 51603 "Order does not exist"; a canceled order without fills also disappears after two hours.
|
||||
return code is "0" or "51603" or "51000" or "1" ? null : throw _http.Failure(url, answer);
|
||||
// Only 51603 "Order does not exist" (also as the sCode of a failed call) means unknown; a canceled order
|
||||
// without fills also disappears after two hours. Any other failure is an error, retried later: a generic
|
||||
// failure taken for "never arrived" would let a lost order be sent twice.
|
||||
var sCode = data.Count > 0 ? Text(data[0], "sCode") : null;
|
||||
return code is "0" or "51603" || sCode == "51603" ? null : throw _http.Failure(url, answer);
|
||||
}
|
||||
|
||||
return stop ? ReadAlgo(data[0]) : ReadOrder(data[0]);
|
||||
|
||||
@@ -140,12 +140,20 @@ public sealed partial class OrderManager
|
||||
return;
|
||||
}
|
||||
|
||||
var applied = await _ledger.ApplySplitAsync(_account.AccountId, instrument.Id, split.SourceKey, split.Ratio!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (!applied)
|
||||
var exDate = new DateTimeOffset(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
var oldShares = await _ledger.ApplySplitAsync(_account.AccountId, instrument.Id, split.SourceKey, split.Ratio!.Value, exDate, cancellationToken).ConfigureAwait(false);
|
||||
if (oldShares is not > 0m)
|
||||
{
|
||||
// Already applied, or nothing was held before the ex-date: the shares held are new shares already.
|
||||
return;
|
||||
}
|
||||
|
||||
if (_broker is PaperBroker paper)
|
||||
{
|
||||
// The simulator is the broker of this account: its book follows the same split, once.
|
||||
await paper.ApplySplitAsync(instrument.Symbol, split.Ratio.Value, oldShares.Value, exDate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.InstrumentId == instrument.Id))
|
||||
{
|
||||
await CancelStopsOfAsync(instrument.Id, position.Strategy, instrument, cancellationToken).ConfigureAwait(false);
|
||||
@@ -173,11 +181,14 @@ public sealed partial class OrderManager
|
||||
|
||||
private async Task AlignPositionAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken)
|
||||
{
|
||||
var working = await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w",
|
||||
("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false);
|
||||
// An execution in progress owns the stops of its position until it ends. Where the broker refuses a purchase
|
||||
// while any sell stop rests on the symbol (Alpaca), a purchase of any strategy holds every stop on it.
|
||||
var sql = "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND status = @w AND (strategy = @s" +
|
||||
(_broker.Capabilities.OppositeSideBlocked ? " OR side = @buy)" : ")");
|
||||
var working = await _db.ReadAsync(s => s.CountAsync(sql,
|
||||
("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working), ("buy", Wire.Text(OrderSide.Buy))), cancellationToken).ConfigureAwait(false);
|
||||
if (working > 0)
|
||||
{
|
||||
// An execution in progress owns the stops of its position until it ends.
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -264,6 +275,21 @@ public sealed partial class OrderManager
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cancels the open stops of every strategy on an instrument (Alpaca blocks the whole symbol). True when none is left.</summary>
|
||||
private async Task<bool> ClearSymbolStopsCoreAsync(Guid instrumentId, Instrument instrument, CancellationToken cancellationToken)
|
||||
{
|
||||
var strategies = await _db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT DISTINCT strategy FROM orders WHERE account_id = @a AND instrument_id = @i AND purpose = 'stop' AND status IN ('created', 'submitted', 'partially_filled')",
|
||||
r => r.Text("strategy"), ("a", _account.AccountId), ("i", instrumentId)), cancellationToken).ConfigureAwait(false);
|
||||
var clear = true;
|
||||
foreach (var strategy in strategies)
|
||||
{
|
||||
clear &= await ClearStopsCoreAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return clear;
|
||||
}
|
||||
|
||||
/// <summary>Cancels the open stops of a position and confirms it with the broker. True when none is left open.</summary>
|
||||
private async Task<bool> ClearStopsCoreAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -174,12 +174,22 @@ public sealed partial class OrderManager : IDisposable
|
||||
{
|
||||
await RefreshOpenOrdersAsync(cancellationToken).ConfigureAwait(false);
|
||||
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
// One execution that fails must not leave the others, or the stops of the whole account, behind: the
|
||||
// first failure is raised again only after the stops are aligned.
|
||||
Exception? failure = null;
|
||||
var plans = new List<(ExecRow Exec, int Priority)>();
|
||||
foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await AdvanceAsync(exec, cancellationToken).ConfigureAwait(false) is { } priority)
|
||||
try
|
||||
{
|
||||
plans.Add((exec, priority));
|
||||
if (await AdvanceAsync(exec, cancellationToken).ConfigureAwait(false) is { } priority)
|
||||
{
|
||||
plans.Add((exec, priority));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
failure ??= ex;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,11 +201,22 @@ public sealed partial class OrderManager : IDisposable
|
||||
continue;
|
||||
}
|
||||
|
||||
await SendStepAsync(exec, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await SendStepAsync(exec, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
failure ??= ex;
|
||||
}
|
||||
}
|
||||
|
||||
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
await AlignStopsCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (failure is not null)
|
||||
{
|
||||
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -354,6 +375,14 @@ public sealed partial class OrderManager : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// A refused sale is never given up, but it is tried again with growing pauses (1, 2, 4, 8, then 15 minutes):
|
||||
// a refusal that lasts neither floods the broker nor runs out of order ids. Reconciliation finds the cause.
|
||||
var refused = orders.AsEnumerable().Reverse().TakeWhile(o => o.Status == OrderStatus.Rejected && o.Reason is not ("okx_51006" or "post_only_would_take")).ToList();
|
||||
if (exec.Side == OrderSide.Sell && refused.Count > 0 && _clock.UtcNow - refused[0].CreatedAt < RefusalPause(refused.Count))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var filled = orders.Sum(o => o.Filled);
|
||||
var remaining = exec.Quantity - filled;
|
||||
if (exec.Side == OrderSide.Sell)
|
||||
@@ -380,6 +409,18 @@ public sealed partial class OrderManager : IDisposable
|
||||
return null;
|
||||
}
|
||||
|
||||
if (quoteNow is null)
|
||||
{
|
||||
if (exec.Side == OrderSide.Buy && exec.Sequence == 0)
|
||||
{
|
||||
// No price to buy at: the decision is dropped, not left waiting.
|
||||
await FinishAsync(exec, ExecutionStates.Canceled, OrderReasons.NoPrice, instrument, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A sale waits for a price with its stops still on the broker: they are removed only right before it leaves.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (exec.Side == OrderSide.Sell && exec.Sequence == 0 && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The stops on the quantity to sell must be gone first (SPEC 7.2); they come back if the sale stops.
|
||||
@@ -387,14 +428,9 @@ public sealed partial class OrderManager : IDisposable
|
||||
}
|
||||
|
||||
if (exec.Side == OrderSide.Buy && exec.Sequence == 0 && _broker.Capabilities.OppositeSideBlocked
|
||||
&& !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Alpaca refuses a purchase while a sell stop rests on the symbol: cancel, buy, put back.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (quoteNow is null)
|
||||
&& !await ClearSymbolStopsCoreAsync(exec.InstrumentId, instrument, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// Alpaca refuses a purchase while any sell stop rests on the symbol, of any strategy: cancel, buy, put back.
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -752,14 +788,17 @@ public sealed partial class OrderManager : IDisposable
|
||||
|
||||
private const string OrderSelect =
|
||||
"SELECT id, execution_id, instrument_id, strategy, client_order_id, side, order_type, purpose, quantity, limit_price, stop_price, status, filled_quantity, " +
|
||||
"average_fill_price, reference_price, step, time_in_force, post_only, created_at FROM orders";
|
||||
"average_fill_price, reference_price, step, time_in_force, post_only, created_at, reason FROM orders";
|
||||
|
||||
private static OrderRow ReadOrder(DbRow r) => new(
|
||||
r.Id("id"), r.IdOrNull("execution_id"), r.Id("instrument_id"), r.Text("strategy"), r.Text("client_order_id"), Wire.Side(r.Text("side")), Wire.Kind(r.Text("order_type")),
|
||||
r.TextOrNull("purpose") is { } p ? Wire.Purpose(p) : OrderPurpose.Entry, r.Money("quantity"), r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"),
|
||||
Wire.Status(r.Text("status")), r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("average_fill_price"), r.MoneyOrNull("reference_price"),
|
||||
r.IsNull("step") ? null : (int)r.Number("step"), r.TextOrNull("time_in_force") is { } t ? Wire.Tif(t) : TimeInForce.Day,
|
||||
!r.IsNull("post_only") && r.Bool("post_only"), r.Moment("created_at"));
|
||||
!r.IsNull("post_only") && r.Bool("post_only"), r.Moment("created_at"), r.TextOrNull("reason"));
|
||||
|
||||
/// <summary>The pause before trying a refused sale again: 1, 2, 4, 8, then 15 minutes.</summary>
|
||||
internal static TimeSpan RefusalPause(int refusals) => TimeSpan.FromMinutes(Math.Min(15, 1 << Math.Clamp(refusals - 1, 0, 4)));
|
||||
|
||||
public void Dispose() => _gate.Dispose();
|
||||
|
||||
@@ -768,5 +807,5 @@ public sealed partial class OrderManager : IDisposable
|
||||
|
||||
private sealed record OrderRow(Guid Id, Guid? ExecutionId, Guid InstrumentId, string Strategy, string ClientOrderId, OrderSide Side, OrderKind Kind, OrderPurpose Purpose,
|
||||
decimal Quantity, decimal? Limit, decimal? Stop, OrderStatus Status, decimal Filled, decimal? AveragePrice, decimal? Reference, int? Step, TimeInForce TimeInForce,
|
||||
bool PostOnly, DateTimeOffset CreatedAt);
|
||||
bool PostOnly, DateTimeOffset CreatedAt, string? Reason = null);
|
||||
}
|
||||
@@ -223,13 +223,13 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
||||
}
|
||||
|
||||
/// <summary>Credits a cash dividend on the quantity held (SPEC 7.3), from the corporate actions.</summary>
|
||||
public async Task<decimal> PayDividendAsync(string symbol, decimal perShare, string currency, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
/// <summary>Pays a cash dividend on the shares held before the ex-date, as the broker would.</summary>
|
||||
public async Task<decimal> PayDividendAsync(string symbol, decimal heldBeforeExDate, decimal perShare, string currency, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
{
|
||||
decimal paid = 0m;
|
||||
await WithBookAsync(book =>
|
||||
{
|
||||
var held = book.Holdings.GetValueOrDefault(symbol)?.Quantity ?? 0m;
|
||||
paid = DbValues.Money(held * perShare);
|
||||
paid = DbValues.Money(heldBeforeExDate * perShare);
|
||||
if (paid <= 0m)
|
||||
{
|
||||
return false;
|
||||
@@ -242,18 +242,22 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
||||
return paid;
|
||||
}
|
||||
|
||||
/// <summary>Applies a split to the simulated holding and to resting orders: quantities times the ratio, prices divided.</summary>
|
||||
public async Task ApplySplitAsync(string symbol, decimal ratio, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Applies a split to the simulated holding and to the orders resting since before the ex-date: the
|
||||
/// <paramref name="oldShares"/> held before the ex-date become ratio times as many, at the same cost.
|
||||
/// </summary>
|
||||
public async Task ApplySplitAsync(string symbol, decimal ratio, decimal oldShares, DateTimeOffset exDate, CancellationToken cancellationToken)
|
||||
{
|
||||
await WithBookAsync(book =>
|
||||
{
|
||||
if (book.Holdings.TryGetValue(symbol, out var holding))
|
||||
if (book.Holdings.TryGetValue(symbol, out var holding) && holding.Quantity > 0m)
|
||||
{
|
||||
holding.Quantity *= ratio;
|
||||
holding.AveragePrice = DbValues.Money(holding.AveragePrice / ratio);
|
||||
var quantity = holding.Quantity + (Math.Min(oldShares, holding.Quantity) * (ratio - 1m));
|
||||
holding.AveragePrice = DbValues.Money(holding.Quantity * holding.AveragePrice / quantity);
|
||||
holding.Quantity = quantity;
|
||||
}
|
||||
|
||||
foreach (var order in book.Orders.Where(o => o.Request.Symbol == symbol && IsOpen(o)))
|
||||
foreach (var order in book.Orders.Where(o => o.Request.Symbol == symbol && IsOpen(o) && o.SubmittedAt < exDate))
|
||||
{
|
||||
order.Request = order.Request with
|
||||
{
|
||||
|
||||
@@ -151,6 +151,7 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
}
|
||||
|
||||
var now = clock.UtcNow;
|
||||
var previous = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false);
|
||||
@@ -160,9 +161,20 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
{
|
||||
var difference = new AccountDifference(DifferenceKinds.Key, account.Name, 0m, 1m, $"La chiave del conto {account.Name} permette i prelievi: non la uso per nuovi acquisti.");
|
||||
await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = @r, differences = @d, updated_at = @now WHERE account_id = @a", cancellationToken,
|
||||
("m", AccountModes.Prudent), ("now", now), ("r", KeyReason), ("d", Stored([difference], [])), ("a", account.AccountId)).ConfigureAwait(false);
|
||||
await Diary.NotifyAsync(s, clock, "key_can_withdraw",
|
||||
$"La chiave del conto {account.Name} permette i prelievi. Non faccio nuovi acquisti su quel conto: sostituiscila con una chiave senza prelievo.", cancellationToken).ConfigureAwait(false);
|
||||
("m", AccountModes.Prudent), ("now", now), ("r", KeyReason), ("d", Stored([difference], previous.Excluded)), ("a", account.AccountId)).ConfigureAwait(false);
|
||||
if (previous.ModeReason != KeyReason)
|
||||
{
|
||||
await Diary.NotifyAsync(s, clock, "key_can_withdraw",
|
||||
$"La chiave del conto {account.Name} permette i prelievi. Non faccio nuovi acquisti su quel conto: sostituiscila con una chiave senza prelievo.", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (previous.ModeReason == KeyReason)
|
||||
{
|
||||
// The key was replaced with one that cannot withdraw: the lock it caused ends; the next round compares again.
|
||||
await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = NULL, differences = @d, updated_at = @now WHERE account_id = @a", cancellationToken,
|
||||
("m", AccountModes.Normal), ("now", now), ("d", Stored([], previous.Excluded)), ("a", account.AccountId)).ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_normal",
|
||||
$"La nuova chiave del conto {account.Name} non permette i prelievi: il conto torna normale.", null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return permissions;
|
||||
@@ -177,12 +189,19 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manager);
|
||||
var account = manager.Account;
|
||||
var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false);
|
||||
if (state.ModeReason == KeyReason)
|
||||
if ((await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).ModeReason == KeyReason)
|
||||
{
|
||||
throw new InvalidOperationException("A key that may withdraw is replaced, not aligned.");
|
||||
}
|
||||
|
||||
// Compared again right now: the choice applies to the differences that exist, never to old ones.
|
||||
await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false);
|
||||
if (state.Mode != AccountModes.Prudent || state.ModeReason == KeyReason)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var excluded = state.Excluded.ToList();
|
||||
if (choice == ReconcileChoice.Align)
|
||||
{
|
||||
@@ -471,6 +490,11 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
stored = [];
|
||||
diary = $"La differenza sul conto {account.Name} si è spiegata da sola: il conto torna normale.";
|
||||
}
|
||||
else if (mode == AccountModes.Prudent && reason != KeyReason)
|
||||
{
|
||||
// After the 15 minutes the user still decides, but nothing old is kept to be aligned.
|
||||
stored = [];
|
||||
}
|
||||
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
|
||||
@@ -238,13 +238,13 @@ public sealed partial class TradingService : IDisposable
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await GuardAsync("patrimonio", () => Equity.TakeAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public IReadOnlyList<ScheduledJob> Jobs() =>
|
||||
[
|
||||
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
|
||||
new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), async ct => await Equity.TakeAsync(ct).ConfigureAwait(false)),
|
||||
new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), PhotographAsync),
|
||||
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
||||
];
|
||||
|
||||
@@ -273,6 +273,34 @@ public sealed partial class TradingService : IDisposable
|
||||
await Task.WhenAll(streams).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The positions valued at the market, then the photograph of the equity (SPEC 7.5).</summary>
|
||||
public async Task PhotographAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await MarkPositionsAsync(cancellationToken).ConfigureAwait(false);
|
||||
await Equity.TakeAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the mid of a recent quote as the last price of every position, so equity, drawdown and the Conti screen
|
||||
/// follow the market and not only the last fill. Without a quote the last known price stays.
|
||||
/// </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)
|
||||
{
|
||||
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } instrument)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote && quote.Ask >= quote.Bid)
|
||||
{
|
||||
await Ledger.MarkAsync(id, quote.Mid, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TickAllAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var manager in _managers.Values)
|
||||
@@ -331,11 +359,7 @@ public sealed partial class TradingService : IDisposable
|
||||
var instrument = held[action.Symbol];
|
||||
if (action.ChangesShares)
|
||||
{
|
||||
if (manager.Broker is PaperBroker paper && !await AppliedAsync(manager.Account.AccountId, action.SourceKey, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await paper.ApplySplitAsync(action.Symbol, action.Ratio!.Value, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The ledger and, on the simulator, the broker's book, together and once.
|
||||
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m)
|
||||
@@ -356,30 +380,40 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
|
||||
var exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
var currency = action.Currency ?? account.Currency;
|
||||
var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false))
|
||||
.Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList();
|
||||
var held = new List<(string Strategy, decimal Quantity)>();
|
||||
foreach (var strategy in strategies)
|
||||
{
|
||||
var quantity = await Ledger.QuantityAtAsync(account.AccountId, instrument.Id, strategy, exDate, cancellationToken).ConfigureAwait(false);
|
||||
if (quantity <= 0m)
|
||||
if (quantity > 0m)
|
||||
{
|
||||
continue;
|
||||
held.Add((strategy, quantity));
|
||||
}
|
||||
|
||||
var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero);
|
||||
if (manager.Broker is PaperBroker paper)
|
||||
{
|
||||
await paper.PayDividendAsync(action.Symbol, action.CashAmount!.Value, action.Currency ?? account.Currency, exDate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, action.Currency ?? account.Currency, exDate,
|
||||
$"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _db.WriteAsync(s => s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now) ON CONFLICT (account_id, source_key) DO NOTHING",
|
||||
cancellationToken, ("id", Ids.NewId(_clock)), ("a", account.AccountId), ("k", key), ("now", _clock.UtcNow)), cancellationToken).ConfigureAwait(false);
|
||||
// Each payment carries its own mark in the same write, so a failure halfway never pays anyone twice.
|
||||
if (manager.Broker is PaperBroker paper && held.Count > 0 && await MarkAppliedAsync(account.AccountId, key + ":book", cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await paper.PayDividendAsync(action.Symbol, held.Sum(h => h.Quantity), action.CashAmount!.Value, currency, exDate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (strategy, quantity) in held)
|
||||
{
|
||||
var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero);
|
||||
await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, currency, exDate,
|
||||
$"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await MarkAppliedAsync(account.AccountId, key, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Marks an action as applied to an account; false when it already was.</summary>
|
||||
private Task<bool> MarkAppliedAsync(Guid accountId, string key, CancellationToken cancellationToken) =>
|
||||
_db.WriteAsync(async s => await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now) ON CONFLICT (account_id, source_key) DO NOTHING",
|
||||
cancellationToken, ("id", Ids.NewId(_clock)), ("a", accountId), ("k", key), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0, cancellationToken);
|
||||
|
||||
private Task<bool> AppliedAsync(Guid accountId, string sourceKey, CancellationToken cancellationToken) =>
|
||||
_db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey))
|
||||
.ConfigureAwait(false) > 0, cancellationToken);
|
||||
|
||||
Reference in new issue
Block a user