Fix what a second independent reading of the Phase 8 fixes found
ci / test (postgres) (push) Failing after 6m9s
ci / test (sqlite) (push) Successful in 7m6s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Successful in 5m51s
ci / test (sqlite) (pull_request) Successful in 7m3s
ci / image (pull_request) Successful in 1m51s
ci / test (postgres) (push) Failing after 6m9s
ci / test (sqlite) (push) Successful in 7m6s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Successful in 5m51s
ci / test (sqlite) (pull_request) Successful in 7m3s
ci / image (pull_request) Successful in 1m51s
One funded signal was enough to start the model for good, because the interval of a few cases had no width: it now takes a hundred, weighed among themselves. A computer always off at 03:00 never made the night of the model: a job to make up for counts from the first start that knows it, and the night waits for the bars of the absence. Stories are seen as they were when the decision was due, a report already out does not close a label, an undone promotion starts the trial again, and the trade card finds the estimate of an example born earlier. ADR 0018 point 18 has the list; each defect has its test. refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b0f4a5e75
commit
c7e462b6f4
18 files changed
+371
-26
No files matched your search
@@ -377,6 +377,11 @@ internal sealed partial class AnubisHost(
|
||||
lastDues[name] = due;
|
||||
}
|
||||
|
||||
if (!options.Demo)
|
||||
{
|
||||
await StartCountingAsync([.. SchedulerJobs(backups)], lastDues, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_sampler is not null)
|
||||
{
|
||||
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
|
||||
@@ -506,13 +511,31 @@ internal sealed partial class AnubisHost(
|
||||
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
|
||||
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
|
||||
|
||||
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
|
||||
private IEnumerable<ScheduledJob> SchedulerJobs(Backups backups)
|
||||
{
|
||||
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
|
||||
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
||||
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
||||
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
|
||||
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
|
||||
return new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job to make up for after an absence counts from the first start that knows it. Otherwise a computer always off at
|
||||
/// its hour would never make it: without a first run there would be no run to find missed (SPEC 5.6).
|
||||
/// </summary>
|
||||
private Task StartCountingAsync(IReadOnlyList<ScheduledJob> jobs, Dictionary<string, DateTimeOffset> lastDues, CancellationToken cancellationToken) => _db!.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var job in jobs.Where(j => j.CatchUpWithin is not null && !lastDues.ContainsKey(j.Name)))
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, created_at, updated_at) VALUES (@id, @n, @d, @now, @now, @now) ON CONFLICT (name) DO NOTHING", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("n", job.Name), ("d", job.Description), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
|
||||
{
|
||||
foreach (var job in SchedulerJobs(backups))
|
||||
{
|
||||
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ internal sealed record LearningView
|
||||
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
|
||||
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
|
||||
Bands = bands,
|
||||
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
|
||||
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands, history ? null : activation.CalibrationError),
|
||||
BandsFromHistory = history && bands.Count > 0,
|
||||
Champion = Column(champion, now),
|
||||
Challenger = Column(challenger, now),
|
||||
@@ -341,7 +341,11 @@ internal sealed record LearningView
|
||||
: $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi.");
|
||||
}
|
||||
|
||||
if (!check.Improves)
|
||||
if (check.Funded < ActivationCheck.FundedNeeded)
|
||||
{
|
||||
missing.Add($"Servono almeno {ActivationCheck.FundedNeeded} segnali di strategie con un capitale, anche in simulazione: per ora {(check.Funded == 1 ? "è uno" : $"sono {Format.Number(check.Funded)}")}.");
|
||||
}
|
||||
else if (!check.Improves)
|
||||
{
|
||||
missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso.");
|
||||
}
|
||||
@@ -353,8 +357,11 @@ internal sealed record LearningView
|
||||
|
||||
private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1));
|
||||
|
||||
/// <summary>The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not count.</summary>
|
||||
public static string BandsWords(IReadOnlyList<LearningBand> bands)
|
||||
/// <summary>
|
||||
/// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not
|
||||
/// count. <paramref name="measured"/> is the error of the criterion to start counting (11.5), when it is the judge.
|
||||
/// </summary>
|
||||
public static string BandsWords(IReadOnlyList<LearningBand> bands, double? measured = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bands);
|
||||
var solid = bands.Where(b => b.Solid).ToList();
|
||||
@@ -363,10 +370,10 @@ internal sealed record LearningView
|
||||
return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci.";
|
||||
}
|
||||
|
||||
var error = solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
|
||||
var error = measured is { } known ? Round(known * 100, 1) : solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
|
||||
var best = solid[^1];
|
||||
var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " +
|
||||
(error < (decimal)ActivationCheck.MaxCalibrationError * 100 ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
|
||||
((measured is { } exact ? exact < ActivationCheck.MaxCalibrationError : error < (decimal)ActivationCheck.MaxCalibrationError * 100) ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
|
||||
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
|
||||
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
|
||||
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
|
||||
|
||||
@@ -77,7 +77,7 @@ internal static class ReasonTexts
|
||||
var applied = Number("applied") ?? 1;
|
||||
if (applied < 1)
|
||||
{
|
||||
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto";
|
||||
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {Math.Clamp(Math.Round(applied * 100), 1, 99):0}%") : said + ": acquisto non fatto";
|
||||
}
|
||||
|
||||
bool Is(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
|
||||
|
||||
@@ -180,9 +180,9 @@ internal sealed record TradesView(
|
||||
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
|
||||
|
||||
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
|
||||
var m = d.Any(x => x.Stage == DecisionStages.Model) ? [] : await s.QueryAsync(
|
||||
var m = await s.QueryAsync(
|
||||
"SELECT d.outcome, d.data FROM decisions d JOIN ml_features f ON f.decision_id = d.decision_id AND f.symbol = d.symbol LEFT JOIN ml_labels l ON l.feature_id = f.id " +
|
||||
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day > @o) ORDER BY d.created_at DESC LIMIT 1",
|
||||
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day >= @o) ORDER BY d.created_at DESC LIMIT 1",
|
||||
r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), ("st", DecisionStages.Model), ("s", t.Strategy), ("sym", t.Symbol), ("t", t.OpenedAt.AddMinutes(5)),
|
||||
("o", DateOnly.FromDateTime(t.OpenedAt.UtcDateTime).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
return (e, d, m);
|
||||
@@ -200,7 +200,10 @@ internal sealed record TradesView(
|
||||
: sell.Purpose is "stop" or "protective" ? "stop" : null;
|
||||
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
|
||||
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
|
||||
List<WhyLine> bought = [.. Lines(buy.Key), .. earlier.SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
|
||||
|
||||
// The decision of the purchase has its own line when the example was born with it.
|
||||
var own = buy.Key is not null && byKey.TryGetValue(buy.Key, out var entryRows) && entryRows.Any(r => r.Stage == DecisionStages.Model);
|
||||
List<WhyLine> bought = [.. Lines(buy.Key), .. (own ? [] : earlier).SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
|
||||
return (bought, sold, entrySlip, exitSlip, code);
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ public sealed class OutsideReader(Database db, IClock clock, SettingsStore? sett
|
||||
var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false);
|
||||
foreach (var (symbol, spec) in specs)
|
||||
{
|
||||
var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.NormWindow, cancellationToken).ConfigureAwait(false);
|
||||
var stories = await _desk.StoriesAtAsync(NewsDesk.Target(spec), at - NewsRules.NormWindow, at, cancellationToken).ConfigureAwait(false);
|
||||
news[symbol] = NewsRules.State([.. stories], at, switches, first);
|
||||
counts[symbol] = stories.Count(s => s.FirstSeenAt <= at && s.Start > at - TimeSpan.FromDays(3) && s.Start <= at);
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ public static class CaseLabels
|
||||
/// <summary>
|
||||
/// The outcome with the bars of <paramref name="data"/> up to <paramref name="through"/>; null while the operation is
|
||||
/// open. The strategy is built fresh: it walks the bars again. <paramref name="earnings"/> is the first report after the
|
||||
/// decision, which <c>equity_meanrev</c> leaves before.
|
||||
/// decision, which <c>equity_meanrev</c> leaves before; one out by the entry session is not ahead any more.
|
||||
/// </summary>
|
||||
public static CaseLabel? Of(Example example, Func<IStrategy> strategy, BacktestDataset data, DateOnly through, CostModel? costs = null, DateOnly? earnings = null)
|
||||
{
|
||||
@@ -158,6 +158,11 @@ public static class CaseLabels
|
||||
return null;
|
||||
}
|
||||
|
||||
if (earnings is { } report && (instrument.Bars.FirstOrDefault(b => b.Day > example.Day) is not { } entry || report <= entry.Day))
|
||||
{
|
||||
earnings = null;
|
||||
}
|
||||
|
||||
var alone = SingleOperation.NeedsUniverse(example.Strategy) ? data : new BacktestDataset([instrument], data.Currency, data.Calendar);
|
||||
foreach (var until in Horizons.Select(h => example.Day.AddDays(h)).Where(d => d < through).Append(through))
|
||||
{
|
||||
|
||||
@@ -195,26 +195,32 @@ public sealed record ActivationCheck(int Evaluated, Scores Scores, double? Calib
|
||||
|
||||
public const double MaxCalibrationError = 0.05;
|
||||
|
||||
/// <summary>The improvement is measured on at least this many signals of strategies with capital (ADR 0018).</summary>
|
||||
public const int FundedNeeded = 100;
|
||||
|
||||
/// <summary>The signals of strategies with capital at that moment: those the improvement is measured on.</summary>
|
||||
public int Funded { get; init; }
|
||||
|
||||
public bool Enough => Evaluated >= Needed;
|
||||
|
||||
public bool Calibrated => CalibrationError is { } error && error < MaxCalibrationError;
|
||||
|
||||
public bool Improves => Low > 0;
|
||||
public bool Improves => Funded >= FundedNeeded && Low > 0;
|
||||
|
||||
public bool Passed => Enough && Calibrated && Improves;
|
||||
|
||||
/// <summary>
|
||||
/// On the estimates that were in charge when each signal came, whatever version made them, weighed by maturation; the
|
||||
/// improvement only on signals of strategies with capital at that moment.
|
||||
/// improvement only on signals of strategies with capital at that moment, weighed among themselves.
|
||||
/// </summary>
|
||||
public static ActivationCheck Of(IReadOnlyList<Estimate> inCharge, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capital)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(inCharge);
|
||||
var weighed = Judge.Weigh(inCharge, baseRates);
|
||||
var scores = Judge.Score(weighed, capital, IsFunded);
|
||||
var funded = weighed.Where(e => IsFunded(e.Case)).ToList();
|
||||
var funded = Judge.Weigh([.. inCharge.Where(e => IsFunded(e.Case))], baseRates);
|
||||
var paid = Judge.Score(funded, capital);
|
||||
var scores = Judge.Score(Judge.Weigh(inCharge, baseRates), capital) with { GainWithout = paid.GainWithout, GainWith = paid.GainWith };
|
||||
var (low, high) = Judge.Interval([.. funded.Select(e => (e.Multiplier - 1) * Judge.Gain(e.Case, capital))], [.. funded.Select(e => e.Weight)], 0.90);
|
||||
return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high);
|
||||
return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high) { Funded = funded.Count };
|
||||
}
|
||||
|
||||
/// <summary>A signal of a strategy that had capital: zeroing those of a candidate in observation is no merit (SPEC 11.3).</summary>
|
||||
|
||||
@@ -177,7 +177,8 @@ public static class Judge
|
||||
|
||||
/// <summary>
|
||||
/// A bootstrap interval of the weighted mean of <paramref name="values"/> that keeps neighbours together: blocks of
|
||||
/// <paramref name="block"/> in a row, because operations close in time win and lose together.
|
||||
/// <paramref name="block"/> in a row, because operations close in time win and lose together. With fewer than three
|
||||
/// blocks nothing can be said: the interval is everything.
|
||||
/// </summary>
|
||||
public static (double Low, double High) Interval(IReadOnlyList<double> values, IReadOnlyList<double> weights, double confidence, int block = 10, int rounds = 2000, long seed = 20_261_201)
|
||||
{
|
||||
@@ -189,7 +190,12 @@ public static class Judge
|
||||
return (0, 0);
|
||||
}
|
||||
|
||||
var size = Math.Clamp(block, 1, n);
|
||||
var size = Math.Max(block, 1);
|
||||
if (n < 3 * size)
|
||||
{
|
||||
return (double.NegativeInfinity, double.PositiveInfinity);
|
||||
}
|
||||
|
||||
var random = new FixedRandom(seed);
|
||||
var means = new double[rounds];
|
||||
for (var r = 0; r < rounds; r++)
|
||||
|
||||
@@ -319,6 +319,13 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
|
||||
|
||||
await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Undone, cancellationToken).ConfigureAwait(false);
|
||||
await ModelStore.SetStatusAsync(s, clock, previous, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// The one on trial starts again: its cases of comparison were against the model just taken away.
|
||||
if (await ModelStore.FindAsync(s, ModelStatuses.Challenger).ConfigureAwait(false) is { } trial)
|
||||
{
|
||||
await ModelStore.SetThresholdAsync(s, clock, trial.Id, 0, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var text = $"Promozione annullata da te: torna in carica la versione {back.Version} al posto della {champion.Version}.";
|
||||
await ModelStore.AddEventAsync(s, clock, ModelEvents.Undone, back.Version, text, cancellationToken).ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_undone", text, null, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -314,7 +314,16 @@ public sealed class LearningTurn
|
||||
{
|
||||
if (context.Day == _day && _collector.Cases.FirstOrDefault(c => c.Symbol == symbol) is { } made)
|
||||
{
|
||||
return AppliedTo(made);
|
||||
try
|
||||
{
|
||||
return AppliedTo(made);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Only the new operation goes on as without a model: those already born keep their multiplier.
|
||||
_failed(ex);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// The operation was born with the latest example before this day: without one, or with nothing held of one already
|
||||
|
||||
@@ -31,6 +31,26 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
|
||||
"WHERE l.scope = @scope AND l.target = @t AND st.last_seen_at >= @since ORDER BY st.published_at, st.id",
|
||||
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since)), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// The stories as they were at <paramref name="at"/>: only the articles, the links and the verdicts saved by then. A
|
||||
/// story keeps growing after it is first read, and a decision recovered hours later must not see it grown (11.2).
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<StoryFact>> StoriesAtAsync(string target, DateTimeOffset since, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
{
|
||||
const string Then = "FROM news_items i WHERE i.story_id = st.id AND i.created_at <= @at";
|
||||
const string Highest = "(SELECT MAX(x.importance) FROM news_items x WHERE x.story_id = st.id AND x.created_at <= @at)";
|
||||
return await db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, (SELECT COUNT(DISTINCT i.publisher) " + Then + ") AS sources, " +
|
||||
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = st.id AND i.created_at <= @at AND so.trusted = @yes) > 0 AS trusted, " +
|
||||
"(SELECT AVG(i.score) " + Then + ") AS score, (SELECT i.severe " + Then + " AND i.severe IS NOT NULL ORDER BY " + NewsStore.SevereOrder + ", i.id LIMIT 1) AS severe, " +
|
||||
Highest + " AS importance, (SELECT MIN(i.published_at) " + Then + " AND i.importance = " + Highest + ") AS raised_at, " +
|
||||
"v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, " +
|
||||
"(SELECT i.publisher " + Then + " ORDER BY i.created_at, i.id LIMIT 1) AS publisher " +
|
||||
"FROM news_stories st JOIN news_links l ON l.story_id = st.id LEFT JOIN news_verdicts v ON v.id = st.verdict_id AND v.created_at <= @at " +
|
||||
"WHERE l.scope = @scope AND l.target = @t AND l.created_at <= @at AND st.last_seen_at >= @since AND EXISTS (SELECT 1 " + Then + ") ORDER BY st.published_at, st.id",
|
||||
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since), ("at", at), ("yes", true)), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The state of 10.2 point 6 of one instrument now.</summary>
|
||||
public async Task<InstrumentNewsState> StateAsync(string target, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -259,7 +259,7 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0";
|
||||
|
||||
// The serious cases in the order of 10.2.
|
||||
private const string SevereOrder =
|
||||
internal const string SevereOrder =
|
||||
"CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" +
|
||||
SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END";
|
||||
|
||||
|
||||
@@ -531,9 +531,40 @@ public sealed partial class TradingService : IDisposable
|
||||
/// <summary>The slippage in force, from the next fill of the simulator on.</summary>
|
||||
public async Task RefreshCostsAsync(CancellationToken cancellationToken) => _slippage = await Costs.TableAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>The longest the night waits for the bars: without a network it goes on with those it has.</summary>
|
||||
public static readonly TimeSpan BarsWait = TimeSpan.FromMinutes(30);
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the bars through the last closed day are downloaded: after an absence the night starts with the process,
|
||||
/// and labels made on the bars of before would see nothing of what happened meanwhile (SPEC 5.6, 9.4).
|
||||
/// </summary>
|
||||
public static async Task BarsReadyAsync(IClock clock, Func<DateTimeOffset?> lastRound, Func<Task> ask, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(lastRound);
|
||||
ArgumentNullException.ThrowIfNull(ask);
|
||||
var now = clock.UtcNow;
|
||||
var midnight = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
|
||||
if (lastRound() >= midnight)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await ask().ConfigureAwait(false);
|
||||
while (!(lastRound() >= midnight) && clock.UtcNow < now + BarsWait)
|
||||
{
|
||||
await clock.WaitUntilAsync(clock.UtcNow + TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// A part of the night that fails never stops the others.
|
||||
private async Task NightAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_market is { } market)
|
||||
{
|
||||
await BarsReadyAsync(_clock, () => market.LastHistoryRun, market.WakeWorker, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Cycle.RunAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Reference in new issue
Block a user