Apply the SPEC 10.5 news and calendar rules to new entries (refs #59)
ci / test (postgres) (push) Successful in 8m20s
ci / test (sqlite) (push) Successful in 4m25s
ci / test (postgres) (pull_request) Successful in 8m13s
ci / test (sqlite) (pull_request) Successful in 4m38s
ci / image (push) Successful in 2m5s
ci / image (pull_request) Successful in 2m6s
ci / test (postgres) (push) Successful in 8m20s
ci / test (sqlite) (push) Successful in 4m25s
ci / test (postgres) (pull_request) Successful in 8m13s
ci / test (sqlite) (pull_request) Successful in 4m38s
ci / image (push) Successful in 2m5s
ci / image (pull_request) Successful in 2m6s
Confirmed serious events hold new purchases of an instrument for 72 hours and keep its stop where it is; confirmed negative news holds them for 24 hours; an unconfirmed rumour only gets a diary note and a check two hours later. Coming earnings keep mean reversion out and macro figures hold entries around their release, now in the live engine too. The strictest row wins, every row can be switched off in the settings, and windows count from the fact, so after an absence only effects still in force apply. A held purchase moves to the end of its restriction while the order is still valid and keeps its first due time, so the price drift check of SPEC 5.6 still compares with the decision. Each restriction is written to the diary once, with its motive. The per-instrument state keeps the tone over one and three days, the story count against its norm and the active restriction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1aede2fc1c
commit
b087dd215b
21 files changed
+1170
-30
No files matched your search
@@ -23,6 +23,12 @@ public sealed record BacktestOptions
|
||||
/// <summary>The risk engine of SPEC 9. Until Phase 5 it lets everything through.</summary>
|
||||
public IIntentStage Risk { get; init; } = PassThroughStage.Risk;
|
||||
|
||||
/// <summary>The earnings calendar, live only (SPEC 8.3): a backtest has none and leaves it null.</summary>
|
||||
public Func<string, DateOnly?>? NextEarnings { get; init; }
|
||||
|
||||
/// <summary>Whether coming earnings keep entries out (SPEC 10.5, fourth row).</summary>
|
||||
public bool EarningsEntries { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// The strategy's share of the bot's total capital (SPEC 8.6, 9.2): the reference equity is the strategy's equity
|
||||
/// divided by it. Null means the strategy is the whole bot.
|
||||
@@ -414,6 +420,8 @@ public static class BacktestEngine
|
||||
var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), Bars, s => _data[s]?.Spec)
|
||||
{
|
||||
NextSession = _data.NextSession(day),
|
||||
NextEarnings = _options.NextEarnings,
|
||||
EarningsEntries = _options.EarningsEntries,
|
||||
ReferenceEquity = _options.ReferenceShare is > 0m and var share ? equity / share : equity,
|
||||
PeriodsPerYear = _data.PeriodsPerYear,
|
||||
History = _history,
|
||||
|
||||
@@ -149,6 +149,9 @@ public static class Format
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>A day in words, for the diary: <c>martedì 13 ottobre</c>.</summary>
|
||||
public static string Day(DateOnly day) => string.Create(CultureInfo.InvariantCulture, $"{_daysLong[(int)day.DayOfWeek]} {day.Day} {_monthsLong[day.Month - 1]}");
|
||||
|
||||
/// <summary>Full date for the top bar: <c>Venerdì 9 ottobre 2026, ore 08:21</c>.</summary>
|
||||
public static string LongDateTime(DateTimeOffset moment, TimeZoneInfo zone)
|
||||
{
|
||||
|
||||
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
|
||||
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
|
||||
|
||||
public static readonly IReadOnlyList<SettingDefinition> All =
|
||||
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
|
||||
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All];
|
||||
|
||||
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
|
||||
|
||||
|
||||
@@ -82,7 +82,11 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_universes = new UniverseStore(db, clock);
|
||||
_builder = new UniverseBuilder(db, clock);
|
||||
_states = new SourceStateStore(db, clock);
|
||||
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") };
|
||||
News = new News.NewsCollector(_http, db, clock, _logger)
|
||||
{
|
||||
ModelFolder = data is null ? null : Path.Combine(data.Root, "models"),
|
||||
Watcher = new News.NewsWatcher(db, clock, settings),
|
||||
};
|
||||
}
|
||||
|
||||
public OkxClient Okx { get; }
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
-- The rules of SPEC 10.5 (issue #59).
|
||||
|
||||
-- An entry held back by a restriction is tried again when it ends: due_at moves, first_due_at keeps the time it was
|
||||
-- first due, so the price check of SPEC 5.6 still compares with the price of the decision.
|
||||
ALTER TABLE planned_orders ADD COLUMN first_due_at {timestamp};
|
||||
|
||||
-- What the diary has already said about a story or an event on one instrument: a restriction, an unconfirmed story,
|
||||
-- its check two hours later, coming earnings. subject is 'story:<id>' or 'event:<source_key>', target 'venue:symbol';
|
||||
-- each line is written once.
|
||||
CREATE TABLE news_notes (
|
||||
id {uuid} PRIMARY KEY,
|
||||
subject TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
UNIQUE (subject, target, kind)
|
||||
){strict};
|
||||
@@ -117,8 +117,16 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
first = false;
|
||||
await ReadAsync(source, dictionary, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Watcher is not null)
|
||||
{
|
||||
await Watcher.RunOnceAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the diary says of the news on the instruments held or watched (SPEC 10.5), after each round.</summary>
|
||||
public NewsWatcher? Watcher { get; init; }
|
||||
|
||||
/// <summary>Whether a source is due: always while it answers, later and later while it fails.</summary>
|
||||
public static bool Due(NewsSource source, DateTimeOffset now)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>
|
||||
/// The news of one instrument as the rules of SPEC 10.5 read them: its stories, its state (10.2 point 6), the
|
||||
/// restriction in force. Only links to the instrument itself count: a story on "crypto" or on the market restricts
|
||||
/// no single coin or stock.
|
||||
/// </summary>
|
||||
public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings = null)
|
||||
{
|
||||
/// <summary>The name of an instrument in news_links: <c>venue:symbol</c>.</summary>
|
||||
public static string Target(InstrumentSpec spec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
return spec.Venue + ":" + spec.Symbol;
|
||||
}
|
||||
|
||||
public Task<NewsRuleSwitches> SwitchesAsync(CancellationToken cancellationToken) => NewsRuleSettings.LoadAsync(settings, cancellationToken);
|
||||
|
||||
/// <summary>The stories linked to <paramref name="target"/> seen since <paramref name="since"/>, oldest first.</summary>
|
||||
public async Task<IReadOnlyList<StoryFact>> StoriesAsync(string target, DateTimeOffset since, CancellationToken cancellationToken) =>
|
||||
await db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " +
|
||||
"(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id 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 WHERE l.scope = @scope AND l.target = @t AND st.last_seen_at >= @since " +
|
||||
"ORDER BY st.published_at, st.id",
|
||||
ReadStory, ("scope", LinkScopes.Instrument), ("t", target), ("since", since)), 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)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var stories = await StoriesAsync(target, now - NewsRules.NormWindow, cancellationToken).ConfigureAwait(false);
|
||||
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(first_seen_at) AS first FROM news_stories", r => r.MomentOrNull("first")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return NewsRules.State([.. stories], now, await SwitchesAsync(cancellationToken).ConfigureAwait(false), first);
|
||||
}
|
||||
|
||||
/// <summary>The restrictions in force on an instrument at <paramref name="at"/>, with the rows the user left on.</summary>
|
||||
public async Task<IReadOnlyList<NewsRestriction>> RestrictionsAsync(string target, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
{
|
||||
var stories = await StoriesAsync(target, at - NewsRules.Longest, cancellationToken).ConfigureAwait(false);
|
||||
return NewsRules.Active(stories, at, await SwitchesAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next earnings date of each stock from <paramref name="from"/> on, as the calendar of 4.4 has it: the day in
|
||||
/// New York. <c>equity_meanrev</c> reads it (10.5, fourth row; 8.3 for its exit).
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyDictionary<string, DateOnly>> EarningsAsync(DateOnly from, CancellationToken cancellationToken)
|
||||
{
|
||||
var start = Zones.At(from, TimeOnly.MinValue, Zones.NewYork);
|
||||
var events = await new CalendarEventStore(db, clock).BetweenAsync(start, start.AddDays(31), cancellationToken).ConfigureAwait(false);
|
||||
var next = new Dictionary<string, DateOnly>(StringComparer.Ordinal);
|
||||
foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { Length: > 0 }).OrderBy(e => e.OccursAt))
|
||||
{
|
||||
next.TryAdd(e.Symbol!, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime));
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
private static StoryFact ReadStory(DbRow r) => new(r.Id("id"), r.Text("title"), r.TextOrNull("publisher") ?? "", r.Moment("published_at"), r.Moment("first_seen_at"),
|
||||
(int)r.Number("sources"), r.Bool("trusted"), r.IsNull("score") ? null : r.Measure("score"), r.TextOrNull("severe"), (int)r.Number("importance"));
|
||||
}
|
||||
|
||||
/// <summary>Why an entry cannot go now, and until when (SPEC 10.5). The motive is what the diary says after "Motivo:".</summary>
|
||||
public sealed record EntryHold(string Code, DateTimeOffset Until, string Motive);
|
||||
|
||||
/// <summary>The check the live engine makes before a purchase goes out, and before it lowers a stop.</summary>
|
||||
public interface IEntryGate
|
||||
{
|
||||
/// <summary>The restriction that stops a purchase of the instrument at <paramref name="at"/>, or null.</summary>
|
||||
Task<EntryHold?> HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The serious event that keeps the stop of a position where it is, or null.</summary>
|
||||
Task<EntryHold?> KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rows of 10.5 that act on a single purchase: the news on the instrument (first two rows) and the high-impact
|
||||
/// figures (fifth row), the strictest of them. The earnings row acts inside <c>equity_meanrev</c>, which knows its
|
||||
/// sessions; the third row never stops anything.
|
||||
/// </summary>
|
||||
public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings = null) : IEntryGate
|
||||
{
|
||||
private readonly NewsDesk _desk = new(db, clock, settings);
|
||||
private readonly CalendarEventStore _calendar = new(db, clock);
|
||||
|
||||
public async Task<EntryHold?> HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var holds = new List<EntryHold>();
|
||||
if (NewsRules.Strictest(await _desk.RestrictionsAsync(NewsDesk.Target(spec), at, cancellationToken).ConfigureAwait(false)) is { } news)
|
||||
{
|
||||
holds.Add(new EntryHold(news.Code, news.Until, Motive(news.Story)));
|
||||
}
|
||||
|
||||
if (switches.Macro)
|
||||
{
|
||||
var events = await _calendar.BetweenAsync(at - TimeSpan.FromHours(3), at + TimeSpan.FromHours(3), cancellationToken).ConfigureAwait(false);
|
||||
if (CalendarBlocks.BlockedUntil(at, events) is { } until)
|
||||
{
|
||||
var named = events.Where(e => CalendarBlocks.Window(e) is { } w && w.From <= at && w.To > at).OrderByDescending(e => CalendarBlocks.Window(e)!.Value.To).First();
|
||||
holds.Add(new EntryHold(CorrectiveReasons.CalendarEvent, until, named.Title));
|
||||
}
|
||||
}
|
||||
|
||||
return holds.OrderByDescending(h => h.Until).FirstOrDefault();
|
||||
}
|
||||
|
||||
public async Task<EntryHold?> KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
return NewsRules.KeepsStop(await _desk.RestrictionsAsync(NewsDesk.Target(spec), at, cancellationToken).ConfigureAwait(false)) is { } severe
|
||||
? new EntryHold(NewsReasons.KeepStop, severe.Until, Motive(severe.Story))
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>The story as the diary names it: its title in quotes and who published it.</summary>
|
||||
public static string Motive(StoryFact story)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(story);
|
||||
var title = story.Title.Length > 160 ? story.Title[..157] + "…" : story.Title;
|
||||
return story.Publisher.Length > 0 ? $"«{title}» ({story.Publisher})" : $"«{title}»";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the diary says of the news on the instruments the bot holds or may buy (SPEC 10.5, appendix F.10): a
|
||||
/// restriction when it starts, with its motive; a story from one untrusted source, and its check two hours later; the
|
||||
/// earnings coming for a stock. A serious event also goes to Telegram. Each line is written once (news_notes).
|
||||
/// </summary>
|
||||
public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settings = null)
|
||||
{
|
||||
private readonly NewsDesk _desk = new(db, clock, settings);
|
||||
|
||||
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
|
||||
|
||||
/// <summary>One round over the instruments watched now: those held by any strategy and those of the latest universes.</summary>
|
||||
public async Task<int> RunOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var watched = await WatchedAsync(cancellationToken).ConfigureAwait(false);
|
||||
var written = 0;
|
||||
foreach (var (target, symbol, held) in watched)
|
||||
{
|
||||
var stories = await _desk.StoriesAsync(target, now - NewsRules.Longest, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var restriction in NewsRules.Active(stories, now, switches))
|
||||
{
|
||||
var text = Restricted(restriction, symbol, held);
|
||||
written += await NoteAsync("story:" + restriction.Story.Id, target, restriction.Code, text, restriction.Code == NewsReasons.Severe, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!switches.Unconfirmed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var story in stories.Where(NewsRules.Unconfirmed))
|
||||
{
|
||||
var subject = "story:" + story.Id;
|
||||
if (now - story.FirstSeenAt < NewsRules.RecheckAfter)
|
||||
{
|
||||
written += await NoteAsync(subject, target, NewsReasons.Unconfirmed,
|
||||
$"Voce non confermata su {Trading.DiaryText.Shown(symbol)}: {EntryGate.Motive(story)}. Nessuna azione: ricontrollo tra 2 ore.", false, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (now - story.FirstSeenAt < NewsRules.Longest)
|
||||
{
|
||||
written += await NoteAsync(subject, target, NewsReasons.Rechecked,
|
||||
$"Ricontrollata la voce su {Trading.DiaryText.Shown(symbol)}: nessun'altra fonte la conferma, nessuna azione.", false, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (switches.Earnings)
|
||||
{
|
||||
written += await EarningsAsync(watched, now, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
private static string Restricted(NewsRestriction r, string symbol, bool held)
|
||||
{
|
||||
var shown = Trading.DiaryText.Shown(symbol);
|
||||
if (r.Code == NewsReasons.Severe)
|
||||
{
|
||||
var stop = held ? " Lo stop resta dov'è." : "";
|
||||
return $"Ho messo una restrizione per 72 ore: niente nuovi acquisti di {shown}.{stop} Motivo: {EntryGate.Motive(r.Story)}.";
|
||||
}
|
||||
|
||||
var what = held ? $"non aumento la posizione su {shown}" : $"non compro {shown}";
|
||||
return $"Ho cambiato una regola per 24 ore: {what}. Motivo: {EntryGate.Motive(r.Story)}.";
|
||||
}
|
||||
|
||||
// Earnings of a watched stock in the next five days (three sessions and a weekend): said once, with the day.
|
||||
private async Task<int> EarningsAsync(IReadOnlyList<(string Target, string Symbol, bool Held)> watched, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var stocks = watched.Where(w => w.Target.StartsWith(Venues.Alpaca + ":", StringComparison.Ordinal)).ToDictionary(w => w.Symbol, w => w.Target, StringComparer.Ordinal);
|
||||
if (stocks.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var written = 0;
|
||||
var events = await new CalendarEventStore(db, clock).BetweenAsync(now, now.AddDays(5), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { } s && stocks.ContainsKey(s)))
|
||||
{
|
||||
var dayText = Format.Day(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime));
|
||||
var (when, until) = e.TimeHint switch
|
||||
{
|
||||
"bmo" => (" prima dell'apertura", $"fino a {dayText}"),
|
||||
"dmh" => (" durante la seduta", $"fino a {dayText}"),
|
||||
"amc" => (" dopo la chiusura", "fino alla seduta dopo i conti"),
|
||||
_ => ("", "fino alla seduta dopo i conti"),
|
||||
};
|
||||
var text = $"Ho messo una restrizione {until}: niente mean reversion su {e.Symbol}. Motivo: {e.Symbol} pubblica i conti {dayText}{when}.";
|
||||
written += await NoteAsync("event:" + e.SourceKey, stocks[e.Symbol!], NewsReasons.Earnings, text, false, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
private Task<int> NoteAsync(string subject, string target, string kind, string text, bool telegram, CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(async s =>
|
||||
{
|
||||
var seen = await s.FirstOrDefaultAsync("SELECT id FROM news_notes WHERE subject = @s AND target = @t AND kind = @k", r => r.IdOrNull("id"),
|
||||
("s", subject), ("t", target), ("k", kind)).ConfigureAwait(false);
|
||||
if (seen is not null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO news_notes (id, subject, target, kind, created_at) VALUES (@id, @s, @t, @k, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("s", subject), ("t", target), ("k", kind), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
await Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.News, kind, text, new { subject, target }, cancellationToken).ConfigureAwait(false);
|
||||
if (telegram)
|
||||
{
|
||||
await Notifications.NotificationSender.EnqueueAsync(s, clock, kind, text, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}, cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<(string Target, string Symbol, bool Held)>> WatchedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var held = await db.ReadAsync(s => s.QueryAsync("SELECT i.venue, i.symbol, p.quantity FROM positions p JOIN instruments i ON i.id = p.instrument_id",
|
||||
r => (Venue: r.Text("venue"), Symbol: r.Text("symbol"), Quantity: r.Money("quantity"))), cancellationToken).ConfigureAwait(false);
|
||||
var members = await db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT i.venue, i.symbol FROM universe_members u JOIN instruments i ON i.id = u.instrument_id " +
|
||||
"WHERE u.as_of = (SELECT MAX(x.as_of) FROM universe_members x WHERE x.universe = u.universe)",
|
||||
r => (Venue: r.Text("venue"), Symbol: r.Text("symbol"))), cancellationToken).ConfigureAwait(false);
|
||||
var holding = held.Where(h => h.Quantity > 0m).Select(h => h.Venue + ":" + h.Symbol).ToHashSet(StringComparer.Ordinal);
|
||||
return [.. held.Where(h => h.Quantity > 0m).Select(h => (h.Venue, h.Symbol)).Concat(members).Distinct()
|
||||
.Select(m => (m.Venue + ":" + m.Symbol, m.Symbol, holding.Contains(m.Venue + ":" + m.Symbol))).OrderBy(m => m.Item1, StringComparer.Ordinal)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>Reason codes of the rules of SPEC 10.5: the decisions table and the diary use them (ReasonCatalog).</summary>
|
||||
public static class NewsReasons
|
||||
{
|
||||
/// <summary>First row: a serious negative event, confirmed. No new entries for 72 hours, the stop is not widened.</summary>
|
||||
public const string Severe = "news_severe";
|
||||
|
||||
/// <summary>Second row: a negative story of importance 3, confirmed. No entries nor increases for 24 hours.</summary>
|
||||
public const string Negative = "news_negative";
|
||||
|
||||
/// <summary>Third row: one untrusted source only. Nothing happens; it is checked again after 2 hours.</summary>
|
||||
public const string Unconfirmed = "news_unconfirmed";
|
||||
|
||||
/// <summary>The check two hours later of a story that was not confirmed.</summary>
|
||||
public const string Rechecked = "news_rechecked";
|
||||
|
||||
/// <summary>A position under a serious event: the strategy wanted a lower stop and it stayed where it was.</summary>
|
||||
public const string KeepStop = "news_keep_stop";
|
||||
|
||||
/// <summary>Fourth row: earnings coming, no entries of <c>equity_meanrev</c>.</summary>
|
||||
public const string Earnings = "calendar_earnings";
|
||||
}
|
||||
|
||||
/// <summary>What the rules know of a story linked to an instrument (the tables of 0008).</summary>
|
||||
public sealed record StoryFact(Guid Id, string Title, string Publisher, DateTimeOffset PublishedAt, DateTimeOffset FirstSeenAt, int Sources, bool Trusted, double? Score,
|
||||
string? Severe, int Importance)
|
||||
{
|
||||
/// <summary>A trusted source, or two independent ones (10.5).</summary>
|
||||
public bool Confirmed => Trusted || Sources >= 2;
|
||||
|
||||
/// <summary>
|
||||
/// When the effect starts: the publication, or the moment the bot read it when a feed dates it in the future. The
|
||||
/// windows of 10.5 are counted from the fact, so after an absence an effect already over is not applied (5.6).
|
||||
/// </summary>
|
||||
public DateTimeOffset Start => PublishedAt < FirstSeenAt ? PublishedAt : FirstSeenAt;
|
||||
|
||||
/// <summary>A serious case (importance 4 or 5): the keywords of 10.2 name only negative facts.</summary>
|
||||
public bool IsSevere => Importance >= 4;
|
||||
|
||||
/// <summary>A negative story of importance 3. The slightly negative ones stay below 3 and create no restriction.</summary>
|
||||
public bool IsNegative => Importance == 3 && Score is not > -0.2;
|
||||
|
||||
/// <summary>Whether the story is one that can restrict: serious, or negative of importance 3.</summary>
|
||||
public bool Matters => IsSevere || IsNegative;
|
||||
}
|
||||
|
||||
/// <summary>An effect of 10.5 on one instrument: what it forbids, from when, until when, and the story behind it.</summary>
|
||||
public sealed record NewsRestriction(string Code, DateTimeOffset From, DateTimeOffset Until, StoryFact Story)
|
||||
{
|
||||
/// <summary>How strict it is when two last as long: the serious event wins, it also keeps the stop.</summary>
|
||||
public int Rank => Code == NewsReasons.Severe ? 2 : 1;
|
||||
}
|
||||
|
||||
/// <summary>The rows of 10.5 the user left on (Impostazioni → Notizie e calendario). All on by default.</summary>
|
||||
public sealed record NewsRuleSwitches(bool Severe = true, bool Negative = true, bool Unconfirmed = true, bool Earnings = true, bool Macro = true)
|
||||
{
|
||||
public static NewsRuleSwitches AllOn { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>The state of one instrument after its news (10.2 point 6): the clues of 11.2 and the Notizie screen read it.</summary>
|
||||
public sealed record InstrumentNewsState(double? Tone1Day, double? Tone3Days, int Stories1Day, double? NormalPerDay, NewsRestriction? Active)
|
||||
{
|
||||
/// <summary>The news of the last day compared with the usual: 1 is a normal day, 3 three times as many.</summary>
|
||||
public double? Busy => NormalPerDay is > 0 and var normal ? Stories1Day / normal : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules of SPEC 10.5 and the state of 10.2 point 6, as pure functions of the stories and the time: the same
|
||||
/// stories at the same moment always give the same answer. The rules only take away: no row ever buys or sells.
|
||||
/// </summary>
|
||||
public static class NewsRules
|
||||
{
|
||||
public static TimeSpan SevereWindow { get; } = TimeSpan.FromHours(72);
|
||||
|
||||
public static TimeSpan NegativeWindow { get; } = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>A story from one untrusted source is checked again this long after the bot first read it.</summary>
|
||||
public static TimeSpan RecheckAfter { get; } = TimeSpan.FromHours(2);
|
||||
|
||||
/// <summary>The longest window: older stories cannot restrict anything.</summary>
|
||||
public static TimeSpan Longest => SevereWindow;
|
||||
|
||||
/// <summary>How long the norm of the number of stories is measured on.</summary>
|
||||
public static TimeSpan NormWindow { get; } = TimeSpan.FromDays(30);
|
||||
|
||||
/// <summary>The restrictions in force at <paramref name="now"/> on one instrument, from its stories.</summary>
|
||||
public static IReadOnlyList<NewsRestriction> Active(IEnumerable<StoryFact> stories, DateTimeOffset now, NewsRuleSwitches switches)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stories);
|
||||
ArgumentNullException.ThrowIfNull(switches);
|
||||
var active = new List<NewsRestriction>();
|
||||
foreach (var story in stories)
|
||||
{
|
||||
// An unconfirmed story does nothing (third row), whatever it says; once confirmed the start is still the fact.
|
||||
if (!story.Matters || !story.Confirmed || story.FirstSeenAt > now)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (on, code, window) = story.IsSevere ? (switches.Severe, NewsReasons.Severe, SevereWindow) : (switches.Negative, NewsReasons.Negative, NegativeWindow);
|
||||
var until = story.Start + window;
|
||||
if (on && story.Start <= now && now < until)
|
||||
{
|
||||
active.Add(new NewsRestriction(code, story.Start, until, story));
|
||||
}
|
||||
}
|
||||
|
||||
return active;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The strictest of the restrictions (10.5: "vale la più restrittiva"): the one that lasts longest, the serious
|
||||
/// event when two end together. Null when nothing is in force.
|
||||
/// </summary>
|
||||
public static NewsRestriction? Strictest(IEnumerable<NewsRestriction> restrictions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(restrictions);
|
||||
return restrictions.OrderByDescending(r => r.Until).ThenByDescending(r => r.Rank).ThenByDescending(r => r.Story.Importance).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Whether a serious event is in force: then the stop of a position is not widened for any reason.</summary>
|
||||
public static NewsRestriction? KeepsStop(IEnumerable<NewsRestriction> restrictions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(restrictions);
|
||||
return restrictions.Where(r => r.Code == NewsReasons.Severe).OrderByDescending(r => r.Until).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Stories that would restrict if confirmed, read from one untrusted source only: the third row.</summary>
|
||||
public static bool Unconfirmed(StoryFact story)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(story);
|
||||
return story.Matters && !story.Confirmed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The state of 10.2 point 6 at <paramref name="now"/>. The tone is the mean score of the stories, each weighed
|
||||
/// by its age with a half-life of half the window (12 hours on one day, 36 on three), so the latest count most and
|
||||
/// a story leaves the window gently. Stories without a score (Italian, no classifier) are not in the tone. The
|
||||
/// norm is the stories per day of the 29 days before the last one; null until the first of those days has passed.
|
||||
/// </summary>
|
||||
public static InstrumentNewsState State(IReadOnlyCollection<StoryFact> stories, DateTimeOffset now, NewsRuleSwitches switches, DateTimeOffset? firstStoryEver = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stories);
|
||||
ArgumentNullException.ThrowIfNull(switches);
|
||||
var known = stories.Where(s => s.FirstSeenAt <= now).ToList();
|
||||
var day = TimeSpan.FromDays(1);
|
||||
var oneDay = known.Count(s => s.Start > now - day && s.Start <= now);
|
||||
var normFrom = now - NormWindow;
|
||||
double? normal = null;
|
||||
if (firstStoryEver is { } first && first <= now - (2 * day))
|
||||
{
|
||||
var from = first > normFrom ? first : normFrom;
|
||||
var days = (now - day - from).TotalDays;
|
||||
normal = days >= 1 ? known.Count(s => s.Start > from && s.Start <= now - day) / days : null;
|
||||
}
|
||||
|
||||
return new InstrumentNewsState(Tone(known, now, day), Tone(known, now, 3 * day), oneDay, normal, Strictest(Active(known, now, switches)));
|
||||
}
|
||||
|
||||
private static double? Tone(IEnumerable<StoryFact> stories, DateTimeOffset now, TimeSpan window)
|
||||
{
|
||||
var halfLife = window.TotalHours / 2;
|
||||
double sum = 0, weights = 0;
|
||||
foreach (var story in stories)
|
||||
{
|
||||
var age = (now - story.Start).TotalHours;
|
||||
if (story.Score is not { } score || age < 0 || age >= window.TotalHours)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var weight = Math.Pow(0.5, age / halfLife);
|
||||
sum += weight * score;
|
||||
weights += weight;
|
||||
}
|
||||
|
||||
return weights > 0 ? Math.Round(sum / weights, 4) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The switches of the rows of 10.5 (SPEC 10.5: "ogni riga della tabella si può spegnere dalle impostazioni").</summary>
|
||||
public static class NewsRuleSettings
|
||||
{
|
||||
public const string On = "on";
|
||||
public const string Off = "off";
|
||||
|
||||
public static readonly SettingDefinition Severe = Switch("news.rule.severe", "Evento grave: niente nuovi acquisti per 72 ore");
|
||||
public static readonly SettingDefinition Negative = Switch("news.rule.negative", "Notizia negativa: niente acquisti né aumenti per 24 ore");
|
||||
public static readonly SettingDefinition Unconfirmed = Switch("news.rule.unconfirmed", "Voce da una sola fonte: annotata e ricontrollata dopo 2 ore");
|
||||
public static readonly SettingDefinition Earnings = Switch("calendar.rule.earnings", "Trimestrale in arrivo: niente mean reversion su quel titolo");
|
||||
public static readonly SettingDefinition Macro = Switch("calendar.rule.macro", "Dato macro importante: niente ingressi da 30 minuti prima a 30 dopo");
|
||||
|
||||
public static readonly IReadOnlyList<SettingDefinition> All = [Severe, Negative, Unconfirmed, Earnings, Macro];
|
||||
|
||||
public static async Task<NewsRuleSwitches> LoadAsync(SettingsStore? settings, CancellationToken cancellationToken)
|
||||
{
|
||||
if (settings is null)
|
||||
{
|
||||
return NewsRuleSwitches.AllOn;
|
||||
}
|
||||
|
||||
async Task<bool> IsOn(SettingDefinition d) => (await settings.GetAsync(d.Key, cancellationToken).ConfigureAwait(false)).Value != Off;
|
||||
return new NewsRuleSwitches(await IsOn(Severe).ConfigureAwait(false), await IsOn(Negative).ConfigureAwait(false), await IsOn(Unconfirmed).ConfigureAwait(false),
|
||||
await IsOn(Earnings).ConfigureAwait(false), await IsOn(Macro).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private static SettingDefinition Switch(string key, string label) => new(key, label, On, [On, Off]);
|
||||
}
|
||||
@@ -486,7 +486,7 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
|
||||
/// </summary>
|
||||
private bool EarningsAhead(StrategyContext context, string symbol)
|
||||
{
|
||||
if (context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry)
|
||||
if (!context.EarningsEntries || context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -269,6 +269,12 @@ public sealed class StrategyContext(
|
||||
/// <summary>A restriction from the news on the instrument (SPEC 10.5, Phase 7); null in a backtest.</summary>
|
||||
public Func<string, bool>? Restricted { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether coming earnings keep <c>equity_meanrev</c> out (SPEC 10.5, fourth row, which the user can switch off).
|
||||
/// The exit before the earnings of 8.3 is a rule of the strategy and stays.
|
||||
/// </summary>
|
||||
public bool EarningsEntries { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// The strategy's equity at each earlier close, up to and including this one: what the risk limits of SPEC 9.2
|
||||
/// measure losses and the fall from the high on.
|
||||
|
||||
@@ -23,6 +23,9 @@ public static class DecisionOutcomes
|
||||
public const string Passed = "passed";
|
||||
public const string Reduced = "reduced";
|
||||
public const string Refused = "refused";
|
||||
|
||||
/// <summary>Held back by a rule of SPEC 10.5 and tried again when it ends.</summary>
|
||||
public const string Postponed = "postponed";
|
||||
public const string Same = "same";
|
||||
public const string Different = "different";
|
||||
}
|
||||
|
||||
@@ -147,6 +147,17 @@ public static class DiaryText
|
||||
public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) =>
|
||||
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
|
||||
|
||||
/// <summary>A purchase a rule of SPEC 10.5 put off: it goes when the restriction ends.</summary>
|
||||
public static string EntryPostponed(string symbol, DateTimeOffset until, TimeZoneInfo zone, string reason, string motive) =>
|
||||
$"Ho rimandato l'acquisto di {Shown(symbol)} alle {TimeZoneInfo.ConvertTime(until, zone):HH:mm}. {reason} Motivo: {motive}.";
|
||||
|
||||
/// <summary>A purchase a rule of SPEC 10.5 left out: the restriction lasts past its deadline (SPEC 5.6).</summary>
|
||||
public static string EntryRestricted(string symbol, string reason, string motive) => $"Non compro {Shown(symbol)}. {reason} Motivo: {motive}.";
|
||||
|
||||
/// <summary>A stop the strategy wanted lower, kept where it was by a serious event (SPEC 10.5, first row).</summary>
|
||||
public static string StopKept(string symbol, decimal level, string currency, string motive) =>
|
||||
$"Lo stop di {Shown(symbol)} resta a {Level(level, currency)}: con un evento grave in corso non lo allargo. Motivo: {motive}.";
|
||||
|
||||
/// <summary>A missed job left out at the restart, with its reason (SPEC 5.6).</summary>
|
||||
public static string Skipped(string what, string reason) => $"Saltato: {what}. {reason}";
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.News;
|
||||
using Anubis.Risk;
|
||||
using Anubis.Strategies;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -47,6 +48,9 @@ public static class DecisionModes
|
||||
public const string NoData = "no_data";
|
||||
}
|
||||
|
||||
/// <summary>The earnings dates a decision sees, and whether the fourth row of 10.5 is on (Impostazioni).</summary>
|
||||
public sealed record EarningsView(IReadOnlyDictionary<string, DateOnly> Next, bool BlockEntries);
|
||||
|
||||
/// <summary>The times of SPEC 5.5 and the limits of SPEC 5.6.</summary>
|
||||
public sealed record LiveEngineOptions
|
||||
{
|
||||
@@ -138,6 +142,18 @@ public sealed partial class LiveEngine : IDisposable
|
||||
/// <summary>Asks the data service for the bars a decision is waiting for (the history step). Called at most every few minutes.</summary>
|
||||
public Func<CancellationToken, Task>? WantData { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The rules of SPEC 10.5 that stop a single purchase (news on the instrument, high-impact figures) and keep the
|
||||
/// stop of a position under a serious event. Null: nothing is held back.
|
||||
/// </summary>
|
||||
public IEntryGate? Gate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The earnings calendar of the stocks for a decision day (SPEC 10.5, fourth row; 8.3): null when the filter is
|
||||
/// off, because the Finnhub key is missing or its answers are old.
|
||||
/// </summary>
|
||||
public Func<DateOnly, CancellationToken, Task<EarningsView?>>? Earnings { get; init; }
|
||||
|
||||
/// <summary>The time zone of the diary's times: Italian time.</summary>
|
||||
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
|
||||
|
||||
@@ -477,6 +493,15 @@ public sealed partial class LiveEngine : IDisposable
|
||||
var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters);
|
||||
var data = loaded.Data;
|
||||
var options = StrategyPipeline.For(m.Strategy, data, new BacktestOptions());
|
||||
if (Earnings is not null && m.Strategy != StrategyNames.CryptoTrend && await Earnings(m.Day, cancellationToken).ConfigureAwait(false) is { } earnings)
|
||||
{
|
||||
options = options with
|
||||
{
|
||||
NextEarnings = symbol => earnings.Next.TryGetValue(symbol, out var date) ? date : null,
|
||||
EarningsEntries = earnings.BlockEntries,
|
||||
};
|
||||
}
|
||||
|
||||
DecisionRecord record;
|
||||
if (observation)
|
||||
{
|
||||
@@ -500,6 +525,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
plan = plan with { Working = await WorkingAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false) };
|
||||
}
|
||||
|
||||
plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false);
|
||||
var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false);
|
||||
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||
await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false);
|
||||
@@ -564,10 +590,67 @@ public sealed partial class LiveEngine : IDisposable
|
||||
DecisionSummary Summary, decimal Equity)
|
||||
{
|
||||
public IReadOnlySet<Guid> Working { get; init; } = new HashSet<Guid>();
|
||||
|
||||
/// <summary>Purchases a rule of 10.5 held back: put off to when it ends, or left out when that is past their deadline.</summary>
|
||||
public IReadOnlyList<(string Symbol, EntryHold Hold, bool Dropped)> Holds { get; init; } = [];
|
||||
|
||||
/// <summary>Stops the strategy wanted lower and a serious event kept where they were (10.5, first row).</summary>
|
||||
public IReadOnlyList<(string Symbol, decimal Level, EntryHold Hold)> KeptStops { get; init; } = [];
|
||||
}
|
||||
|
||||
private sealed record PlannedOrder(Guid InstrumentId, string Symbol, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, decimal? StopLevel, decimal? StopOffset,
|
||||
decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, bool Crypto);
|
||||
decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, bool Crypto)
|
||||
{
|
||||
/// <summary>The time the order was first due, when a restriction put it off.</summary>
|
||||
public DateTimeOffset? FirstDue { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules of 10.5 on what was planned: a purchase under a restriction waits for its end, within the limits of
|
||||
/// 5.6 (its deadline), or is left out; a stop is not lowered while a serious event lasts. The decision itself, and
|
||||
/// so the example of 11.2, keeps what the strategy proposed.
|
||||
/// </summary>
|
||||
private async Task<PlanResult> GateAsync(Moment m, string mode, PlanResult plan, BacktestDataset data, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Gate is null)
|
||||
{
|
||||
return plan;
|
||||
}
|
||||
|
||||
var orders = new List<PlannedOrder>();
|
||||
var holds = new List<(string, EntryHold, bool)>();
|
||||
foreach (var order in plan.Orders)
|
||||
{
|
||||
if (order.Side != OrderSide.Buy || data[order.Symbol]?.Spec is not { } spec || await Gate.HoldAsync(spec, m.Now, cancellationToken).ConfigureAwait(false) is not { } hold)
|
||||
{
|
||||
orders.Add(order);
|
||||
continue;
|
||||
}
|
||||
|
||||
var dropped = order.ValidUntil is { } until && hold.Until > until;
|
||||
holds.Add((order.Symbol, hold, dropped));
|
||||
if (!dropped)
|
||||
{
|
||||
orders.Add(hold.Until > order.Due ? order with { Due = hold.Until, FirstDue = order.Due } : order);
|
||||
}
|
||||
}
|
||||
|
||||
var stops = new List<(string, decimal, decimal)>();
|
||||
var kept = new List<(string, decimal, EntryHold)>();
|
||||
foreach (var (symbol, from, to) in plan.Stops)
|
||||
{
|
||||
if (mode != DecisionModes.Observation && from > 0m && to < from && data[symbol]?.Spec is { } spec
|
||||
&& await Gate.KeepStopAsync(spec, m.Now, cancellationToken).ConfigureAwait(false) is { } keep)
|
||||
{
|
||||
kept.Add((symbol, from, keep));
|
||||
continue;
|
||||
}
|
||||
|
||||
stops.Add((symbol, from, to));
|
||||
}
|
||||
|
||||
return plan with { Orders = orders, Stops = stops, Holds = holds, KeptStops = kept };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The intents become orders as the backtest plans them (BacktestEngine.Plan): target quantity from the weight and
|
||||
@@ -721,6 +804,27 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (symbol, hold, dropped) in plan.Holds)
|
||||
{
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Correctives,
|
||||
dropped ? DecisionOutcomes.Refused : DecisionOutcomes.Postponed, [hold.Code], new Dictionary<string, object?> { ["until"] = hold.Until, ["motive"] = hold.Motive }, now),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (!observation)
|
||||
{
|
||||
var text = dropped ? DiaryText.EntryRestricted(symbol, ReasonCatalog.Text(hold.Code), hold.Motive)
|
||||
: DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, text, new { decision = decisionId, symbol }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (symbol, level, hold) in plan.KeptStops)
|
||||
{
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Correctives, DecisionOutcomes.Refused, [hold.Code],
|
||||
new Dictionary<string, object?> { ["stop"] = level, ["motive"] = hold.Motive }, now), cancellationToken).ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.News, hold.Code, DiaryText.StopKept(symbol, level, currency, hold.Motive), new { decision = decisionId, symbol },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (symbol, reason) in plan.Notes)
|
||||
{
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Order, DecisionOutcomes.Refused, [reason], null, now),
|
||||
@@ -764,11 +868,11 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
var id = Ids.NewId(_clock);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " +
|
||||
"VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, @stop, @off, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken,
|
||||
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, first_due_at, status, created_at, updated_at) " +
|
||||
"VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, @stop, @off, @ref, @r, @due, @until, @first, @st, @now, @now)", cancellationToken,
|
||||
("id", id), ("d", decisionId), ("s", m.Strategy), ("a", account), ("i", order.InstrumentId), ("side", Wire.Text(order.Side)), ("p", Wire.Text(order.Purpose)),
|
||||
("q", DbValues.Money(order.Quantity)), ("all", order.ExitAll), ("stop", order.StopLevel), ("off", order.StopOffset), ("ref", order.Reference), ("r", order.Reason),
|
||||
("due", order.Due), ("until", order.ValidUntil), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false);
|
||||
("due", order.Due), ("until", order.ValidUntil), ("first", order.FirstDue), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false);
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [],
|
||||
new Dictionary<string, object?> { ["side"] = Wire.Text(order.Side), ["quantity"] = order.Quantity, ["equity"] = plan.Equity, ["close"] = order.Reference, ["planned"] = id },
|
||||
now), cancellationToken).ConfigureAwait(false);
|
||||
@@ -810,6 +914,9 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent;
|
||||
|
||||
// The news rows go with the news in the diary, the calendar ones with the decisions.
|
||||
private static string DiaryKind(string code) => code is NewsReasons.Severe or NewsReasons.Negative ? DiaryKinds.News : DiaryKinds.Decisions;
|
||||
|
||||
private sealed record ProposedIntent(string Symbol, decimal? Weight, decimal? Stop);
|
||||
|
||||
// ---- One-step comparison (SPEC 12.3) ------------------------------------------------------------------------
|
||||
@@ -846,7 +953,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
// ---- Releasing planned orders -------------------------------------------------------------------------------
|
||||
|
||||
private sealed record Planned(Guid Id, Guid DecisionId, string Strategy, Guid AccountId, Guid InstrumentId, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll,
|
||||
decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil);
|
||||
decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, DateTimeOffset? FirstDue = null);
|
||||
|
||||
/// <summary>
|
||||
/// The planned orders whose time has come go to the order manager, sales first (SPEC 5.5). An entry past its
|
||||
@@ -856,12 +963,8 @@ public sealed partial class LiveEngine : IDisposable
|
||||
/// </summary>
|
||||
private async Task ReleaseAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var due = await _db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until " +
|
||||
"FROM planned_orders WHERE status = @p AND due_at <= @now ORDER BY due_at, id",
|
||||
r => new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")),
|
||||
r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"),
|
||||
r.MomentOrNull("valid_until")), ("p", PlannedStates.Pending), ("now", now)), cancellationToken).ConfigureAwait(false);
|
||||
var due = await _db.ReadAsync(s => s.QueryAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.status = @p AND p.due_at <= @now ORDER BY p.due_at, p.id",
|
||||
ReadPlanned, ("p", PlannedStates.Pending), ("now", now)), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var order in due.OrderBy(o => o.Side == OrderSide.Buy).ThenBy(o => o.Due))
|
||||
{
|
||||
try
|
||||
@@ -912,6 +1015,12 @@ public sealed partial class LiveEngine : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (order.Side == OrderSide.Buy && Gate is not null && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold)
|
||||
{
|
||||
await HoldAsync(order, instrument.Symbol, hold, now, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var quantity = order.Quantity;
|
||||
if (order.Side == OrderSide.Sell)
|
||||
{
|
||||
@@ -926,7 +1035,8 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
var late = now - order.Due > Options.Late;
|
||||
// An entry put off by a restriction is a recovered one: its price is checked against the decision's (SPEC 5.6).
|
||||
var late = now - (order.FirstDue ?? order.Due) > Options.Late;
|
||||
decimal? stopLevel = order.StopLevel;
|
||||
if (order.Side == OrderSide.Buy)
|
||||
{
|
||||
@@ -959,7 +1069,8 @@ public sealed partial class LiveEngine : IDisposable
|
||||
StopLevel = stopLevel,
|
||||
StartAggressive = aggressive,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null;
|
||||
// A purchase put off by a restriction already said why in the diary; only one late because the bot was off is "recovered".
|
||||
var recovered = late && order.FirstDue is null ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null;
|
||||
await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -997,11 +1108,11 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, " +
|
||||
"reason, due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, @reason, " +
|
||||
"@due, @until, @st, NULL, NULL, @now, @now)", cancellationToken,
|
||||
"reason, due_at, valid_until, first_due_at, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, " +
|
||||
"@reason, @due, @until, @first, @st, NULL, NULL, @now, @now)", cancellationToken,
|
||||
("id", Ids.NewId(_clock)), ("d", order.DecisionId), ("s", order.Strategy), ("a", order.AccountId), ("i", order.InstrumentId), ("side", Wire.Text(order.Side)),
|
||||
("p", Wire.Text(order.Purpose)), ("q", Math.Max(0m, order.Quantity - filled)), ("x", order.ExitAll), ("sl", order.StopLevel), ("so", order.StopOffset),
|
||||
("r", order.Reference), ("reason", order.Reason), ("due", sale ? now : order.Due), ("until", order.ValidUntil), ("st", PlannedStates.Pending), ("now", now))
|
||||
("r", order.Reference), ("reason", order.Reason), ("due", sale ? now : order.Due), ("until", order.ValidUntil), ("first", sale ? null : order.FirstDue), ("st", PlannedStates.Pending), ("now", now))
|
||||
.ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, LiveReasons.Restart, DiaryText.RestartedOrder(sale, symbol), new { planned = order.Id, execution },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
@@ -1015,12 +1126,12 @@ public sealed partial class LiveEngine : IDisposable
|
||||
private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked);
|
||||
|
||||
private const string PlannedColumns =
|
||||
"p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until";
|
||||
"p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until, p.first_due_at";
|
||||
|
||||
private static Planned ReadPlanned(DbRow r) =>
|
||||
new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")),
|
||||
r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"),
|
||||
r.MomentOrNull("valid_until"));
|
||||
r.MomentOrNull("valid_until"), r.MomentOrNull("first_due_at"));
|
||||
|
||||
/// <summary>
|
||||
/// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between
|
||||
@@ -1049,6 +1160,32 @@ public sealed partial class LiveEngine : IDisposable
|
||||
return unlinked is null ? (Interrupted?)null : new Interrupted(unlinked, info.Filled, true);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>A purchase a rule of 10.5 stops now: put off to its end when that is within its deadline, otherwise left out.</summary>
|
||||
private async Task HoldAsync(Planned order, string symbol, EntryHold hold, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
if (order.ValidUntil is { } until && hold.Until > until)
|
||||
{
|
||||
await CloseAsync(order, PlannedStates.Expired, hold.Code, null, DiaryText.EntryRestricted(symbol, ReasonCatalog.Text(hold.Code), hold.Motive), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await _db.WriteAsync(async s =>
|
||||
{
|
||||
var moved = await s.ExecuteAsync("UPDATE planned_orders SET due_at = @u, first_due_at = @f, updated_at = @now WHERE id = @id AND status = @p", cancellationToken,
|
||||
("u", hold.Until), ("f", order.FirstDue ?? order.Due), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false);
|
||||
if (moved == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, symbol, DecisionStages.Order, DecisionOutcomes.Postponed,
|
||||
[hold.Code], new Dictionary<string, object?> { ["planned"] = order.Id, ["until"] = hold.Until, ["motive"] = hold.Motive }, now), cancellationToken).ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive),
|
||||
new { planned = order.Id }, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string OrderWords(Planned order, string symbol) =>
|
||||
(order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol);
|
||||
|
||||
|
||||
@@ -36,6 +36,13 @@ public static class ReasonCatalog
|
||||
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
|
||||
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
|
||||
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
|
||||
// News and calendar (SPEC 10.5).
|
||||
["news_severe"] = "Un evento grave e negativo su questo strumento: niente nuovi acquisti per 72 ore.",
|
||||
["news_negative"] = "Una notizia negativa importante su questo strumento: niente acquisti né aumenti per 24 ore.",
|
||||
["news_unconfirmed"] = "Una voce da una sola fonte non affidabile: nessuna azione, la ricontrollo dopo 2 ore.",
|
||||
["news_rechecked"] = "La voce non è stata confermata da un'altra fonte: nessuna azione.",
|
||||
["news_keep_stop"] = "Con un evento grave in corso lo stop non si allarga.",
|
||||
["calendar_earnings"] = "Trimestrale in arrivo: niente mean reversion su questo titolo fino alla pubblicazione.",
|
||||
// Risk.
|
||||
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
|
||||
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
|
||||
|
||||
@@ -187,6 +187,8 @@ public sealed partial class TradingService : IDisposable
|
||||
Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger)
|
||||
{
|
||||
WantData = market is null ? null : _ => market.WakeWorker(),
|
||||
Gate = new News.EntryGate(db, clock, settings),
|
||||
Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct),
|
||||
Ready = () => _started,
|
||||
AccountReady = AccountReady,
|
||||
};
|
||||
@@ -194,6 +196,18 @@ public sealed partial class TradingService : IDisposable
|
||||
|
||||
private volatile bool _started;
|
||||
|
||||
// The earnings of SPEC 10.5 (fourth row) and 8.3: only while the Finnhub calendar is fresh, as the strategies expect.
|
||||
private async Task<EarningsView?> EarningsAsync(MarketDataService market, DateOnly day, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await market.References.EarningsFilterActiveAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var dates = await new News.NewsDesk(_db, _clock, _settings).EarningsAsync(day, cancellationToken).ConfigureAwait(false);
|
||||
return new EarningsView(dates, (await News.NewsRuleSettings.LoadAsync(_settings, cancellationToken).ConfigureAwait(false)).Earnings);
|
||||
}
|
||||
|
||||
/// <summary>The startup steps of SPEC 9.4 are done and the loop runs.</summary>
|
||||
public bool IsStarted => _started;
|
||||
|
||||
|
||||
Reference in new issue
Block a user