diff --git a/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs b/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs
new file mode 100644
index 0000000..5752a7c
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Data/AuctionRecorder.cs
@@ -0,0 +1,419 @@
+using System.Collections.Concurrent;
+using System.Text.Encodings.Web;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using BidooBidBot.Bidoo;
+using BidooBidBot.Engine;
+using BidooBidBot.Ml;
+using BidooBidBot.Settings;
+
+namespace BidooBidBot.Data;
+
+/// Le variabili di una decisione come si salvano in bot_decisions.state.
+public sealed class DecisionState
+{
+ public BidContext? Ctx { get; set; }
+ public double Price { get; set; }
+ public double Timer { get; set; }
+ public string? LastBidder { get; set; }
+ public int PingMs { get; set; }
+ public int BidsUsed { get; set; }
+ public int Resets { get; set; }
+ public int? Balance { get; set; }
+ public int? Paid { get; set; }
+ public int? Free { get; set; }
+ public string Mode { get; set; } = "";
+ public bool Live { get; set; }
+ public double? BuyNow { get; set; }
+ public double? Shipping { get; set; }
+ public double? ForecastClose { get; set; }
+ public double? ForecastP10 { get; set; }
+ public double? ForecastP90 { get; set; }
+}
+
+/// Una decisione da registrare.
+public sealed record DecisionRecord(
+ string Kind, string Action, double? PModel, double? PBandit, double? OwnBidFactor, double? PWin, double? Ev,
+ double? BidCost, double? Value, string Reason, string? ContextKey, string? Champion, string? ModelVersion,
+ string? AltAction, int LeadMs, bool Shadow, DecisionState State);
+
+/// Il riepilogo di un'asta alla chiusura.
+public sealed record CloseSummary(
+ DateTime EndedAtUtc, string Outcome, string FinalStatus, bool WonByMe, string Winner, double FinalPrice,
+ double? BuyNow, double? Shipping, double? MarketValue, double BidCost, double TransactionFee, int MyBids, double MyBidsCost,
+ int? WinnerBidsPaid, int? WinnerBidsFree, int Resets, int DistinctBidders, int TotalObservedBids, double TopBidderShare,
+ bool ObservedFromStart, bool ObservedToEnd, double ObservedMinutes, DateTime FirstSeenUtc, DateTime? OpenedUtc,
+ double? AvgPing, double? P95Ping, double? P99Ping, long Polls, long PollErrors, int LeadMs, bool LeadManual,
+ int TimerExpired, int SuccessfulBids, int FailedBids, double PriceVelocityPerMinute, string PriceSeriesJson,
+ string BidsByUserJson, string ModeAtClose, string? Category);
+
+///
+/// Registra nel database ciò che succede a un'asta mentre la si segue (portato dal legacy):
+/// ogni puntata di chiunque con l'ora del server, ogni reset con la profondità del ciclo, ogni
+/// mia puntata con anticipo voluto ed effettivo, ogni decisione con le variabili, e alla fine
+/// il riepilogo. Le singole interrogazioni non si scrivono: tutto ciò che il modello impara
+/// sta già in puntate e reset. Nessuna scrittura tocca il disco sul thread che segue l'asta:
+/// tutto va nella coda.
+///
+/// Questi dati non esistono a posteriori: Bidoo non espone lo storico dei prezzi né i
+/// tempi delle puntate di un'asta conclusa. O li si raccoglie mentre va, o sono persi.
+///
+public sealed class AuctionRecorder
+{
+ private static readonly JsonSerializerOptions Json = new()
+ {
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+ };
+
+ private readonly WriteQueue? _queue;
+ private readonly Db? _db;
+ private readonly Func _settings;
+ private readonly Func _me;
+ private readonly ConcurrentDictionary _open = new(StringComparer.Ordinal);
+ private long _nextDecisionId;
+
+ ///
+ /// Senza coda ( null) non si scrive nulla: il simulatore segue le
+ /// sue aste senza toccare l'archivio vero.
+ ///
+ public AuctionRecorder(WriteQueue? queue, Db? db, Func settings, Func me)
+ {
+ _queue = queue;
+ _db = db;
+ _settings = settings;
+ _me = me;
+ }
+
+ public bool Enabled => _queue != null && _settings().RecordAuctions;
+ public int OpenCount => _open.Count;
+
+ /// Gli id delle decisioni si assegnano qui: la puntata li porta con sé senza aspettare il disco.
+ public async Task InitAsync()
+ {
+ if (_db == null) return;
+ _nextDecisionId = await _db.ScalarAsync("SELECT MAX(decision_id) FROM bot_decisions").ConfigureAwait(false) ?? 0;
+ }
+
+ public long NextDecisionId() => Interlocked.Increment(ref _nextDecisionId);
+
+ public AuctionRecording? For(string auctionId) => _open.TryGetValue(auctionId, out var r) ? r : null;
+
+ ///
+ /// Prepara la registrazione prima che il motore parta: riga dell'asta, e — se l'asta era
+ /// già seguita prima di un riavvio — le puntate già scritte, per non duplicarle. Un'asta
+ /// seguita a cavallo di un riavvio resta una storia sola.
+ ///
+ public async Task PrepareAsync(AuctionInfo auction)
+ {
+ if (!Enabled || string.IsNullOrEmpty(auction.Id)) return null;
+ if (_open.TryGetValue(auction.Id, out var existing)) return existing;
+
+ var rec = new AuctionRecording(this, auction.Id);
+ if (_db != null)
+ {
+ try
+ {
+ var known = await _db.QueryAsync("SELECT price_after, bid_type FROM bids WHERE auction_id = $1",
+ r => ((int)Math.Round(r.Dbl("price_after") * 100), r.Str("bid_type")), auction.Id).ConfigureAwait(false);
+ foreach (var (cents, type) in known) rec.Known[cents] = type;
+ }
+ catch { /* senza, al massimo si riscrive qualche puntata già vista */ }
+ }
+
+ WriteAuctionRow(auction);
+ return _open.GetOrAdd(auction.Id, rec);
+ }
+
+ private void WriteAuctionRow(AuctionInfo a)
+ {
+ var s = _settings();
+ var config = JsonSerializer.Serialize(new
+ {
+ mode = RunModes.ToKey(a.Mode), leadMs = a.LeadMs, leadIsManual = a.LeadIsManual, maxPrice = a.MaxPrice, maxBids = a.MaxBids,
+ adaptiveLead = s.AdaptiveLeadEnabled, leadMinMs = s.LeadMinMs, leadMaxMs = s.LeadMaxMs, learningEnabled = s.LearningEnabled,
+ live = s.LiveBiddingEnabled, origin = a.Origin
+ }, Json);
+
+ _queue!.EnqueueGroup(new (string, object?[])[]
+ {
+ ("INSERT INTO items(product_key, bidoo_product_id, title, image_url, retail_price_bidoo, shipping) VALUES($1, $2, $3, $4, $5, $6) " +
+ "ON CONFLICT(product_key) DO UPDATE SET title = CASE WHEN excluded.title <> '' THEN excluded.title ELSE items.title END, " +
+ " bidoo_product_id = COALESCE(excluded.bidoo_product_id, items.bidoo_product_id), image_url = COALESCE(excluded.image_url, items.image_url), " +
+ " retail_price_bidoo = COALESCE(excluded.retail_price_bidoo, items.retail_price_bidoo), shipping = COALESCE(excluded.shipping, items.shipping), updated_at = now()",
+ new object?[] { a.ProductKey, a.BidooProductId > 0 ? a.BidooProductId.ToString(System.Globalization.CultureInfo.InvariantCulture) : null,
+ a.Name, a.ImageUrl, a.BuyNowPrice, a.Shipping }),
+
+ ("INSERT INTO auctions(auction_id, item_id, product_key, name, url, status, me, app_version, added_at, first_seen_at, " +
+ " buy_now_price, shipping, market_value, has_win_limit, win_limit, configured_lead_ms, lead_is_manual, config) " +
+ "VALUES($1, (SELECT item_id FROM items WHERE product_key = $2), $2, $3, $4, 'open', $5, $6, $7, now(), $8, $9, " +
+ " (SELECT market_price_est FROM items WHERE product_key = $2), $10, $11, $12, $13, $14) " +
+ "ON CONFLICT(auction_id) DO UPDATE SET me = COALESCE(excluded.me, auctions.me), app_version = excluded.app_version, " +
+ " name = CASE WHEN excluded.name <> '' THEN excluded.name ELSE auctions.name END, " +
+ " buy_now_price = COALESCE(excluded.buy_now_price, auctions.buy_now_price), shipping = COALESCE(excluded.shipping, auctions.shipping), " +
+ " has_win_limit = excluded.has_win_limit OR auctions.has_win_limit, win_limit = COALESCE(excluded.win_limit, auctions.win_limit), " +
+ " configured_lead_ms = excluded.configured_lead_ms, lead_is_manual = excluded.lead_is_manual, config = excluded.config",
+ new object?[] { a.Id, a.ProductKey, a.Name, a.Url, _me(), AppInfo.Version, a.AddedAtUtc, a.BuyNowPrice, a.Shipping,
+ !string.IsNullOrEmpty(a.WinLimit), a.WinLimit, a.LeadMs, a.LeadIsManual, new Jsonb(config) })
+ });
+ }
+
+ /// Aggiorna nome, prodotto e prezzi dell'asta quando la pagina è stata letta.
+ public void UpdateProductInfo(AuctionInfo a)
+ {
+ if (!Enabled || !_open.ContainsKey(a.Id)) return;
+ WriteAuctionRow(a);
+ }
+
+ ///
+ /// Una decisione del motore, in Osserva come dal vivo: cosa avrebbe fatto o ha fatto, con
+ /// che stima e per quale motivo. Restituisce l'id, che la puntata porta con sé. L'esito si
+ /// scrive alla chiusura.
+ ///
+ public long RecordDecision(AuctionInfo a, AuctionState s, DecisionRecord d)
+ {
+ var id = NextDecisionId();
+ if (!Enabled) return id;
+
+ _queue!.Enqueue(
+ "INSERT INTO bot_decisions(decision_id, auction_id, ts, t, price, timer, kind, action, p_model, p_bandit, own_bid_factor, " +
+ " p_win, ev, bid_cost, value, reason_detail, state, context_key, champion, model_version, alt_action, lead_ms, shadow) " +
+ "VALUES($1, $2, now(), $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)",
+ id, a.Id, For(a.Id)?.Elapsed(), s.Price, Math.Round(s.Timer, 2), d.Kind, d.Action, d.PModel, d.PBandit, d.OwnBidFactor,
+ d.PWin, d.Ev, d.BidCost, d.Value, d.Reason, new Jsonb(JsonSerializer.Serialize(d.State, Json)), d.ContextKey, d.Champion,
+ d.ModelVersion, d.AltAction, d.LeadMs, d.Shadow);
+ return id;
+ }
+
+ /// La previsione dell'asta (all'aggancio e a ogni aggiornamento).
+ public void RecordForecast(AuctionInfo a, ForecastResult f, bool initial)
+ {
+ if (!Enabled || !_open.ContainsKey(a.Id)) return;
+ _queue!.Enqueue(
+ "INSERT INTO auction_forecasts(auction_id, ts, is_initial, price_at, forecast_close, forecast_close_p10, forecast_close_p90, " +
+ " forecast_winner_bids, forecast_minutes, p_win_if_enter, ev_if_enter, basis) VALUES($1, now(), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
+ a.Id, initial, f.PriceAt, f.Close, f.P10, f.P90, f.WinnerBids, f.MinutesLeft, f.PWinIfEnter, f.EvIfEnter,
+ new Jsonb(JsonSerializer.Serialize(new { text = f.Basis, samples = f.Samples }, Json)));
+ }
+
+ ///
+ /// L'asta è stata tolta prima della fine: la riga resta, marcata come interrotta (una serie
+ /// di prezzi che si ferma a metà sembrerebbe un'asta finita a quel prezzo).
+ ///
+ public void Abandon(string auctionId, string reason)
+ {
+ if (!_open.TryRemove(auctionId, out var rec) || !Enabled) return;
+ _queue!.Enqueue(
+ "UPDATE auctions SET status = CASE WHEN outcome IS NULL THEN 'abandoned' ELSE status END, abandon_reason = $2, " +
+ "closed_at = COALESCE(closed_at, now()), polls = $3 WHERE auction_id = $1",
+ auctionId, reason, rec.Polls);
+ }
+
+ ///
+ /// Chiude la registrazione con il riepilogo, poi calcola in SQL le risposte alle mie puntate
+ /// (la puntata a price + 0,02 risponde a quella che ha portato il prezzo a
+ /// price + 0,01), gli esiti delle decisioni e previsione ↔ realtà.
+ ///
+ public void Close(AuctionInfo a, CloseSummary c)
+ {
+ _open.TryRemove(a.Id, out _);
+ if (!Enabled) return;
+
+ var totalWinner = c.WinnerBidsPaid.HasValue || c.WinnerBidsFree.HasValue ? (c.WinnerBidsPaid ?? 0) + (c.WinnerBidsFree ?? 0) : (int?)null;
+
+ _queue!.EnqueueGroup(new (string, object?[])[]
+ {
+ ("UPDATE auctions SET status = 'closed', closed_at = now(), end_time = $2, outcome = $3, final_status = $4, won_by_me = $5, " +
+ " winner_user = $6, final_price = $7, buy_now_price = COALESCE($8, buy_now_price), shipping = COALESCE($9, shipping), " +
+ " market_value = COALESCE($10, market_value), bid_fee = $11, transaction_fee = $12, my_bids = $13, my_bids_cost = $14, " +
+ " winner_bids_paid = $15, winner_bids_free = $16, resets = $17, distinct_bidders = $18, total_observed_bids = $19, " +
+ " top_bidder_share = $20, observed_from_start = $21, observed_to_end = $22, observed_minutes = $23, first_seen_at = $24, " +
+ " opened_at = COALESCE($25, opened_at), avg_ping_ms = $26, p95_ping_ms = $27, p99_ping_ms = $28, polls = $29, poll_errors = $30, " +
+ " configured_lead_ms = $31, lead_is_manual = $32, timer_expired = $33, successful_bids = $34, failed_bids = $35, " +
+ " price_velocity_per_minute = $36, price_series = $37, bids_by_user = $38, mode_at_close = $39 WHERE auction_id = $1",
+ new object?[]
+ {
+ a.Id, c.EndedAtUtc, c.Outcome, c.FinalStatus, c.WonByMe, c.Winner, c.FinalPrice, c.BuyNow, c.Shipping, c.MarketValue,
+ Math.Round(c.BidCost, 4), c.TransactionFee, c.MyBids, Math.Round(c.MyBidsCost, 2), c.WinnerBidsPaid, c.WinnerBidsFree,
+ c.Resets, c.DistinctBidders, c.TotalObservedBids, Math.Round(c.TopBidderShare, 4), c.ObservedFromStart, c.ObservedToEnd,
+ Math.Round(c.ObservedMinutes, 2), c.FirstSeenUtc, c.OpenedUtc, c.AvgPing, c.P95Ping, c.P99Ping, c.Polls, c.PollErrors,
+ c.LeadMs, c.LeadManual, c.TimerExpired, c.SuccessfulBids, c.FailedBids, Math.Round(c.PriceVelocityPerMinute, 4),
+ new Jsonb(c.PriceSeriesJson), new Jsonb(c.BidsByUserJson), c.ModeAtClose
+ }),
+
+ ("INSERT INTO bidders(username, first_seen, last_seen, n_auctions, n_bids, n_auto, n_manual, win_count) " +
+ "SELECT username, MIN(created_at), MAX(created_at), 1, COUNT(*), SUM(CASE WHEN bid_type = 'Auto' THEN 1 ELSE 0 END), " +
+ " SUM(CASE WHEN bid_type = 'Manuale' THEN 1 ELSE 0 END), 0 FROM bids WHERE auction_id = $1 AND username <> '' GROUP BY username " +
+ "ON CONFLICT(username) DO UPDATE SET last_seen = excluded.last_seen, first_seen = COALESCE(bidders.first_seen, excluded.first_seen), " +
+ " n_auctions = bidders.n_auctions + 1, n_bids = bidders.n_bids + excluded.n_bids, n_auto = bidders.n_auto + excluded.n_auto, " +
+ " n_manual = bidders.n_manual + excluded.n_manual",
+ new object?[] { a.Id }),
+
+ ("UPDATE bidders SET win_count = win_count + 1 WHERE username = $1 AND $1 <> ''", new object?[] { c.Winner }),
+
+ ("UPDATE items SET retail_price_bidoo = COALESCE($2, retail_price_bidoo), shipping = COALESCE($3, shipping), updated_at = now() WHERE product_key = $1",
+ new object?[] { a.ProductKey, c.BuyNow, c.Shipping }),
+
+ ("UPDATE my_bids SET " +
+ " answered_by = (SELECT b.username FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1), " +
+ " answered_type = (SELECT b.bid_type FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1), " +
+ " answered_after_s = COALESCE(" +
+ " (SELECT b2.server_ts - b1.server_ts FROM bids b1, bids b2 WHERE b1.auction_id = my_bids.auction_id AND ABS(b1.price_after - (my_bids.price + 0.01)) < 0.005 AND b1.server_ts > 0 " +
+ " AND b2.auction_id = my_bids.auction_id AND ABS(b2.price_after - (my_bids.price + 0.02)) < 0.005 AND b2.server_ts > 0 LIMIT 1), " +
+ " (SELECT b.seen_t - my_bids.t FROM bids b WHERE b.auction_id = my_bids.auction_id AND ABS(b.price_after - (my_bids.price + 0.02)) < 0.005 LIMIT 1)), " +
+ " unanswered = (my_bids.price + 0.01 >= $2 - 0.005) " +
+ "WHERE auction_id = $1 AND success AND NOT manual",
+ new object?[] { a.Id, c.FinalPrice }),
+
+ // Esiti delle decisioni. Una puntata partita: prezzo dopo di lei price + 0,01; se il
+ // finale non l'ha superato, era la vincente. Shadow o NO-OP: il prezzo del momento.
+ ("UPDATE bot_decisions SET outcome = CASE WHEN price + 0.01 >= $2 - 0.005 THEN 'won' ELSE 'answered' END " +
+ "WHERE auction_id = $1 AND executed AND action = 'BID' AND (outcome IS NULL OR outcome = 'sent')",
+ new object?[] { a.Id, c.FinalPrice }),
+
+ ("UPDATE bot_decisions SET outcome = CASE WHEN price >= $2 - 0.005 THEN (CASE WHEN action = 'BID' THEN 'would_win' ELSE 'missed' END) " +
+ " ELSE (CASE WHEN action = 'BID' THEN 'would_be_answered' ELSE 'right_skip' END) END " +
+ "WHERE auction_id = $1 AND NOT executed AND outcome IS NULL",
+ new object?[] { a.Id, c.FinalPrice }),
+
+ ("UPDATE bot_decisions SET has_my_bid = true WHERE auction_id = $1 AND $2", new object?[] { a.Id, c.MyBids > 0 }),
+
+ ("UPDATE auction_forecasts SET actual_close = $2, actual_winner_bids = $3, actual_minutes = $4, " +
+ " error_close = $2 - forecast_close, in_interval = ($2 >= forecast_close_p10 - 0.005 AND $2 <= forecast_close_p90 + 0.005) " +
+ "WHERE auction_id = $1",
+ new object?[] { a.Id, c.FinalPrice, totalWinner, c.OpenedUtc is { } o ? Math.Round((c.EndedAtUtc - o).TotalMinutes, 2) : (double?)null })
+ });
+ }
+
+ internal WriteQueue Queue => _queue!;
+}
+
+/// La registrazione aperta di un'asta.
+public sealed class AuctionRecording
+{
+ private readonly AuctionRecorder _owner;
+ private readonly DateTime _startedAt = DateTime.UtcNow;
+ private readonly object _sync = new();
+
+ private double _cycleMinTimer = double.MaxValue;
+ private double _cycleStartedElapsed = -1;
+ private double _completedCycleMinTimer = double.NaN;
+ private double _completedCycleSeconds = double.NaN;
+ private double _lastPollPrice = double.NaN;
+
+ public string AuctionId { get; }
+ public long Polls;
+
+ /// Puntate già scritte (centesimi → tipo): evitano i doppioni.
+ internal Dictionary Known { get; } = new();
+
+ internal AuctionRecording(AuctionRecorder owner, string auctionId)
+ {
+ _owner = owner;
+ AuctionId = auctionId;
+ }
+
+ public double Elapsed() => Math.Round((DateTime.UtcNow - _startedAt).TotalSeconds, 3);
+
+ /// Un'interrogazione: non si scrive nulla, si segue il ciclo in corso (fin dove scende il cronometro).
+ public void Poll(AuctionState state)
+ {
+ Interlocked.Increment(ref Polls);
+ lock (_sync)
+ {
+ var now = Elapsed();
+ if (!double.IsNaN(_lastPollPrice) && state.Price > _lastPollPrice)
+ {
+ _completedCycleMinTimer = _cycleMinTimer == double.MaxValue ? double.NaN : _cycleMinTimer;
+ _completedCycleSeconds = _cycleStartedElapsed >= 0 ? now - _cycleStartedElapsed : double.NaN;
+ _cycleMinTimer = double.MaxValue;
+ _cycleStartedElapsed = now;
+ }
+ else if (_cycleStartedElapsed < 0) _cycleStartedElapsed = now;
+
+ _lastPollPrice = state.Price;
+ if (state.Timer > 0 && state.Timer < _cycleMinTimer) _cycleMinTimer = state.Timer;
+ }
+ }
+
+ ///
+ /// Una puntata vista nello storico (di chiunque, anche mia). Il tipo dichiarato dal server
+ /// vince su quello ignoto di una riga già scritta; una puntata ricostruita da un cambio di
+ /// prezzo non sovrascrive mai un tipo vero.
+ ///
+ public void ForeignBid(BidHistoryEntry entry, int rttMs = 0)
+ {
+ var cents = entry.PriceCents;
+ double? timerBefore;
+ bool insert, update;
+ lock (_sync)
+ {
+ timerBefore = _cycleMinTimer == double.MaxValue ? null : Math.Round(_cycleMinTimer, 2);
+ if (!Known.TryGetValue(cents, out var known))
+ {
+ Known[cents] = entry.BidType;
+ insert = true;
+ update = false;
+ }
+ else
+ {
+ insert = false;
+ update = known.Length == 0 && entry.BidType.Length > 0;
+ if (update) Known[cents] = entry.BidType;
+ }
+ }
+
+ if (!_owner.Enabled) return;
+ if (insert)
+ {
+ _owner.Queue.EnqueueBid(
+ "INSERT INTO bids(auction_id, username, price_after, bid_type, is_mine, server_ts, seen_t, local_ts, timer_before, rtt_ms) " +
+ "VALUES($1, $2, $3, $4, $5, $6, $7, now(), $8, $9)",
+ AuctionId, entry.Username, (double)entry.Price, entry.BidType, entry.IsMyBid,
+ entry.Timestamp > 0 ? entry.Timestamp : null, Elapsed(), timerBefore, rttMs > 0 ? rttMs : null);
+ }
+ else if (update)
+ {
+ _owner.Queue.EnqueueBid(
+ "UPDATE bids SET bid_type = $3, server_ts = COALESCE(NULLIF($4::bigint, 0), server_ts), is_mine = is_mine OR $5, " +
+ " username = CASE WHEN $6 <> '' THEN $6 ELSE username END WHERE auction_id = $1 AND price_after = $2",
+ AuctionId, (double)entry.Price, entry.BidType, entry.Timestamp, entry.IsMyBid, entry.Username);
+ }
+ }
+
+ /// Una mia puntata, con tutto ciò che serve a giudicarla.
+ public void MyBid(double price, int plannedLeadMs, double actualLeadMs, double waitErrorMs, int pingMs, int rttMs, bool success,
+ string? error, int? bidsUsed, int? remaining, int? remainingPaid, int? remainingFree, long? decisionId, double? pWin, string? kind, bool manual)
+ {
+ if (!_owner.Enabled) return;
+ _owner.Queue.Enqueue(
+ "INSERT INTO my_bids(auction_id, t, local_ts, price, planned_lead_ms, actual_lead_ms, wait_error_ms, ping_ms, rtt_ms, success, error, " +
+ " bids_used, remaining_bids, remaining_paid, remaining_free, decision_id, p_win, kind, manual) " +
+ "VALUES($1, $2, now(), $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)",
+ AuctionId, Elapsed(), price, plannedLeadMs, Math.Round(actualLeadMs, 2), Math.Round(waitErrorMs, 3), pingMs, rttMs, success, error,
+ bidsUsed, remaining, remainingPaid, remainingFree, decisionId, pWin, kind, manual);
+
+ if (decisionId is { } id)
+ _owner.Queue.Enqueue("UPDATE bot_decisions SET executed = true, outcome = $2 WHERE decision_id = $1",
+ id, success ? "sent" : "failed:" + (error ?? "?"));
+ }
+
+ /// Il timer è stato azzerato da una puntata: si chiude un ciclo.
+ public void Reset(int resetCount, double price, string? bidder)
+ {
+ double? minTimer, cycleSeconds;
+ lock (_sync)
+ {
+ minTimer = double.IsNaN(_completedCycleMinTimer) ? null : Math.Round(_completedCycleMinTimer, 2);
+ cycleSeconds = double.IsNaN(_completedCycleSeconds) ? null : Math.Round(_completedCycleSeconds, 2);
+ _completedCycleMinTimer = double.NaN;
+ _completedCycleSeconds = double.NaN;
+ }
+
+ if (!_owner.Enabled) return;
+ _owner.Queue.EnqueueBid(
+ "INSERT INTO resets(auction_id, t, local_ts, reset_count, price, bidder, min_timer, cycle_seconds) VALUES($1, $2, now(), $3, $4, $5, $6, $7)",
+ AuctionId, Elapsed(), resetCount, price, bidder, minTimer, cycleSeconds);
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Ml/AuctionForecast.cs b/Mimante/src/BidooBidBot/Ml/AuctionForecast.cs
new file mode 100644
index 0000000..6ec11c7
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Ml/AuctionForecast.cs
@@ -0,0 +1,208 @@
+using System.Globalization;
+using System.Text.Json;
+
+namespace BidooBidBot.Ml;
+
+/// La previsione di una singola asta in un istante.
+/// Prezzo di chiusura atteso (mediana condizionata al prezzo attuale).
+/// 10° percentile.
+/// 90° percentile: l'intervallo 10-90 dovrebbe contenere la chiusura 8 volte su 10.
+/// Puntate attese del vincitore (mediana del prodotto).
+/// Durata attesa da adesso, dal ritmo recente delle puntate.
+/// Se entrassi ora e puntassi a ogni ciclo utile: probabilità stimata di vincere.
+/// Costo atteso delle puntate fino alla chiusura attesa.
+/// Valore atteso di entrare ora (servono valore e probabilità).
+/// Su cosa poggia, in italiano: quante aste, quale fascia.
+public sealed record ForecastResult(
+ double Close, double P10, double P90, double? WinnerBids, double? MinutesLeft,
+ double? PWinIfEnter, double? CostIfEnter, double? EvIfEnter, string Basis, int Samples, DateTime AtUtc, double PriceAt);
+
+/// Ciò che la previsione sa dell'asta in questo istante.
+public readonly record struct ForecastInput(
+ string ProductKey, double Price, double? Value, int HourBand, double? BidsPerMinute,
+ double? PerBidP, double BidCost, double TransactionFee, double Shipping, int DistinctBidders, int MaxBids);
+
+///
+/// La previsione della singola asta (specifica §7.7, nuovo). Tiene per ogni prodotto le
+/// ultime chiusure (prezzo, fascia oraria, puntate del vincitore, durata) e, per tutte le
+/// aste, il rapporto chiusura/valore come ripiego. A ogni aggiornamento stima:
+///
+///
+/// - chiusura attesa e intervallo 10°-90° percentile fra le chiusure passate che hanno
+/// superato il prezzo attuale (condizionata: un'asta a 4 € non chiude a 2 €), della stessa
+/// fascia oraria se ce ne sono almeno 10;
+/// - puntate attese del vincitore e durata attesa (dal ritmo delle ultime puntate);
+/// - «se entrassi ora»: puntando una volta ogni tanti cicli quanti sono i puntatori
+/// distinti, la probabilità che una delle mie resti l'ultima è 1 − (1 − p)^k, con p
+/// la P per puntata del modello. È una stima grossolana, detta come tale: non decide nulla,
+/// il modello resta l'unico decisore.
+///
+/// Alla chiusura la previsione si confronta con la realtà e le distribuzioni imparano l'asta
+/// nuova, da sole.
+///
+public sealed class AuctionForecast
+{
+ public const int PerProductSamples = 200;
+ public const int GlobalSamples = 3000;
+ public const int MinSamples = 5;
+
+ public sealed record Sample(double Close, int Band, int? WinnerBids, double? Minutes, double? Ratio);
+
+ private readonly object _sync = new();
+ private Dictionary> _byProduct = new(StringComparer.Ordinal);
+ private List _global = new();
+
+ public long Observed { get; private set; }
+
+ public void Observe(string productKey, double close, double? value, int band, int? winnerBids, double? minutes)
+ {
+ if (close <= 0) return;
+ var ratio = value is > 0 ? close / value.Value : (double?)null;
+ var s = new Sample(Math.Round(close, 2), band, winnerBids, minutes is { } m ? Math.Round(m, 1) : null, ratio is { } r ? Math.Round(r, 5) : null);
+
+ lock (_sync)
+ {
+ Observed++;
+ if (!string.IsNullOrEmpty(productKey))
+ {
+ if (!_byProduct.TryGetValue(productKey, out var list)) _byProduct[productKey] = list = new List();
+ list.Add(s);
+ if (list.Count > PerProductSamples) list.RemoveRange(0, list.Count - PerProductSamples);
+ }
+ if (s.Ratio != null)
+ {
+ _global.Add(s);
+ if (_global.Count > GlobalSamples) _global.RemoveRange(0, _global.Count - GlobalSamples);
+ }
+ }
+ }
+
+ public int SamplesFor(string productKey)
+ {
+ lock (_sync) return _byProduct.TryGetValue(productKey, out var l) ? l.Count : 0;
+ }
+
+ public ForecastResult? Forecast(ForecastInput input)
+ {
+ List closes;
+ string basis;
+ List productSamples;
+
+ lock (_sync)
+ {
+ productSamples = _byProduct.TryGetValue(input.ProductKey, out var l) ? l.ToList() : new List();
+ var sameBand = productSamples.Where(s => s.Band == input.HourBand).ToList();
+ var pool = sameBand.Count >= 10 ? sameBand : productSamples;
+ closes = pool.Select(s => s.Close).Where(c => c >= input.Price).OrderBy(c => c).ToList();
+ basis = pool == sameBand
+ ? $"{pool.Count} aste del prodotto alle {BidFeatures.HourBandLabel(input.HourBand)}"
+ : $"{pool.Count} aste del prodotto";
+
+ if (closes.Count < MinSamples && input.Value is > 0 && _global.Count >= 20)
+ {
+ closes = _global.Where(s => s.Ratio != null).Select(s => s.Ratio!.Value * input.Value.Value)
+ .Where(c => c >= input.Price).OrderBy(c => c).ToList();
+ basis = $"{_global.Count} aste di tutti i prodotti, in rapporto al valore";
+ }
+ }
+
+ if (closes.Count < MinSamples) return null;
+
+ var close = Quantile(closes, 0.5);
+ var p10 = Quantile(closes, 0.1);
+ var p90 = Quantile(closes, 0.9);
+
+ var winnerBids = productSamples.Where(s => s.WinnerBids is > 0).Select(s => (double)s.WinnerBids!.Value).OrderBy(x => x).ToList();
+ double? expectedWinnerBids = winnerBids.Count >= 3 ? Quantile(winnerBids, 0.5) : null;
+
+ var remainingBids = Math.Max(0, (close - input.Price) * 100);
+ double? minutesLeft = input.BidsPerMinute is > 0.01 ? remainingBids / input.BidsPerMinute.Value : null;
+
+ double? pWin = null, cost = null, ev = null;
+ if (input.PerBidP is { } p && p > 0)
+ {
+ var k = Math.Max(1.0, remainingBids / Math.Max(1, input.DistinctBidders));
+ if (input.MaxBids > 0) k = Math.Min(k, input.MaxBids);
+ pWin = 1 - Math.Pow(1 - Math.Clamp(p, 0, 1), k);
+ cost = k * input.BidCost;
+ if (input.Value is > 0)
+ ev = pWin * (input.Value.Value - close - input.TransactionFee - input.Shipping) - cost;
+ }
+
+ return new ForecastResult(Math.Round(close, 2), Math.Round(p10, 2), Math.Round(p90, 2), expectedWinnerBids,
+ minutesLeft, pWin, cost, ev, basis, closes.Count, DateTime.UtcNow, input.Price);
+ }
+
+ public static double Quantile(IReadOnlyList sorted, double q)
+ {
+ if (sorted.Count == 0) return 0;
+ var pos = (sorted.Count - 1) * Math.Clamp(q, 0, 1);
+ var lo = (int)Math.Floor(pos);
+ var hi = (int)Math.Ceiling(pos);
+ return lo == hi ? sorted[lo] : sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
+ }
+
+ // ── Persistenza (documento ml/forecast) ──────────────────────────────
+
+ private sealed class Snapshot
+ {
+ public long Observed { get; set; }
+ public Dictionary> Products { get; set; } = new();
+ public List Global { get; set; } = new();
+ }
+
+ public string ToJson()
+ {
+ lock (_sync)
+ return JsonSerializer.Serialize(new Snapshot { Observed = Observed, Products = _byProduct, Global = _global });
+ }
+
+ public static AuctionForecast FromJson(string? json)
+ {
+ var f = new AuctionForecast();
+ if (string.IsNullOrEmpty(json)) return f;
+ try
+ {
+ var s = JsonSerializer.Deserialize(json);
+ if (s == null) return f;
+ f._byProduct = new Dictionary>(s.Products, StringComparer.Ordinal);
+ f._global = s.Global;
+ f.Observed = s.Observed;
+ }
+ catch (JsonException) { /* si riparte da vuoto */ }
+ return f;
+ }
+
+ /// La previsione come testo breve, per il registro dell'asta.
+ public static string Describe(ForecastResult f)
+ {
+ var it = CultureInfo.GetCultureInfo("it-IT");
+ return $"chiusura attesa {f.Close.ToString("0.00", it)} EUR ({f.P10.ToString("0.00", it)}-{f.P90.ToString("0.00", it)}), su {f.Basis}";
+ }
+}
+
+/// Previsione ↔ realtà, per le metriche dell'allenamento (errore mediano, copertura).
+public static class ForecastErrors
+{
+ public readonly record struct Row(double Forecast, double P10, double P90, double Actual, double? ForecastBids, int? ActualBids);
+
+ public readonly record struct Summary(int Auctions, double? MedianAbsError, double? MedianAbsErrorPct, double? SignedMedianPct, double? Coverage, double? MedianBidsError);
+
+ public static Summary Summarize(IReadOnlyList rows)
+ {
+ if (rows.Count == 0) return new Summary(0, null, null, null, null, null);
+ var abs = rows.Select(r => Math.Abs(r.Actual - r.Forecast)).OrderBy(x => x).ToList();
+ var pct = rows.Where(r => r.Actual > 0).Select(r => Math.Abs(r.Actual - r.Forecast) / r.Actual).OrderBy(x => x).ToList();
+ var signed = rows.Where(r => r.Actual > 0).Select(r => (r.Forecast - r.Actual) / r.Actual).OrderBy(x => x).ToList();
+ var inside = rows.Count(r => r.Actual >= r.P10 - 0.005 && r.Actual <= r.P90 + 0.005);
+ var bids = rows.Where(r => r.ForecastBids is > 0 && r.ActualBids is > 0)
+ .Select(r => Math.Abs(r.ActualBids!.Value - r.ForecastBids!.Value)).OrderBy(x => x).ToList();
+
+ return new Summary(rows.Count,
+ AuctionForecast.Quantile(abs, 0.5),
+ pct.Count > 0 ? AuctionForecast.Quantile(pct, 0.5) : null,
+ signed.Count > 0 ? AuctionForecast.Quantile(signed, 0.5) : null,
+ (double)inside / rows.Count,
+ bids.Count > 0 ? AuctionForecast.Quantile(bids, 0.5) : null);
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Ml/AuctionProfileStats.cs b/Mimante/src/BidooBidBot/Ml/AuctionProfileStats.cs
new file mode 100644
index 0000000..98f6723
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Ml/AuctionProfileStats.cs
@@ -0,0 +1,193 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.Json;
+
+namespace BidooBidBot.Ml;
+
+///
+/// Cosa aspettarsi da un'asta prima che cominci: puntate del vincitore e prezzo di
+/// chiusura in rapporto al valore, per prodotto, fascia oraria e tipo di giorno.
+///
+/// Il problema dei cassetti vuoti. Prodotto × fascia oraria × feriale/festivo
+/// fa centinaia di combinazioni, e molte hanno tre aste o nessuna. Una media su tre
+/// aste non è una stima, è un aneddoto. Per questo ogni stima è un restringimento:
+/// si parte dalla media globale, la si corregge verso quella del prodotto quanto più il
+/// prodotto ha esempi, e poi verso quella della combinazione esatta quanto più ne ha
+/// lei. Con dieci esempi il cassetto pesa metà; con cento quasi tutto; con uno quasi
+/// niente. È lo stimatore di Bayes empirico, e non serve nessuna libreria.
+///
+/// Si aggiorna a ogni asta chiusa con la formula di Welford, senza tenere gli
+/// esempi: media e varianza corrono, i dati no.
+///
+public sealed class AuctionProfileStats
+{
+ /// Esempi oltre i quali un cassetto pesa più del livello sopra.
+ public const double Shrink = 10.0;
+
+ private sealed class Cell
+ {
+ public long N { get; set; }
+ public double MeanBids { get; set; }
+ public double M2Bids { get; set; }
+ public long NBids { get; set; }
+ public double MeanRatio { get; set; }
+ public double M2Ratio { get; set; }
+ public long NRatio { get; set; }
+ }
+
+ private readonly Dictionary _cells = new(StringComparer.Ordinal);
+ private readonly object _sync = new();
+
+ public long AuctionsObserved { get; private set; }
+
+ /// Stima per una combinazione, con quanti esempi la sorreggono davvero.
+ public readonly record struct Estimate(double WinnerBids, double CloseRatio, long ExactSupport, long ProductSupport);
+
+ ///
+ /// Registra un'asta chiusa. Le puntate del vincitore possono mancare (dato non
+ /// attendibile o non registrato): in quel caso alimentano solo il prezzo.
+ ///
+ public void Observe(string? productKey, DateTime closedAtLocal, int? winnerBids, double? closeRatio)
+ {
+ var keys = KeysFor(productKey, closedAtLocal);
+
+ lock (_sync)
+ {
+ AuctionsObserved++;
+
+ foreach (var k in keys)
+ {
+ if (!_cells.TryGetValue(k, out var c)) _cells[k] = c = new Cell();
+ c.N++;
+
+ if (winnerBids is { } b && b > 0)
+ {
+ c.NBids++;
+ var d = b - c.MeanBids;
+ c.MeanBids += d / c.NBids;
+ c.M2Bids += d * (b - c.MeanBids);
+ }
+
+ if (closeRatio is { } r && r > 0)
+ {
+ c.NRatio++;
+ var d = r - c.MeanRatio;
+ c.MeanRatio += d / c.NRatio;
+ c.M2Ratio += d * (r - c.MeanRatio);
+ }
+ }
+ }
+ }
+
+ /// Cosa aspettarsi da un'asta di questo prodotto che chiude a quest'ora.
+ public Estimate? Expect(string? productKey, DateTime whenLocal)
+ {
+ var keys = KeysFor(productKey, whenLocal); // [globale, prodotto, esatta]
+
+ lock (_sync)
+ {
+ if (!_cells.TryGetValue(keys[0], out var global) || global.N == 0) return null;
+
+ _cells.TryGetValue(keys[1], out var product);
+ _cells.TryGetValue(keys[2], out var exact);
+
+ var bids = Shrunk(global.MeanBids, global.NBids, product?.MeanBids, product?.NBids ?? 0, exact?.MeanBids, exact?.NBids ?? 0);
+ var ratio = Shrunk(global.MeanRatio, global.NRatio, product?.MeanRatio, product?.NRatio ?? 0, exact?.MeanRatio, exact?.NRatio ?? 0);
+
+ return new Estimate(bids, ratio, exact?.N ?? 0, product?.N ?? 0);
+ }
+ }
+
+ ///
+ /// Globale → prodotto → esatta, ogni livello pesato dai propri esempi.
+ ///
+ private static double Shrunk(double g, long ng, double? p, long np, double? e, long ne)
+ {
+ var stima = g;
+ if (p is { } pv && np > 0) stima = (np * pv + Shrink * stima) / (np + Shrink);
+ if (e is { } ev && ne > 0) stima = (ne * ev + Shrink * stima) / (ne + Shrink);
+ return stima;
+ }
+
+ private static string[] KeysFor(string? productKey, DateTime when)
+ {
+ var prod = (productKey ?? "").Trim().ToLowerInvariant();
+ var band = BidFeatures.HourBand(when.Hour);
+ var day = BidFeatures.IsWeekend(when.DayOfWeek) ? "fest" : "fer";
+ return new[] { "g", "p:" + prod, "p:" + prod + "|h" + band + "|" + day };
+ }
+
+ /// Una riga del profilo, leggibile: per mostrarlo.
+ public readonly record struct Row(string Product, int HourBand, bool Weekend, long Auctions, double WinnerBids, double CloseRatio);
+
+ ///
+ /// Le combinazioni esatte con almeno un'asta, dalla più numerosa. Solo le esatte:
+ /// le righe di prodotto e quella globale sono medie delle esatte, e mostrarle
+ /// insieme confonderebbe.
+ ///
+ public IReadOnlyList Rows(int max = 200)
+ {
+ var list = new List();
+ lock (_sync)
+ {
+ foreach (var kv in _cells)
+ {
+ // chiave esatta: "p:{prodotto}|h{fascia}|{fer|fest}"
+ var k = kv.Key;
+ if (!k.StartsWith("p:", StringComparison.Ordinal)) continue;
+ var h = k.LastIndexOf("|h", StringComparison.Ordinal);
+ if (h < 0) continue;
+
+ var product = k.Substring(2, h - 2);
+ var rest = k[(h + 2)..]; // "{fascia}|{fer|fest}"
+ var bar = rest.IndexOf('|');
+ if (bar < 0 || !int.TryParse(rest[..bar], out var band)) continue;
+ var weekend = rest[(bar + 1)..] == "fest";
+
+ var c = kv.Value;
+ list.Add(new Row(product, band, weekend, c.N,
+ c.NBids > 0 ? c.MeanBids : double.NaN,
+ c.NRatio > 0 ? c.MeanRatio : double.NaN));
+ }
+ }
+ return list.OrderByDescending(r => r.Auctions).Take(max).ToList();
+ }
+
+ // ── Persistenza ──────────────────────────────────────────────────
+
+ private sealed class Snapshot
+ {
+ public int Version { get; set; } = 1;
+ public long AuctionsObserved { get; set; }
+ public Dictionary Cells { get; set; } = new();
+ }
+
+ public string ToJson()
+ {
+ lock (_sync)
+ {
+ return JsonSerializer.Serialize(new Snapshot
+ {
+ AuctionsObserved = AuctionsObserved,
+ Cells = new Dictionary(_cells)
+ });
+ }
+ }
+
+ public static AuctionProfileStats FromJson(string json)
+ {
+ var s = new AuctionProfileStats();
+ try
+ {
+ var snap = JsonSerializer.Deserialize(json);
+ if (snap?.Cells != null)
+ {
+ foreach (var kv in snap.Cells) s._cells[kv.Key] = kv.Value;
+ s.AuctionsObserved = snap.AuctionsObserved;
+ }
+ }
+ catch (JsonException) { /* si riparte da vuoto */ }
+ return s;
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Ml/BidFeatures.cs b/Mimante/src/BidooBidBot/Ml/BidFeatures.cs
new file mode 100644
index 0000000..b9d4e52
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Ml/BidFeatures.cs
@@ -0,0 +1,229 @@
+namespace BidooBidBot.Ml;
+
+///
+/// Lo stato di un'asta nell'istante di una puntata, ridotto a ciò che serve per prevedere se
+/// quella puntata resterà senza risposta (portato dal legacy). Si salva così com'è in
+/// bot_decisions.state: il CSV dei dati del modello ricostruisce il vettore da qui.
+///
+/// Quanto è durato il ciclo che questa puntata chiude. Negativo = ignoto.
+/// Quota di autopuntate fra le ultime dieci (0-1). Negativo = ignoto.
+/// Puntatori distinti fra le ultime venti.
+/// Prezzo sul valore del prodotto. Null = valore ignoto.
+/// Ora locale della puntata.
+/// Giorno della settimana.
+/// Ora locale in cui l'asta è stata agganciata.
+/// La puntata è dell'autopuntata del sito.
+/// Autopuntate di fila prima di questa. Negativo = nessuna manuale in vista.
+/// Prezzo in centesimi: le puntate fatte da tutti.
+/// Chi punta è lo stesso di due puntate fa: la firma del duello.
+/// Chiave normalizzata del prodotto.
+/// Fra gli ultimi dieci cicli, quanti hanno raggiunto gli 8 s.
+/// Prezzo sulla chiusura tipica del prodotto a quest'ora.
+public readonly record struct BidContext(
+ double CycleSeconds,
+ double AutoShareRecent,
+ int DistinctBiddersRecent,
+ double? PriceRatio,
+ int Hour,
+ DayOfWeek Day,
+ int OpenHour,
+ bool IsAutoBid,
+ int CyclesSinceManual,
+ int AuctionDepthCents,
+ bool SameBidderAsTwoAgo,
+ string ProductKey,
+ int DeepCyclesRecent = 0,
+ double? PriceVsTypicalClose = null);
+
+///
+/// Da al vettore del modello (portato dal legacy, Version = 2).
+///
+/// Quasi tutto a fasce: un ciclo di 9 s non è «tre volte» uno di 3, e a fasce ogni
+/// fascia impara il suo peso restando leggibile. Il prodotto in 32 cassetti con un hash
+/// stabile. I nomi delle variabili sono anche le intestazioni del CSV dei dati del modello.
+///
+public static class BidFeatures
+{
+ /// Cambia ogni volta che si aggiunge, toglie o ridefinisce una fascia: l'archivio si ristudia.
+ public const int Version = 2;
+
+ private const int GapBuckets = 6;
+ private const int BiddersBuckets = 5;
+ private const int RatioBuckets = 6;
+ private const int HourBands = 6;
+ private const int DayTypes = 2;
+ private const int BidTypes = 2;
+ private const int SinceManualBuckets = 4;
+ private const int DepthBuckets = 4;
+ public const int ProductBuckets = 32;
+ private const int DeepBuckets = 4;
+ private const int TypicalBuckets = 6;
+
+ public const int Size =
+ GapBuckets + 2 + BiddersBuckets + RatioBuckets + HourBands + DayTypes + BidTypes + SinceManualBuckets +
+ DepthBuckets + 1 + HourBands + ProductBuckets + DeepBuckets + TypicalBuckets;
+
+ /// Nomi delle variabili nell'ordine del vettore.
+ public static readonly string[] Names = BuildNames();
+
+ public static double[] Build(in BidContext c)
+ {
+ var x = new double[Size];
+ var o = 0;
+
+ if (c.CycleSeconds >= 0) x[o + GapBucket(c.CycleSeconds)] = 1;
+ o += GapBuckets;
+
+ if (c.AutoShareRecent >= 0) x[o] = Math.Clamp(c.AutoShareRecent, 0, 1);
+ else x[o + 1] = 1;
+ o += 2;
+
+ x[o + BiddersBucket(c.DistinctBiddersRecent)] = 1; o += BiddersBuckets;
+ x[o + RatioBucket(c.PriceRatio)] = 1; o += RatioBuckets;
+ x[o + HourBand(c.Hour)] = 1; o += HourBands;
+ x[o + (IsWeekend(c.Day) ? 1 : 0)] = 1; o += DayTypes;
+ x[o + (c.IsAutoBid ? 1 : 0)] = 1; o += BidTypes;
+ x[o + SinceManualBucket(c.CyclesSinceManual)] = 1; o += SinceManualBuckets;
+ x[o + DepthBucket(c.AuctionDepthCents)] = 1; o += DepthBuckets;
+ if (c.SameBidderAsTwoAgo) x[o] = 1;
+ o += 1;
+ x[o + HourBand(c.OpenHour)] = 1; o += HourBands;
+ x[o + ProductBucket(c.ProductKey)] = 1; o += ProductBuckets;
+ x[o + DeepBucket(c.DeepCyclesRecent)] = 1; o += DeepBuckets;
+ x[o + TypicalBucket(c.PriceVsTypicalClose)] = 1;
+ return x;
+ }
+
+ public static int GapBucket(double s) => s < 2 ? 0 : s < 4 ? 1 : s < 6 ? 2 : s < 8 ? 3 : s < 10 ? 4 : 5;
+ public static int BiddersBucket(int n) => n <= 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : n <= 5 ? 3 : 4;
+ public static int RatioBucket(double? r) => r is not { } v ? 5 : v < 0.02 ? 0 : v < 0.05 ? 1 : v < 0.10 ? 2 : v < 0.20 ? 3 : 4;
+ public static int DeepBucket(int n) => n <= 0 ? 0 : n <= 2 ? 1 : n <= 5 ? 2 : 3;
+ public static int TypicalBucket(double? r) => r is not { } v ? 5 : v < 0.5 ? 0 : v < 0.8 ? 1 : v < 1.1 ? 2 : v < 1.5 ? 3 : 4;
+
+ /// 0: 0-8 · 1: 9 · 2: 10-12 · 3: 13-17 · 4: 18-20 · 5: 21-23.
+ public static int HourBand(int h)
+ {
+ h = ((h % 24) + 24) % 24;
+ if (h <= 8) return 0;
+ if (h == 9) return 1;
+ if (h <= 12) return 2;
+ if (h <= 17) return 3;
+ if (h <= 20) return 4;
+ return 5;
+ }
+
+ public static string HourBandLabel(int band) => band switch
+ {
+ 0 => "0-8", 1 => "9", 2 => "10-12", 3 => "13-17", 4 => "18-20", _ => "21-23"
+ };
+
+ public static bool IsWeekend(DayOfWeek d) => d is DayOfWeek.Saturday or DayOfWeek.Sunday;
+ public static int SinceManualBucket(int n) => n < 0 ? 3 : n == 0 ? 0 : n <= 2 ? 1 : n <= 5 ? 2 : 3;
+ public static int DepthBucket(int cents) => cents < 50 ? 0 : cents < 150 ? 1 : cents < 400 ? 2 : 3;
+
+ /// Quanti degli ultimi dieci intervalli fra puntate hanno raggiunto gli 8 s (istanti dal più recente).
+ public static int CountDeepCycles(IReadOnlyList serverSecondsNewestFirst, int window = 10, double deepSeconds = 8)
+ {
+ var deep = 0;
+ var seen = 0;
+ for (var i = 0; i + 1 < serverSecondsNewestFirst.Count && seen < window; i++)
+ {
+ var newer = serverSecondsNewestFirst[i];
+ var older = serverSecondsNewestFirst[i + 1];
+ if (newer <= 0 || older <= 0) continue;
+ seen++;
+ if (newer - older >= deepSeconds) deep++;
+ }
+ return deep;
+ }
+
+ /// Hash stabile fra un avvio e l'altro (FNV-1a): string.GetHashCode cambia a ogni processo.
+ public static int ProductBucket(string? key)
+ {
+ if (string.IsNullOrWhiteSpace(key)) return 0;
+ uint h = 2166136261;
+ foreach (var ch in key.Trim().ToLowerInvariant())
+ {
+ h ^= ch;
+ h *= 16777619;
+ }
+ return (int)(h % ProductBuckets);
+ }
+
+ /// Il nome di una variabile in italiano semplice, per la scheda Apprendimento.
+ public static string Describe(string name) => name switch
+ {
+ "ciclo<2s" => "ultima puntata arrivata entro 2 secondi",
+ "ciclo<4s" => "ultima puntata arrivata fra 2 e 4 secondi",
+ "ciclo<6s" => "ultima puntata arrivata fra 4 e 6 secondi",
+ "ciclo<8s" => "ultima puntata arrivata fra 6 e 8 secondi",
+ "ciclo<10s" => "ultima puntata arrivata fra 8 e 10 secondi",
+ "ciclo>=10s" => "ciclo di 10 secondi o più",
+ "quotaAuto" => "quante autopuntate fra le ultime dieci",
+ "quotaAutoIgnota" => "tipo delle puntate recenti sconosciuto",
+ "puntatori=1" => "1 solo puntatore nelle ultime 20",
+ "puntatori=2" => "due puntatori recenti",
+ "puntatori=3" => "tre puntatori recenti",
+ "puntatori4-5" => "quattro o cinque puntatori recenti",
+ "puntatori>=6" => "sei o più puntatori recenti",
+ "prezzo<2%" => "prezzo sotto il 2% del valore",
+ "prezzo<5%" => "prezzo fra il 2% e il 5% del valore",
+ "prezzo<10%" => "prezzo fra il 5% e il 10% del valore",
+ "prezzo<20%" => "prezzo fra il 10% e il 20% del valore",
+ "prezzo>=20%" => "prezzo oltre il 20% del valore",
+ "valoreIgnoto" => "valore del prodotto sconosciuto",
+ "ora0-8" => "ora 0-8", "ora9" => "ora 9", "ora10-12" => "ora 10-12",
+ "ora13-17" => "ora 13-17", "ora18-20" => "ora 18-20", "ora21-23" => "ora 21-23",
+ "feriale" => "giorno feriale",
+ "festivo" => "sabato o domenica",
+ "manuale" => "puntata fatta a mano",
+ "automatica" => "puntata dell'autopuntata del sito",
+ "auto di fila=0" => "l'ultima puntata era manuale",
+ "auto di fila1-2" => "una o due autopuntate di fila",
+ "auto di fila3-5" => "da tre a cinque autopuntate di fila",
+ "auto di fila>=6" => "sei o più autopuntate di fila",
+ "profondita<50" => "meno di 50 puntate nell'asta",
+ "profondita<150" => "fra 50 e 150 puntate nell'asta",
+ "profondita<400" => "fra 150 e 400 puntate nell'asta",
+ "profondita>=400" => "oltre 400 puntate nell'asta",
+ "stessoPuntatoreDiDueFa" => "chi punta è lo stesso di due puntate fa",
+ "aggancio0-8" => "asta agganciata fra le 0 e le 8",
+ "aggancio9" => "asta agganciata alle 9",
+ "aggancio10-12" => "asta agganciata fra le 10 e le 12",
+ "aggancio13-17" => "asta agganciata fra le 13 e le 17",
+ "aggancio18-20" => "asta agganciata fra le 18 e le 20",
+ "aggancio21-23" => "asta agganciata fra le 21 e le 23",
+ "cicliLunghi=0" => "nessun ciclo lungo negli ultimi dieci",
+ "cicliLunghi1-2" => "uno o due cicli lunghi negli ultimi dieci",
+ "cicliLunghi3-5" => "da tre a cinque cicli lunghi negli ultimi dieci",
+ "cicliLunghi>=6" => "sei o più cicli lunghi: gli altri si stancano",
+ "tipico<50%" => "prezzo sotto la metà della chiusura tipica",
+ "tipico<80%" => "prezzo fra il 50% e l'80% della chiusura tipica",
+ "tipico<110%" => "prezzo intorno alla chiusura tipica",
+ "tipico<150%" => "prezzo fra il 110% e il 150% della chiusura tipica",
+ "tipico>=150%" => "prezzo ≥ 150% chiusura tipica",
+ "tipicoIgnoto" => "chiusura tipica del prodotto sconosciuta",
+ _ when name.StartsWith("prodotto#", StringComparison.Ordinal) => "gruppo di prodotti " + name[9..],
+ _ => name
+ };
+
+ private static string[] BuildNames()
+ {
+ var n = new List();
+ n.AddRange(new[] { "ciclo<2s", "ciclo<4s", "ciclo<6s", "ciclo<8s", "ciclo<10s", "ciclo>=10s" });
+ n.AddRange(new[] { "quotaAuto", "quotaAutoIgnota" });
+ n.AddRange(new[] { "puntatori=1", "puntatori=2", "puntatori=3", "puntatori4-5", "puntatori>=6" });
+ n.AddRange(new[] { "prezzo<2%", "prezzo<5%", "prezzo<10%", "prezzo<20%", "prezzo>=20%", "valoreIgnoto" });
+ n.AddRange(new[] { "ora0-8", "ora9", "ora10-12", "ora13-17", "ora18-20", "ora21-23" });
+ n.AddRange(new[] { "feriale", "festivo" });
+ n.AddRange(new[] { "manuale", "automatica" });
+ n.AddRange(new[] { "auto di fila=0", "auto di fila1-2", "auto di fila3-5", "auto di fila>=6" });
+ n.AddRange(new[] { "profondita<50", "profondita<150", "profondita<400", "profondita>=400" });
+ n.Add("stessoPuntatoreDiDueFa");
+ n.AddRange(new[] { "aggancio0-8", "aggancio9", "aggancio10-12", "aggancio13-17", "aggancio18-20", "aggancio21-23" });
+ for (var i = 0; i < ProductBuckets; i++) n.Add($"prodotto#{i}");
+ n.AddRange(new[] { "cicliLunghi=0", "cicliLunghi1-2", "cicliLunghi3-5", "cicliLunghi>=6" });
+ n.AddRange(new[] { "tipico<50%", "tipico<80%", "tipico<110%", "tipico<150%", "tipico>=150%", "tipicoIgnoto" });
+ return n.ToArray();
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Ml/LatencyModel.cs b/Mimante/src/BidooBidBot/Ml/LatencyModel.cs
new file mode 100644
index 0000000..b57360a
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Ml/LatencyModel.cs
@@ -0,0 +1,165 @@
+using System.Text.Json;
+using BidooBidBot.Data;
+using BidooBidBot.Settings;
+
+namespace BidooBidBot.Ml;
+
+///
+/// L'anticipo della puntata deciso dalla rete di questa sessione, dentro i paletti
+/// dell'utente (portato dal legacy).
+///
+/// La regola. anticipo = margine + p99(andata e ritorno): la coda, non la
+/// media, perché una puntata su cento che arriva tardi costa un'asta. Il margine parte da
+/// 300 ms (elaborazione del server più arrotondamento al secondo). Una puntata tardiva alza
+/// il margine subito e di molto (+150 ms); venti puntate puntuali di fila lo abbassano di
+/// 25 ms. Asimmetrico apposta: sbagliare per eccesso costa qualche puntata, per difetto
+/// costa l'asta. Un anticipo scritto a mano su un'asta vince sempre.
+///
+public sealed class LatencyModel
+{
+ public const string DocKey = "ml/latency";
+ private const int Window = 300;
+
+ private readonly object _sync = new();
+ private readonly Queue _pings = new();
+ private readonly Queue _roundTrips = new();
+ private readonly IDocumentStore? _docs;
+ private int _marginMs = 300;
+ private int _bidsSinceLastLate;
+ private int _lateBids;
+ private int _bidsTotal;
+ private DateTime _lastSave = DateTime.MinValue;
+
+ public LatencyModel(IDocumentStore? docs)
+ {
+ _docs = docs;
+ Load();
+ }
+
+ public void NotePing(int ms)
+ {
+ if (ms <= 0 || ms > 10_000) return;
+ lock (_sync)
+ {
+ _pings.Enqueue(ms);
+ while (_pings.Count > Window) _pings.Dequeue();
+ }
+ }
+
+ /// Una puntata inviata: quanto ci ha messo e se è arrivata tardi.
+ public void NoteBid(int roundTripMs, bool late)
+ {
+ lock (_sync)
+ {
+ if (roundTripMs is > 0 and < 10_000)
+ {
+ _roundTrips.Enqueue(roundTripMs);
+ while (_roundTrips.Count > Window) _roundTrips.Dequeue();
+ }
+ _bidsTotal++;
+ if (late)
+ {
+ _lateBids++;
+ _bidsSinceLastLate = 0;
+ _marginMs = Math.Min(2000, _marginMs + 150);
+ }
+ else
+ {
+ _bidsSinceLastLate++;
+ if (_bidsSinceLastLate % 20 == 0) _marginMs = Math.Max(150, _marginMs - 25);
+ }
+ }
+ Save(force: late);
+ }
+
+ /// L'anticipo consigliato adesso, dentro i paletti delle impostazioni.
+ public int RecommendedLeadMs(AppSettings settings)
+ {
+ var min = Math.Max(100, settings.LeadMinMs);
+ var max = Math.Max(min, settings.LeadMaxMs);
+ lock (_sync)
+ {
+ var tail = _roundTrips.Count >= 10 ? Percentile(_roundTrips, 0.99)
+ : _pings.Count >= 10 ? Percentile(_pings, 0.99)
+ : -1;
+ if (tail < 0) return Math.Clamp(settings.DefaultBidBeforeDeadlineMs, min, max);
+ return Math.Clamp(_marginMs + tail, min, max);
+ }
+ }
+
+ public readonly record struct Numbers(int Samples, int P50, int P99, int MarginMs, int LateBids, int Bids);
+
+ public Numbers Snapshot()
+ {
+ lock (_sync)
+ {
+ var src = _roundTrips.Count >= 10 ? _roundTrips : _pings;
+ return new Numbers(src.Count, src.Count > 0 ? Percentile(src, 0.5) : 0, src.Count > 0 ? Percentile(src, 0.99) : 0,
+ _marginMs, _lateBids, _bidsTotal);
+ }
+ }
+
+ private static int Percentile(Queue q, double p)
+ {
+ var a = q.ToArray();
+ Array.Sort(a);
+ var i = (int)Math.Ceiling(p * a.Length) - 1;
+ return a[Math.Clamp(i, 0, a.Length - 1)];
+ }
+
+ private sealed class Snap
+ {
+ public int MarginMs { get; set; } = 300;
+ public int LateBids { get; set; }
+ public int Bids { get; set; }
+ public int[] RoundTrips { get; set; } = Array.Empty();
+ }
+
+ private void Load()
+ {
+ var json = _docs?.Get(DocKey);
+ if (string.IsNullOrEmpty(json)) return;
+ try
+ {
+ var s = JsonSerializer.Deserialize(json);
+ if (s == null) return;
+ lock (_sync)
+ {
+ _marginMs = Math.Clamp(s.MarginMs, 150, 2000);
+ _lateBids = s.LateBids;
+ _bidsTotal = s.Bids;
+ foreach (var r in s.RoundTrips.TakeLast(Window)) _roundTrips.Enqueue(r);
+ }
+ }
+ catch (JsonException) { /* si riparte dai predefiniti */ }
+ }
+
+ /// Si salva a ogni puntata tardiva e al massimo una volta al minuto altrimenti.
+ public void Save(bool force = false)
+ {
+ if (_docs == null) return;
+ string json;
+ lock (_sync)
+ {
+ if (!force && DateTime.UtcNow - _lastSave < TimeSpan.FromMinutes(1)) return;
+ _lastSave = DateTime.UtcNow;
+ json = JsonSerializer.Serialize(new Snap { MarginMs = _marginMs, LateBids = _lateBids, Bids = _bidsTotal, RoundTrips = _roundTrips.ToArray() });
+ }
+ _docs.Set(DocKey, json);
+ }
+
+ /// Dimentica le misure: si riparte dai predefiniti.
+ public void Forget()
+ {
+ lock (_sync)
+ {
+ _pings.Clear();
+ _roundTrips.Clear();
+ _marginMs = 300;
+ _bidsSinceLastLate = 0;
+ _lateBids = 0;
+ _bidsTotal = 0;
+ }
+ _docs?.Delete(DocKey);
+ }
+}
diff --git a/Mimante/src/BidooBidBot/Ml/LearningData.cs b/Mimante/src/BidooBidBot/Ml/LearningData.cs
new file mode 100644
index 0000000..200c7ac
--- /dev/null
+++ b/Mimante/src/BidooBidBot/Ml/LearningData.cs
@@ -0,0 +1,166 @@
+using BidooBidBot.Data;
+
+namespace BidooBidBot.Ml;
+
+/// Un'asta conclusa vista dal profilo e dalle previsioni.
+public sealed record ClosedAuctionRow(
+ string AuctionId, string ProductKey, DateTime EndUtc, double FinalPrice, double? BuyNow, double? MarketValue,
+ int? WinnerBidsPaid, int? WinnerBidsFree, DateTime? OpenedUtc, bool WonByMe, string Winner);
+
+///
+/// Ciò che l'apprendimento legge e scrive nell'archivio. Un'interfaccia perché i test lo
+/// provino senza PostgreSQL; in produzione è .
+///
+public interface ILearningData
+{
+ /// Aspetta che le scritture accodate siano sul disco (prima di leggere ciò che si è appena scritto).
+ Task FlushAsync();
+
+ Task> PendingAuctionIdsAsync();
+ Task PendingCountAsync();
+ Task> ClosedAuctionIdsAsync(int max);
+ Task LoadSessionAsync(string auctionId, string? me);
+ Task IsLearnedAsync(string auctionId);
+ void MarkLearned(string auctionId);
+ Task MarkAllUnlearnedAsync();
+
+ /// Le decisioni dal vivo eseguite con esito: (P prevista, esito). Per la correzione sulle mie puntate.
+ Task> OwnBidOutcomesAsync(string? auctionId);
+
+ /// (chiave del contesto, esito) delle decisioni di un'asta: per il bandit.
+ Task> DecisionOutcomesAsync(string auctionId);
+ Task> AuctionsWithDecisionOutcomesAsync();
+
+ Task> DecisionsForReasonAsync(string auctionId);
+ Task> MyBidsForReasonAsync(string auctionId);
+ void WriteLossReason(string auctionId, string reason);
+
+ Task> ClosedAuctionsAsync(int max);
+ Task> LossReasonSummaryAsync(int days);
+ Task> ShadowRowsAsync(int days, bool? shadow, double defaultBidCost);
+}
+
+public sealed class DbLearningData : ILearningData
+{
+ private readonly Db _db;
+ private readonly WriteQueue _queue;
+
+ public DbLearningData(Db db, WriteQueue queue)
+ {
+ _db = db;
+ _queue = queue;
+ }
+
+ public Task FlushAsync() => _queue.FlushAsync(TimeSpan.FromSeconds(30));
+
+ public Task> PendingAuctionIdsAsync() =>
+ _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL ORDER BY end_time DESC",
+ r => r.Str("auction_id"));
+
+ public async Task PendingCountAsync() =>
+ (int)(await _db.ScalarAsync("SELECT COUNT(*) FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL").ConfigureAwait(false));
+
+ public async Task> ClosedAuctionIdsAsync(int max)
+ {
+ var ids = await _db.QueryAsync("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL ORDER BY end_time", r => r.Str("auction_id")).ConfigureAwait(false);
+ return max > 0 && ids.Count > max ? ids.Skip(ids.Count - max).ToList() : ids;
+ }
+
+ public async Task LoadSessionAsync(string auctionId, string? me)
+ {
+ var a = await _db.QueryOneAsync(
+ "SELECT auction_id, product_key, buy_now_price, added_at, winner_user, final_price, outcome, me FROM auctions WHERE auction_id = $1",
+ r => new
+ {
+ Id = r.Str("auction_id"), Key = r.Str("product_key"), BuyNow = r.DblOrNull("buy_now_price"), Added = r.Date("added_at"),
+ Winner = r.Str("winner_user"), Final = r.Dbl("final_price"), Outcome = r.StrOrNull("outcome"), Me = r.StrOrNull("me")
+ }, auctionId).ConfigureAwait(false);
+ if (a == null) return null;
+
+ var bids = await _db.QueryAsync(
+ "SELECT username, price_after, bid_type, is_mine, server_ts, seen_t FROM bids WHERE auction_id = $1 ORDER BY COALESCE(server_ts, 0), price_after",
+ r => new TrainingReader.Bid(r.Dbl("seen_t"), r.Str("username"), r.LongOrNull("server_ts") ?? 0, r.Str("bid_type"), r.Bool("is_mine"), r.Dbl("price_after")),
+ auctionId).ConfigureAwait(false);
+
+ return TrainingReader.Finish(new TrainingReader.Session
+ {
+ AuctionId = a.Id,
+ ProductKey = a.Key,
+ BuyNowPrice = a.BuyNow,
+ AddedAtLocal = a.Added is { } d ? AppInfo.ToLocal(d) : DateTime.MinValue,
+ Bids = bids,
+ Winner = a.Winner,
+ FinalPrice = a.Final,
+ HasSummary = a.Outcome != null,
+ Me = a.Me ?? me ?? ""
+ });
+ }
+
+ public async Task IsLearnedAsync(string auctionId) =>
+ await _db.ScalarAsync("SELECT learned_at FROM auctions WHERE auction_id = $1", auctionId).ConfigureAwait(false) != null;
+
+ public void MarkLearned(string auctionId) =>
+ _queue.Enqueue("UPDATE auctions SET learned_at = now() WHERE auction_id = $1", auctionId);
+
+ public async Task MarkAllUnlearnedAsync()
+ {
+ await FlushAsync().ConfigureAwait(false);
+ await _db.ExecuteAsync("UPDATE auctions SET learned_at = NULL").ConfigureAwait(false);
+ }
+
+ public Task> OwnBidOutcomesAsync(string? auctionId) =>
+ _db.QueryAsync(
+ "SELECT p_win, outcome FROM bot_decisions WHERE NOT shadow AND executed AND p_win IS NOT NULL AND outcome IN ('won', 'answered')" +
+ (auctionId != null ? " AND auction_id = $1" : ""),
+ r => (r.Dbl("p_win"), r.Str("outcome")),
+ auctionId != null ? new object?[] { auctionId } : Array.Empty