M4-M5: registratore, rischio, prodotti, strategia e modello portati su PostgreSQL

Registratore delle aste con puntate senza doppioni anche a cavallo di un riavvio,
reset con la profondità del ciclo, decisioni con le variabili complete in jsonb e,
alla chiusura, risposte alle mie puntate, esiti delle decisioni e previsione contro
realtà calcolati in SQL. Gestore del rischio con HALT persistente e contabilità in
memoria; schede prodotto con stellina, statistiche e limiti consigliati (solo
consiglio). Il modello (logistica, rete sfidante, bandit, profilo, latenza, motivi
delle perdite, valutazione) è portato senza cambiarne la matematica, da statico a
istanza; nuova previsione dell'asta con intervallo 10-90. Strategia a tre passi:
rischio dal vivo, paletti dell'utente, modello con esplorazione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-09-26 17:23:49 +02:00
1 parent 630d6983b5
commit f64c9e11da
26 files changed
+5788

No files matched your search

@@ -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;
/// <summary>Le variabili di una decisione come si salvano in <c>bot_decisions.state</c>.</summary>
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; }
}
/// <summary>Una decisione da registrare.</summary>
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);
/// <summary>Il riepilogo di un'asta alla chiusura.</summary>
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);
/// <summary>
/// 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.
///
/// <para>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.</para>
/// </summary>
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<AppSettings> _settings;
private readonly Func<string?> _me;
private readonly ConcurrentDictionary<string, AuctionRecording> _open = new(StringComparer.Ordinal);
private long _nextDecisionId;
/// <summary>
/// Senza coda (<paramref name="queue"/> null) non si scrive nulla: il simulatore segue le
/// sue aste senza toccare l'archivio vero.
/// </summary>
public AuctionRecorder(WriteQueue? queue, Db? db, Func<AppSettings> settings, Func<string?> me)
{
_queue = queue;
_db = db;
_settings = settings;
_me = me;
}
public bool Enabled => _queue != null && _settings().RecordAuctions;
public int OpenCount => _open.Count;
/// <summary>Gli id delle decisioni si assegnano qui: la puntata li porta con sé senza aspettare il disco.</summary>
public async Task InitAsync()
{
if (_db == null) return;
_nextDecisionId = await _db.ScalarAsync<long?>("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;
/// <summary>
/// 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.
/// </summary>
public async Task<AuctionRecording?> 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) })
});
}
/// <summary>Aggiorna nome, prodotto e prezzi dell'asta quando la pagina è stata letta.</summary>
public void UpdateProductInfo(AuctionInfo a)
{
if (!Enabled || !_open.ContainsKey(a.Id)) return;
WriteAuctionRow(a);
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>La previsione dell'asta (all'aggancio e a ogni aggiornamento).</summary>
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)));
}
/// <summary>
/// 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).
/// </summary>
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);
}
/// <summary>
/// Chiude la registrazione con il riepilogo, poi calcola in SQL le risposte alle mie puntate
/// (la puntata a <c>price + 0,02</c> risponde a quella che ha portato il prezzo a
/// <c>price + 0,01</c>), gli esiti delle decisioni e previsione ↔ realtà.
/// </summary>
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!;
}
/// <summary>La registrazione aperta di un'asta.</summary>
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;
/// <summary>Puntate già scritte (centesimi → tipo): evitano i doppioni.</summary>
internal Dictionary<int, string> Known { get; } = new();
internal AuctionRecording(AuctionRecorder owner, string auctionId)
{
_owner = owner;
AuctionId = auctionId;
}
public double Elapsed() => Math.Round((DateTime.UtcNow - _startedAt).TotalSeconds, 3);
/// <summary>Un'interrogazione: non si scrive nulla, si segue il ciclo in corso (fin dove scende il cronometro).</summary>
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;
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>Una mia puntata, con tutto ciò che serve a giudicarla.</summary>
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 ?? "?"));
}
/// <summary>Il timer è stato azzerato da una puntata: si chiude un ciclo.</summary>
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);
}
}
@@ -0,0 +1,208 @@
using System.Globalization;
using System.Text.Json;
namespace BidooBidBot.Ml;
/// <summary>La previsione di una singola asta in un istante.</summary>
/// <param name="Close">Prezzo di chiusura atteso (mediana condizionata al prezzo attuale).</param>
/// <param name="P10">10° percentile.</param>
/// <param name="P90">90° percentile: l'intervallo 10-90 dovrebbe contenere la chiusura 8 volte su 10.</param>
/// <param name="WinnerBids">Puntate attese del vincitore (mediana del prodotto).</param>
/// <param name="MinutesLeft">Durata attesa da adesso, dal ritmo recente delle puntate.</param>
/// <param name="PWinIfEnter">Se entrassi ora e puntassi a ogni ciclo utile: probabilità stimata di vincere.</param>
/// <param name="CostIfEnter">Costo atteso delle puntate fino alla chiusura attesa.</param>
/// <param name="EvIfEnter">Valore atteso di entrare ora (servono valore e probabilità).</param>
/// <param name="Basis">Su cosa poggia, in italiano: quante aste, quale fascia.</param>
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);
/// <summary>Ciò che la previsione sa dell'asta in questo istante.</summary>
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);
/// <summary>
/// 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:
///
/// <list type="bullet">
/// <item>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;</item>
/// <item>puntate attese del vincitore e durata attesa (dal ritmo delle ultime puntate);</item>
/// <item>«se entrassi ora»: puntando una volta ogni tanti cicli quanti sono i puntatori
/// distinti, la probabilità che una delle mie resti l'ultima è <c>1 − (1 − p)^k</c>, con p
/// la P per puntata del modello. È una stima grossolana, detta come tale: non decide nulla,
/// il modello resta l'unico decisore.</item>
/// </list>
/// Alla chiusura la previsione si confronta con la realtà e le distribuzioni imparano l'asta
/// nuova, da sole.
/// </summary>
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<string, List<Sample>> _byProduct = new(StringComparer.Ordinal);
private List<Sample> _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<Sample>();
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<double> closes;
string basis;
List<Sample> productSamples;
lock (_sync)
{
productSamples = _byProduct.TryGetValue(input.ProductKey, out var l) ? l.ToList() : new List<Sample>();
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<double> 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<string, List<Sample>> Products { get; set; } = new();
public List<Sample> 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<Snapshot>(json);
if (s == null) return f;
f._byProduct = new Dictionary<string, List<Sample>>(s.Products, StringComparer.Ordinal);
f._global = s.Global;
f.Observed = s.Observed;
}
catch (JsonException) { /* si riparte da vuoto */ }
return f;
}
/// <summary>La previsione come testo breve, per il registro dell'asta.</summary>
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}";
}
}
/// <summary>Previsione ↔ realtà, per le metriche dell'allenamento (errore mediano, copertura).</summary>
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<Row> 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);
}
}
@@ -0,0 +1,193 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace BidooBidBot.Ml;
/// <summary>
/// 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.
///
/// <para><b>Il problema dei cassetti vuoti.</b> 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 <i>restringimento</i>:
/// 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.</para>
///
/// <para>Si aggiorna a ogni asta chiusa con la formula di Welford, senza tenere gli
/// esempi: media e varianza corrono, i dati no.</para>
/// </summary>
public sealed class AuctionProfileStats
{
/// <summary>Esempi oltre i quali un cassetto pesa più del livello sopra.</summary>
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<string, Cell> _cells = new(StringComparer.Ordinal);
private readonly object _sync = new();
public long AuctionsObserved { get; private set; }
/// <summary>Stima per una combinazione, con quanti esempi la sorreggono davvero.</summary>
public readonly record struct Estimate(double WinnerBids, double CloseRatio, long ExactSupport, long ProductSupport);
/// <summary>
/// Registra un'asta chiusa. Le puntate del vincitore possono mancare (dato non
/// attendibile o non registrato): in quel caso alimentano solo il prezzo.
/// </summary>
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);
}
}
}
}
/// <summary>Cosa aspettarsi da un'asta di questo prodotto che chiude a quest'ora.</summary>
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);
}
}
/// <summary>
/// Globale → prodotto → esatta, ogni livello pesato dai propri esempi.
/// </summary>
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 };
}
/// <summary>Una riga del profilo, leggibile: per mostrarlo.</summary>
public readonly record struct Row(string Product, int HourBand, bool Weekend, long Auctions, double WinnerBids, double CloseRatio);
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<Row> Rows(int max = 200)
{
var list = new List<Row>();
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<string, Cell> Cells { get; set; } = new();
}
public string ToJson()
{
lock (_sync)
{
return JsonSerializer.Serialize(new Snapshot
{
AuctionsObserved = AuctionsObserved,
Cells = new Dictionary<string, Cell>(_cells)
});
}
}
public static AuctionProfileStats FromJson(string json)
{
var s = new AuctionProfileStats();
try
{
var snap = JsonSerializer.Deserialize<Snapshot>(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;
}
}
+229
View File
@@ -0,0 +1,229 @@
namespace BidooBidBot.Ml;
/// <summary>
/// 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
/// <c>bot_decisions.state</c>: il CSV dei dati del modello ricostruisce il vettore da qui.
/// </summary>
/// <param name="CycleSeconds">Quanto è durato il ciclo che questa puntata chiude. Negativo = ignoto.</param>
/// <param name="AutoShareRecent">Quota di autopuntate fra le ultime dieci (0-1). Negativo = ignoto.</param>
/// <param name="DistinctBiddersRecent">Puntatori distinti fra le ultime venti.</param>
/// <param name="PriceRatio">Prezzo sul valore del prodotto. Null = valore ignoto.</param>
/// <param name="Hour">Ora locale della puntata.</param>
/// <param name="Day">Giorno della settimana.</param>
/// <param name="OpenHour">Ora locale in cui l'asta è stata agganciata.</param>
/// <param name="IsAutoBid">La puntata è dell'autopuntata del sito.</param>
/// <param name="CyclesSinceManual">Autopuntate di fila prima di questa. Negativo = nessuna manuale in vista.</param>
/// <param name="AuctionDepthCents">Prezzo in centesimi: le puntate fatte da tutti.</param>
/// <param name="SameBidderAsTwoAgo">Chi punta è lo stesso di due puntate fa: la firma del duello.</param>
/// <param name="ProductKey">Chiave normalizzata del prodotto.</param>
/// <param name="DeepCyclesRecent">Fra gli ultimi dieci cicli, quanti hanno raggiunto gli 8 s.</param>
/// <param name="PriceVsTypicalClose">Prezzo sulla chiusura tipica del prodotto a quest'ora.</param>
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);
/// <summary>
/// Da <see cref="BidContext"/> al vettore del modello (portato dal legacy, <c>Version = 2</c>).
///
/// <para>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.</para>
/// </summary>
public static class BidFeatures
{
/// <summary>Cambia ogni volta che si aggiunge, toglie o ridefinisce una fascia: l'archivio si ristudia.</summary>
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;
/// <summary>Nomi delle variabili nell'ordine del vettore.</summary>
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;
/// <summary>0: 0-8 · 1: 9 · 2: 10-12 · 3: 13-17 · 4: 18-20 · 5: 21-23.</summary>
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;
/// <summary>Quanti degli ultimi dieci intervalli fra puntate hanno raggiunto gli 8 s (istanti dal più recente).</summary>
public static int CountDeepCycles(IReadOnlyList<long> 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;
}
/// <summary>Hash stabile fra un avvio e l'altro (FNV-1a): string.GetHashCode cambia a ogni processo.</summary>
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);
}
/// <summary>Il nome di una variabile in italiano semplice, per la scheda Apprendimento.</summary>
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<string>();
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();
}
}
+165
View File
@@ -0,0 +1,165 @@
using System.Text.Json;
using BidooBidBot.Data;
using BidooBidBot.Settings;
namespace BidooBidBot.Ml;
/// <summary>
/// L'anticipo della puntata deciso dalla rete di questa sessione, dentro i paletti
/// dell'utente (portato dal legacy).
///
/// <para><b>La regola.</b> <c>anticipo = margine + p99(andata e ritorno)</c>: 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.</para>
/// </summary>
public sealed class LatencyModel
{
public const string DocKey = "ml/latency";
private const int Window = 300;
private readonly object _sync = new();
private readonly Queue<int> _pings = new();
private readonly Queue<int> _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();
}
}
/// <summary>Una puntata inviata: quanto ci ha messo e se è arrivata tardi.</summary>
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);
}
/// <summary>L'anticipo consigliato adesso, dentro i paletti delle impostazioni.</summary>
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<int> 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<int>();
}
private void Load()
{
var json = _docs?.Get(DocKey);
if (string.IsNullOrEmpty(json)) return;
try
{
var s = JsonSerializer.Deserialize<Snap>(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 */ }
}
/// <summary>Si salva a ogni puntata tardiva e al massimo una volta al minuto altrimenti.</summary>
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);
}
/// <summary>Dimentica le misure: si riparte dai predefiniti.</summary>
public void Forget()
{
lock (_sync)
{
_pings.Clear();
_roundTrips.Clear();
_marginMs = 300;
_bidsSinceLastLate = 0;
_lateBids = 0;
_bidsTotal = 0;
}
_docs?.Delete(DocKey);
}
}
+166
View File
@@ -0,0 +1,166 @@
using BidooBidBot.Data;
namespace BidooBidBot.Ml;
/// <summary>Un'asta conclusa vista dal profilo e dalle previsioni.</summary>
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);
/// <summary>
/// Ciò che l'apprendimento legge e scrive nell'archivio. Un'interfaccia perché i test lo
/// provino senza PostgreSQL; in produzione è <see cref="DbLearningData"/>.
/// </summary>
public interface ILearningData
{
/// <summary>Aspetta che le scritture accodate siano sul disco (prima di leggere ciò che si è appena scritto).</summary>
Task FlushAsync();
Task<List<string>> PendingAuctionIdsAsync();
Task<int> PendingCountAsync();
Task<List<string>> ClosedAuctionIdsAsync(int max);
Task<TrainingReader.Session?> LoadSessionAsync(string auctionId, string? me);
Task<bool> IsLearnedAsync(string auctionId);
void MarkLearned(string auctionId);
Task MarkAllUnlearnedAsync();
/// <summary>Le decisioni dal vivo eseguite con esito: (P prevista, esito). Per la correzione sulle mie puntate.</summary>
Task<List<(double PWin, string Outcome)>> OwnBidOutcomesAsync(string? auctionId);
/// <summary>(chiave del contesto, esito) delle decisioni di un'asta: per il bandit.</summary>
Task<List<(string ContextKey, string Outcome)>> DecisionOutcomesAsync(string auctionId);
Task<List<string>> AuctionsWithDecisionOutcomesAsync();
Task<List<LossReasons.DecisionRow>> DecisionsForReasonAsync(string auctionId);
Task<List<LossReasons.MyBidRow>> MyBidsForReasonAsync(string auctionId);
void WriteLossReason(string auctionId, string reason);
Task<List<ClosedAuctionRow>> ClosedAuctionsAsync(int max);
Task<List<(string Reason, int Count)>> LossReasonSummaryAsync(int days);
Task<List<ShadowReport.Row>> 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<List<string>> 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<int> PendingCountAsync() =>
(int)(await _db.ScalarAsync<long>("SELECT COUNT(*) FROM auctions WHERE outcome IS NOT NULL AND learned_at IS NULL").ConfigureAwait(false));
public async Task<List<string>> 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<TrainingReader.Session?> 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<bool> IsLearnedAsync(string auctionId) =>
await _db.ScalarAsync<DateTime?>("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<List<(double PWin, string Outcome)>> 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<object?>());
public Task<List<(string ContextKey, string Outcome)>> DecisionOutcomesAsync(string auctionId) =>
_db.QueryAsync("SELECT context_key, outcome FROM bot_decisions WHERE auction_id = $1 AND context_key IS NOT NULL AND outcome IS NOT NULL",
r => (r.Str("context_key"), r.Str("outcome")), auctionId);
public Task<List<string>> AuctionsWithDecisionOutcomesAsync() =>
_db.QueryAsync("SELECT DISTINCT auction_id FROM bot_decisions WHERE context_key IS NOT NULL AND outcome IS NOT NULL ORDER BY auction_id",
r => r.Str("auction_id"));
public Task<List<LossReasons.DecisionRow>> DecisionsForReasonAsync(string auctionId) =>
_db.QueryAsync("SELECT action, kind, p_win, shadow, outcome FROM bot_decisions WHERE auction_id = $1 ORDER BY decision_id",
r => new LossReasons.DecisionRow(r.Str("action"), r.StrOrNull("kind"), r.DblOrNull("p_win"), r.Bool("shadow"), r.StrOrNull("outcome")),
auctionId);
public Task<List<LossReasons.MyBidRow>> MyBidsForReasonAsync(string auctionId) =>
_db.QueryAsync("SELECT price, answered_after_s, answered_by, answered_type, unanswered FROM my_bids WHERE auction_id = $1 AND success ORDER BY id",
r => new LossReasons.MyBidRow(r.Dbl("price"), r.DblOrNull("answered_after_s"), r.StrOrNull("answered_by"), r.StrOrNull("answered_type"), r.BoolOrNull("unanswered")),
auctionId);
public void WriteLossReason(string auctionId, string reason) =>
_queue.Enqueue("UPDATE auctions SET loss_reason = $2 WHERE auction_id = $1", auctionId, reason);
public Task<List<ClosedAuctionRow>> ClosedAuctionsAsync(int max) =>
_db.QueryAsync(
"SELECT auction_id, product_key, end_time, final_price, buy_now_price, market_value, winner_bids_paid, winner_bids_free, opened_at, won_by_me, winner_user " +
"FROM auctions WHERE outcome IS NOT NULL AND final_price IS NOT NULL AND end_time IS NOT NULL ORDER BY end_time DESC LIMIT $1",
r => new ClosedAuctionRow(r.Str("auction_id"), r.Str("product_key"), r.Date("end_time")!.Value, r.Dbl("final_price"),
r.DblOrNull("buy_now_price"), r.DblOrNull("market_value"), r.IntOrNull("winner_bids_paid"), r.IntOrNull("winner_bids_free"),
r.Date("opened_at"), r.Bool("won_by_me"), r.Str("winner_user")),
max <= 0 ? 1_000_000 : max);
public async Task<List<(string Reason, int Count)>> LossReasonSummaryAsync(int days)
{
var rows = await _db.QueryAsync(
"SELECT loss_reason FROM auctions WHERE outcome IS NOT NULL AND loss_reason IS NOT NULL AND end_time >= now() - make_interval(days => $1)",
r => r.Str("loss_reason"), days).ConfigureAwait(false);
return rows.GroupBy(LossReasons.Group).Select(g => (g.Key, g.Count())).OrderByDescending(t => t.Item2).ToList();
}
public Task<List<ShadowReport.Row>> ShadowRowsAsync(int days, bool? shadow, double defaultBidCost) =>
_db.QueryAsync(
"SELECT d.action, d.alt_action, d.outcome, d.ev, d.price, d.shadow, d.executed, d.bid_cost, " +
" COALESCE(a.market_value, a.buy_now_price, d.value, 0) AS v, COALESCE(a.shipping, 0) AS ship " +
"FROM bot_decisions d JOIN auctions a ON a.auction_id = d.auction_id " +
"WHERE d.ts >= now() - make_interval(days => $1) AND d.outcome IS NOT NULL AND d.kind IN ('punta', 'esplora', 'ev-negativo', 'non-pronto')" +
(shadow is { } s ? (s ? " AND d.shadow" : " AND NOT d.shadow") : ""),
r => new ShadowReport.Row(r.Str("action"), r.StrOrNull("alt_action"), r.Str("outcome"), r.DblOrNull("ev"), r.Dbl("price"),
r.Dbl("v"), r.Dbl("ship"), r.DblOrNull("bid_cost") is > 0 ? r.Dbl("bid_cost") : defaultBidCost, r.Bool("shadow"), r.Bool("executed")),
days);
}
@@ -0,0 +1,225 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BidooBidBot.Ml;
/// <summary>
/// Valuta il modello sulle aste vere del database, con una divisione onesta nel tempo:
/// si impara dalle più vecchie e si giudica sulle più recenti, mai viste. Poi, sulle
/// recenti, la valutazione <b>prequenziale</b>: ogni asta prima prevista e poi appresa,
/// in ordine di tempo, che è esattamente la sequenza del motore in produzione.
///
/// <para>Sta in una classe a sé perché la usano in due: i test (su sessioni costruite a
/// mano) e la scheda Apprendimento («Valutazione»). Portata dal legacy.</para>
///
/// <para><b>Cosa misura.</b> Quanto il modello separa le puntate rimaste senza risposta
/// (sollevamento nella cima della classifica), se la probabilità è nella scala giusta
/// (calibrazione per fasce, punteggio di Brier), e sulle nostre puntate vere cosa
/// avrebbe fatto il cancello del valore atteso.</para>
/// </summary>
public static class LearningEvaluator
{
public sealed class Report
{
public string Text { get; init; } = "";
public int Auctions { get; init; }
public int Usable { get; init; }
public double Lift5 { get; init; }
public double Brier { get; init; }
public double CalibrationFactor { get; init; }
public int MyBids { get; init; }
public int MyBlocked { get; init; }
public int MyBlockedWinning { get; init; }
public bool Enough => Usable >= 20;
}
private sealed record Row(double P, bool Unanswered, bool Mine, double Ev);
public static async Task<Report> RunAsync(ILearningData data, int maxAuctions, string? me, Action<string>? progress = null, CancellationToken ct = default)
{
await data.FlushAsync().ConfigureAwait(false);
var ids = await data.ClosedAuctionIdsAsync(maxAuctions).ConfigureAwait(false);
var sessions = new List<TrainingReader.Session>();
var read = 0;
foreach (var id in ids)
{
ct.ThrowIfCancellationRequested();
var s = await data.LoadSessionAsync(id, me).ConfigureAwait(false);
if (s != null && s.IsUsable) sessions.Add(s);
if (++read % 200 == 0) progress?.Invoke($"lette {read:N0} aste su {ids.Count:N0}...");
}
return Evaluate(sessions, ids.Count, progress, ct);
}
/// <summary>La valutazione vera e propria, su sessioni già in memoria (anche per i test).</summary>
public static Report Evaluate(List<TrainingReader.Session> sessions, int totalAuctions, Action<string>? progress = null, CancellationToken ct = default)
{
var report = new StringBuilder();
report.AppendLine($"Aste chiuse: {totalAuctions:N0}, utilizzabili: {sessions.Count:N0}");
if (sessions.Count < 20)
{
report.AppendLine("Troppo poche aste utilizzabili per una valutazione.");
return new Report { Text = report.ToString(), Auctions = totalAuctions, Usable = sessions.Count };
}
progress?.Invoke("addestramento e confronto delle configurazioni…");
var split = (int)(sessions.Count * 0.7);
var train = sessions.Take(split).ToList();
var test = sessions.Skip(split).ToList();
var trainX = train.SelectMany(s => TrainingReader.Examples(s))
.Select(e => (X: BidFeatures.Build(e.Context), Y: e.Unanswered)).ToList();
var perAsta = test.Select(s => TrainingReader.Examples(s)
.Select(e => (
X: BidFeatures.Build(e.Context), Y: e.Unanswered, Mine: e.Mine,
Margine: s.BuyNowPrice is > 0 ? s.BuyNowPrice.Value - e.Context.AuctionDepthCents / 100.0 - 0.01 : double.NaN))
.ToList()).ToList();
var testX = perAsta.SelectMany(a => a).ToList();
var n = testX.Count;
var positives = testX.Count(r => r.Y);
var baseRate = (double)positives / Math.Max(1, n);
report.AppendLine($"Addestramento: {train.Count:N0} aste, {trainX.Count:N0} puntate");
report.AppendLine($"Valutazione : {test.Count:N0} aste, {n:N0} puntate, {positives:N0} senza risposta ({baseRate:P3})");
report.AppendLine();
// ── Confronto fra configurazioni (modello congelato) ─────────────
const double costo = 0.20;
var configs = new List<(string Nome, double Lr, double L2)>();
foreach (var lr in new[] { 0.01, 0.003 })
foreach (var l2 in new[] { 1e-4, 0.0 })
configs.Add(($"passo {lr:0.000}, L2 {l2:0.######}", lr, l2));
report.AppendLine("Configurazione (modello congelato) | sollev. 5% | prevista/osservata (cima 10%) | prevista/osservata (tutte)");
report.AppendLine("-------------------------------------+------------+-------------------------------+---------------------------");
OnlineLogit? best = null; var bestName = ""; var bestScore = double.MaxValue;
foreach (var (nome, lr, l2) in configs)
{
ct.ThrowIfCancellationRequested();
var modello = new OnlineLogit(BidFeatures.Size) { LearningRate = lr, L2 = l2 };
foreach (var (x, y) in trainX) modello.Update(x, y);
var ps = testX.Select(r => modello.Predict(r.X)).ToArray();
var order = Enumerable.Range(0, n).OrderByDescending(i => ps[i]).ToArray();
var k5 = Math.Max(1, n / 20); var k10 = Math.Max(1, n / 10);
var lift5 = order.Take(k5).Count(i => testX[i].Y) / (double)k5 / Math.Max(1e-9, baseRate);
var top10 = order.Take(k10).ToArray();
var ratioTop = top10.Average(i => ps[i]) / Math.Max(1e-9, top10.Average(i => testX[i].Y ? 1.0 : 0.0));
var ratioAll = ps.Average() / Math.Max(1e-9, baseRate);
report.AppendLine($"{nome,-37} | {lift5,9:N2}x | {ratioTop,29:N2} | {ratioAll,25:N2}");
var score = Math.Abs(Math.Log(Math.Max(1e-9, ratioTop))) + Math.Abs(Math.Log(Math.Max(1e-9, ratioAll)));
if (lift5 > 2.0 && score < bestScore) { bestScore = score; best = modello; bestName = nome; }
}
report.AppendLine();
if (best == null)
{
report.AppendLine("Nessuna configurazione separa abbastanza (sollevamento al 5% > 2x).");
return new Report { Text = report.ToString(), Auctions = totalAuctions, Usable = sessions.Count };
}
report.AppendLine($"Scelta: {bestName}");
report.AppendLine();
// ── Prequenziale: come nell'uso vero ─────────────────────────────
progress?.Invoke("valutazione prequenziale…");
var model = best;
var rows = new List<Row>();
foreach (var esempi in perAsta)
{
ct.ThrowIfCancellationRequested();
foreach (var r in esempi)
{
var p = model.PredictCalibrated(r.X);
rows.Add(new Row(p, r.Y, r.Mine, double.IsNaN(r.Margine) ? double.NaN : p * r.Margine - costo));
}
foreach (var r in esempi) model.Update(r.X, r.Y);
}
report.AppendLine($"Valutazione prequenziale (ogni asta prima prevista, poi appresa), fattore di calibrazione finale {model.CalibrationFactor:N2}:");
var meanPos = rows.Where(r => r.Unanswered).Select(r => r.P).DefaultIfEmpty(0).Average();
var meanNeg = rows.Where(r => !r.Unanswered).Select(r => r.P).DefaultIfEmpty(0).Average();
report.AppendLine($"P media sulle puntate senza risposta : {meanPos:P3}");
report.AppendLine($"P media sulle altre : {meanNeg:P3}");
report.AppendLine($"rapporto : {meanPos / Math.Max(meanNeg, 1e-9):N2}x");
// Il punteggio di Brier: media del quadrato dell'errore fra probabilità e
// esito. È la misura onesta di una probabilità: premia chi è calibrato E
// discrimina. Si confronta con quello del tasso di base, che è il minimo
// ottenibile senza guardare nulla.
var brier = rows.Average(r => Math.Pow(r.P - (r.Unanswered ? 1 : 0), 2));
var brierBase = rows.Average(r => Math.Pow(baseRate - (r.Unanswered ? 1 : 0), 2));
report.AppendLine($"punteggio di Brier : {brier:F6} (tasso di base: {brierBase:F6}, miglioramento {(1 - brier / Math.Max(1e-12, brierBase)):P1})");
report.AppendLine();
var sorted = rows.OrderByDescending(r => r.P).ToList();
report.AppendLine("Sollevamento nella cima della classifica (precisione / tasso di base):");
double liftTop5 = 0;
foreach (var frac in new[] { 0.01, 0.05, 0.10, 0.25 })
{
var k = Math.Max(1, (int)(n * frac));
var prec = sorted.Take(k).Count(r => r.Unanswered) / (double)k;
var lift = prec / Math.Max(1e-9, baseRate);
if (frac == 0.05) liftTop5 = lift;
report.AppendLine($" cima {frac:P0}: {k,8:N0} puntate, precisione {prec:P2}, sollevamento {lift:N2}x");
}
report.AppendLine();
report.AppendLine("Calibrazione per fasce di probabilità prevista:");
var edges = new[] { 0.0, 0.001, 0.0025, 0.005, 0.01, 0.02, 0.05, 1.0 };
for (var i = 0; i < edges.Length - 1; i++)
{
var bin = rows.Where(r => r.P >= edges[i] && r.P < edges[i + 1]).ToList();
if (bin.Count == 0) continue;
report.AppendLine($" P in [{edges[i]:P2}, {edges[i + 1]:P2}): {bin.Count,8:N0} puntate, prevista {bin.Average(r => r.P):P3}, osservata {bin.Average(r => r.Unanswered ? 1.0 : 0.0):P3}");
}
report.AppendLine();
var mie = rows.Where(r => r.Mine && !double.IsNaN(r.Ev)).ToList();
var fermate = mie.Where(r => r.Ev < 0).ToList();
if (mie.Count > 0)
{
var passate = mie.Where(r => r.Ev >= 0).ToList();
report.AppendLine($"Le mie puntate nel periodo di valutazione: {mie.Count:N0}, di cui finali {mie.Count(r => r.Unanswered):N0}");
report.AppendLine($" il cancello ne avrebbe lasciate passare {passate.Count:N0} (finali: {passate.Count(r => r.Unanswered):N0})");
report.AppendLine($" e ne avrebbe fermate {fermate.Count:N0} (di cui finali, cioè vincenti perse: {fermate.Count(r => r.Unanswered):N0})");
}
else
{
report.AppendLine("Nessuna mia puntata nel periodo di valutazione (serve il nome utente, o non ci sono).");
}
report.AppendLine();
report.AppendLine("Pesi più forti (cosa ha imparato):");
foreach (var (nome, peso) in BidFeatures.Names.Select((nm, i) => (nm, model.Weights[i])).OrderByDescending(t => Math.Abs(t.Item2)).Take(15))
report.AppendLine($" {peso,+8:F3} {nome}");
return new Report
{
Text = report.ToString(),
Auctions = totalAuctions,
Usable = sessions.Count,
Lift5 = liftTop5,
Brier = brier,
CalibrationFactor = model.CalibrationFactor,
MyBids = mie.Count,
MyBlocked = fermate.Count,
MyBlockedWinning = fermate.Count(r => r.Unanswered)
};
}
}
@@ -0,0 +1,762 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using BidooBidBot.Bidoo;
using BidooBidBot.Data;
using BidooBidBot.Engine;
using BidooBidBot.Logging;
using BidooBidBot.Products;
using BidooBidBot.Settings;
namespace BidooBidBot.Ml;
/// <summary>Avanzamento di un'operazione lunga, per la finestra di avanzamento dell'interfaccia.</summary>
public readonly record struct ProgressStep(int Done, int Total, string? Detail = null);
/// <summary>Un'asta appena chiusa, per l'apprendimento.</summary>
public sealed record ClosedAuctionInfo(
string AuctionId, string Name, string ProductKey, DateTime EndedAtUtc, double FinalPrice, double? BuyNow,
double? MarketValue, int? WinnerBidsPaid, int? WinnerBidsFree, bool WonByMe, string Winner, double? ObservedMinutes);
/// <summary>
/// L'apprendimento (portato dal legacy, specifica §7): impara da ogni asta che chiude e
/// risponde al motore quando deve decidere. È l'unica strategia del bot.
///
/// <para><b>Tre cose imparate.</b> Il <i>modello delle puntate</i> risponde a «se punto
/// adesso, qualcuno risponderà?» (logistica online campione, rete sfidante). Il <i>profilo</i>
/// e le <i>previsioni</i> rispondono a «come chiude di solito questo prodotto a quest'ora?».
/// La <i>correzione sulle mie puntate</i> risponde a «quando sono io a puntare, il modello ci
/// prende?». Il bandit impara dagli esiti di ogni decisione, anche senza puntata, e guida
/// l'esplorazione.</para>
///
/// <para>Tutto lo stato vive in memoria (il motore chiede una probabilità in microsecondi) e
/// si salva nei documenti <c>ml/*</c>. Cambiare le variabili (<see cref="BidFeatures.Version"/>)
/// fa ristudiare l'archivio da capo.</para>
/// </summary>
public sealed class LearningService
{
public const int FullStudyBacklog = 200;
public const int OwnBidsMinimum = 30;
public const double ExplorationEvidence = 200;
private const double BrierWindow = 20_000;
private const long ChallengerMinSamples = 5_000;
private const int MaxDecisions = 300;
private readonly object _sync = new();
private readonly object _saveSync = new();
private readonly IDocumentStore _docs;
private readonly ILearningData _data;
private readonly Func<AppSettings> _settings;
private readonly AppLog? _log;
private readonly string _prefix;
private OnlineLogit _model = new(BidFeatures.Size);
private NeuralNet _challenger = NewChallenger();
private ThompsonBandit _bandit = new();
private AuctionProfileStats _profile = new();
private AuctionForecast _forecast = new();
private int _learned;
private volatile bool _studying;
private volatile bool _fullStudyPending;
private double _brierLogit = double.NaN;
private double _brierNet = double.NaN;
private long _brierSamples;
private double _ownPredicted;
private double _ownObserved;
private int _ownBids;
private string _explorationDay = "";
private int _explorationUsed;
private readonly Queue<Decision> _decisions = new();
private readonly HashSet<string> _closedSeen = new(StringComparer.Ordinal);
private DateTime _lastSaveUtc = DateTime.MinValue;
/// <param name="prefix">Radice dei documenti: <c>ml/</c> per il modello vero, <c>ml-sim/</c> per quello del simulatore.</param>
public LearningService(IDocumentStore docs, ILearningData data, Func<AppSettings> settings, AppLog? log, string prefix = "ml/")
{
_docs = docs;
_data = data;
_settings = settings;
_log = log;
_prefix = prefix;
}
private static NeuralNet NewChallenger() =>
new(new[] { BidFeatures.Size, 32, 16, 1 }, seed: 42) { LearningRate = 0.001, L2 = 1e-5 };
private string Key(string name) => _prefix + name;
// ── Stato ────────────────────────────────────────────────────────────
public ThompsonBandit Bandit { get { lock (_sync) return _bandit; } }
public long ModelUpdates { get { lock (_sync) return _model.Updates; } }
public double CalibrationFactor { get { lock (_sync) return _model.CalibrationFactor; } }
public int AuctionsLearned { get { lock (_sync) return _learned; } }
public long ProfileAuctions { get { lock (_sync) return _profile.AuctionsObserved; } }
public bool Studying => _studying;
public bool FullStudyPending => _fullStudyPending;
public bool ChallengerLeads
{
get { lock (_sync) return _brierSamples >= ChallengerMinSamples && !double.IsNaN(_brierNet) && _brierNet < _brierLogit; }
}
/// <summary>«logit» o «rete»: chi risponde al motore adesso.</summary>
public string Champion => ChallengerLeads ? "rete" : "logit";
public (double Logit, double Net, long Samples) BrierScores { get { lock (_sync) return (_brierLogit, _brierNet, _brierSamples); } }
public string ModelVersion
{
get
{
lock (_sync)
{
var net = _brierSamples >= ChallengerMinSamples && !double.IsNaN(_brierNet) && _brierNet < _brierLogit;
return net ? $"mlp-v{BidFeatures.Version}-{_challenger.Updates}" : $"logit-v{BidFeatures.Version}-{_model.Updates}";
}
}
}
public string NetworkShape => string.Join("→", _challenger.Sizes);
public bool IsReady(AppSettings s) => AuctionsLearned >= Math.Max(1, s.LearningMinAuctions);
public enum StudyState { DaRicalcolare, InStudio, InAscolto, Pronto }
public readonly record struct Status(StudyState State, int Learned, int Pending, int Threshold, string Headline, string Detail);
public async Task<Status> GetStatusAsync(AppSettings settings)
{
var learned = AuctionsLearned;
var pending = await _data.PendingCountAsync().ConfigureAwait(false);
var threshold = Math.Max(1, settings.LearningMinAuctions);
if (_studying)
return new Status(StudyState.InStudio, learned, pending, threshold, "Sta studiando",
$"{learned:N0} aste studiate, {pending:N0} ancora da vedere. Intanto decide con quello che sa.");
if (_fullStudyPending || (learned == 0 && pending > 0))
return new Status(StudyState.DaRicalcolare, learned, pending, threshold, "Serve un ricalcolo",
$"Il modo di leggere le aste è cambiato (variabili versione {BidFeatures.Version}): le {pending:N0} aste in archivio vanno studiate di nuovo. Premi «Studia adesso».");
if (learned < threshold)
return new Status(StudyState.InAscolto, learned, pending, threshold, "Sta ancora imparando",
$"Ha studiato {learned:N0} aste su {threshold:N0} necessarie: finché non ci arriva, in Attiva punta entro i paletti senza fermare nessuna puntata.");
return new Status(StudyState.Pronto, learned, pending, threshold, "Pronto",
pending > 0
? $"Ha studiato {learned:N0} aste; {pending:N0} chiuse di recente aspettano di essere studiate (succede da sé, o premi «Studia adesso»)."
: $"Ha studiato {learned:N0} aste e decide a ogni ciclo con il valore atteso.");
}
/// <summary>I pesi con i loro nomi, dal più forte: cosa ha imparato.</summary>
public IReadOnlyList<(string Name, double Weight)> Weights()
{
lock (_sync)
return BidFeatures.Names.Select((n, i) => (n, _model.Weights[i])).OrderByDescending(t => Math.Abs(t.Item2)).ToList();
}
public IReadOnlyList<AuctionProfileStats.Row> ProfileRows(int max = 200)
{
lock (_sync) return _profile.Rows(max);
}
public AuctionProfileStats.Estimate? Expect(string? productKey, DateTime whenLocal)
{
lock (_sync) return _profile.Expect(productKey, whenLocal);
}
// ── Correzione sulle mie puntate ─────────────────────────────────────
/// <summary>(osservate + 0,5) / (previste + 0,5), limitata a [0,25; 4], attiva da 30 puntate. 1 = nessuna correzione.</summary>
public double OwnBidFactor
{
get
{
lock (_sync)
{
if (_ownBids < OwnBidsMinimum || _ownPredicted <= 0) return 1.0;
return Math.Clamp((_ownObserved + 0.5) / (_ownPredicted + 0.5), 0.25, 4.0);
}
}
}
public (int Bids, double Predicted, double Observed) OwnBidStats { get { lock (_sync) return (_ownBids, _ownPredicted, _ownObserved); } }
public async Task<(int Bids, double Factor)> RebuildOwnCalibrationAsync()
{
await _data.FlushAsync().ConfigureAwait(false);
var rows = await _data.OwnBidOutcomesAsync(null).ConfigureAwait(false);
lock (_sync)
{
_ownPredicted = 0; _ownObserved = 0; _ownBids = 0;
foreach (var (p, outcome) in rows)
{
_ownPredicted += p;
_ownObserved += outcome == "won" ? 1 : 0;
_ownBids++;
}
}
Save(force: true);
return (rows.Count, OwnBidFactor);
}
// ── Esplorazione ─────────────────────────────────────────────────────
private static string Today() => AppInfo.LocalNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
public int ExplorationUsedToday
{
get { lock (_sync) return _explorationDay == Today() ? _explorationUsed : 0; }
}
public bool ExplorationAvailable(AppSettings s) => s.ExplorationBidsPerDay > 0 && ExplorationUsedToday < s.ExplorationBidsPerDay;
public void NoteExplorationBid()
{
lock (_sync)
{
var today = Today();
if (_explorationDay != today) { _explorationDay = today; _explorationUsed = 0; }
_explorationUsed++;
}
Save(force: true);
}
// ── Ultime decisioni (per la scheda) ─────────────────────────────────
public readonly record struct Decision(DateTime AtUtc, string AuctionId, string Auction, double Price, double Probability,
double ExpectedValue, string Action, string Kind, string Reason, bool Shadow);
public void RecordDecision(Decision d)
{
lock (_decisions)
{
_decisions.Enqueue(d);
while (_decisions.Count > MaxDecisions) _decisions.Dequeue();
}
}
public IReadOnlyList<Decision> RecentDecisions(int max = 100)
{
lock (_decisions) return _decisions.Reverse().Take(max).ToList();
}
// ── Domande dal motore ───────────────────────────────────────────────
/// <summary>P(senza risposta) per un contesto: risponde il campione del momento. In microsecondi.</summary>
public double PredictUnanswered(in BidContext ctx)
{
var x = BidFeatures.Build(ctx);
lock (_sync)
{
var net = _brierSamples >= ChallengerMinSamples && !double.IsNaN(_brierNet) && _brierNet < _brierLogit;
return net ? _challenger.PredictCalibrated(x) : _model.PredictCalibrated(x);
}
}
private double? TypicalCloseRatioUnlocked(string productKey, DateTime whenLocal)
{
var e = _profile.Expect(productKey, whenLocal);
return e is { CloseRatio: > 0 } est ? est.CloseRatio : null;
}
/// <summary>
/// Lo stato dell'asta nell'istante della decisione, ridotto alle variabili del modello.
/// Null quando non c'è abbastanza contesto (nessuna puntata recente).
/// </summary>
public BidContext? BuildContext(AuctionInfo auction, AuctionState state, DateTime nowLocal, string? me)
{
var recent = auction.SnapshotRecentBids(20);
if (recent.Count == 0) return null;
var last = recent[0];
var gap = state.ServerUnixSeconds > 0 && last.Timestamp > 0 ? state.ServerUnixSeconds - last.Timestamp : -1;
int declared = 0, auto = 0;
foreach (var b in recent.Take(10))
{
if (b.IsAuto) { auto++; declared++; }
else if (b.IsManual) declared++;
}
var autoShare = declared == 0 ? -1 : (double)auto / declared;
var distinct = recent.Select(b => b.Username).Distinct(StringComparer.OrdinalIgnoreCase).Count();
var sinceManual = -1;
for (var i = 0; i < recent.Count; i++)
{
if (recent[i].IsManual) { sinceManual = i; break; }
if (!recent[i].IsAuto) break;
}
var productKey = string.IsNullOrEmpty(auction.ProductKey) ? ProductKey.From(auction.Name) : auction.ProductKey;
double? ratio = auction.BuyNowPrice is > 0 ? state.Price / auction.BuyNowPrice.Value : null;
double? typical = null;
if (ratio is { } r)
{
double? close;
lock (_sync) close = TypicalCloseRatioUnlocked(productKey, nowLocal);
if (close is { } c && c > 0) typical = r / c;
}
return new BidContext(
CycleSeconds: gap,
AutoShareRecent: autoShare,
DistinctBiddersRecent: Math.Max(1, distinct),
PriceRatio: ratio,
Hour: nowLocal.Hour,
Day: nowLocal.DayOfWeek,
OpenHour: AppInfo.ToLocal(auction.TrackingStartedAtUtc ?? auction.AddedAtUtc).Hour,
IsAutoBid: false,
CyclesSinceManual: sinceManual,
AuctionDepthCents: (int)Math.Round(state.Price * 100),
SameBidderAsTwoAgo: recent.Count >= 2 && !string.IsNullOrEmpty(me) && string.Equals(recent[1].Username, me, StringComparison.OrdinalIgnoreCase),
ProductKey: productKey,
DeepCyclesRecent: BidFeatures.CountDeepCycles(recent.Select(b => b.Timestamp).ToList()),
PriceVsTypicalClose: typical);
}
/// <summary>La previsione dell'asta con i numeri di adesso.</summary>
public ForecastResult? Forecast(ForecastInput input)
{
lock (_sync) return _forecast.Forecast(input);
}
public long ForecastObserved { get { lock (_sync) return _forecast.Observed; } }
// ── Avvio ────────────────────────────────────────────────────────────
public async Task LoadAsync()
{
var storedVersion = ReadInt(Key("features-version"), "version");
var hasModel = _docs.Get(Key("model")) != null;
if (hasModel && storedVersion != BidFeatures.Version)
{
_log?.Warn("APPRENDIMENTO", $"Le variabili del modello sono cambiate (versione {storedVersion?.ToString(CultureInfo.InvariantCulture) ?? "vecchia"} -> {BidFeatures.Version}): ricomincio a studiare l'archivio");
await ForgetAsync().ConfigureAwait(false);
return;
}
lock (_sync)
{
try
{
if (_docs.Get(Key("model")) is { } model) _model = OnlineLogit.FromJson(model, BidFeatures.Size);
if (_docs.Get(Key("challenger")) is { } ch) _challenger = NeuralNet.FromJson(ch, new[] { BidFeatures.Size, 32, 16, 1 });
if (_docs.Get(Key("bandit")) is { } b) _bandit = ThompsonBandit.FromJson(b);
if (_docs.Get(Key("profile")) is { } p) _profile = AuctionProfileStats.FromJson(p);
_forecast = AuctionForecast.FromJson(_docs.Get(Key("forecast")));
if (ReadObject(Key("brier")) is { } brier)
{
_brierLogit = brier.TryGetProperty("logit", out var l) && l.ValueKind == JsonValueKind.Number ? l.GetDouble() : double.NaN;
_brierNet = brier.TryGetProperty("net", out var n) && n.ValueKind == JsonValueKind.Number ? n.GetDouble() : double.NaN;
_brierSamples = brier.TryGetProperty("samples", out var s) ? s.GetInt64() : 0;
}
if (ReadObject(Key("own-bid-factor")) is { } own)
{
_ownBids = own.GetProperty("bids").GetInt32();
_ownPredicted = own.GetProperty("predicted").GetDouble();
_ownObserved = own.GetProperty("observed").GetDouble();
}
if (ReadObject(Key("exploration")) is { } ex)
{
_explorationDay = ex.GetProperty("day").GetString() ?? "";
_explorationUsed = ex.GetProperty("used").GetInt32();
}
_learned = ReadInt(Key("learned"), "count") ?? 0;
}
catch (Exception e) when (e is JsonException or KeyNotFoundException or InvalidOperationException)
{
_log?.Warn("APPRENDIMENTO", $"Archivio del modello illeggibile, si riparte da zero: {e.Message}");
_model = new OnlineLogit(BidFeatures.Size);
_profile = new AuctionProfileStats();
_learned = 0;
}
}
if (storedVersion == null) _docs.Set(Key("features-version"), JsonSerializer.Serialize(new { version = BidFeatures.Version }));
if (_docs.Get(Key("own-bid-factor")) == null)
{
try
{
var (n, f) = await RebuildOwnCalibrationAsync().ConfigureAwait(false);
if (n > 0) _log?.Info("APPRENDIMENTO", $"Correzione sulle mie puntate calcolata da {n} puntate registrate: fattore {f:N2}");
}
catch { /* si rifà alla prossima asta */ }
}
if (ProfileAuctions == 0) await RebuildProfileAsync(null, CancellationToken.None).ConfigureAwait(false);
_fullStudyPending = AuctionsLearned == 0 && await _data.PendingCountAsync().ConfigureAwait(false) > 0;
_log?.Info("APPRENDIMENTO", $"Modello: {ModelUpdates:N0} esempi da {AuctionsLearned:N0} aste, profilo {ProfileAuctions:N0} aste, correzione sulle mie puntate {OwnBidFactor:N2}, risponde il {(ChallengerLeads ? "la rete" : "logistico")}");
}
private int? ReadInt(string key, string property) =>
ReadObject(key) is { } o && o.TryGetProperty(property, out var v) && v.TryGetInt32(out var i) ? i : null;
private JsonElement? ReadObject(string key)
{
var json = _docs.Get(key);
if (string.IsNullOrEmpty(json)) return null;
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.ValueKind == JsonValueKind.Object ? doc.RootElement.Clone() : null;
}
catch (JsonException) { return null; }
}
/// <summary>
/// Salva tutto nei documenti. Durante lo studio al massimo una volta ogni 30 s; alla fine
/// di ogni operazione con <paramref name="force"/>.
/// </summary>
public void Save(bool force = false)
{
string model, challenger, bandit, profile, forecast, brier, own, expl;
int learned;
lock (_sync)
{
if (!force && DateTime.UtcNow - _lastSaveUtc < TimeSpan.FromSeconds(30)) return;
_lastSaveUtc = DateTime.UtcNow;
model = _model.ToJson();
challenger = _challenger.ToJson();
bandit = _bandit.ToJson();
profile = _profile.ToJson();
forecast = _forecast.ToJson();
brier = JsonSerializer.Serialize(new
{
logit = double.IsNaN(_brierLogit) ? (double?)null : _brierLogit,
net = double.IsNaN(_brierNet) ? (double?)null : _brierNet,
samples = _brierSamples
});
own = JsonSerializer.Serialize(new { bids = _ownBids, predicted = _ownPredicted, observed = _ownObserved });
expl = JsonSerializer.Serialize(new { day = _explorationDay, used = _explorationUsed });
learned = _learned;
}
lock (_saveSync)
{
_docs.Set(Key("model"), model);
_docs.Set(Key("challenger"), challenger);
_docs.Set(Key("bandit"), bandit);
_docs.Set(Key("profile"), profile);
_docs.Set(Key("forecast"), forecast);
_docs.Set(Key("brier"), brier);
_docs.Set(Key("own-bid-factor"), own);
_docs.Set(Key("exploration"), expl);
_docs.Set(Key("learned"), JsonSerializer.Serialize(new { count = learned }));
_docs.Set(Key("features-version"), JsonSerializer.Serialize(new { version = BidFeatures.Version }));
}
}
/// <summary>Profilo e distribuzioni delle previsioni rifatti da tutte le aste concluse.</summary>
public async Task<int> RebuildProfileAsync(IProgress<ProgressStep>? progress, CancellationToken ct)
{
var rows = await _data.ClosedAuctionsAsync(0).ConfigureAwait(false);
var profile = new AuctionProfileStats();
var forecast = new AuctionForecast();
var done = 0;
foreach (var r in rows.OrderBy(r => r.EndUtc))
{
ct.ThrowIfCancellationRequested();
ObserveClosed(profile, forecast, r.ProductKey, r.EndUtc, r.FinalPrice, r.BuyNow, r.MarketValue, r.WinnerBidsPaid, r.WinnerBidsFree,
r.OpenedUtc is { } o ? (r.EndUtc - o).TotalMinutes : null);
if (++done % 100 == 0 || done == rows.Count) progress?.Report(new ProgressStep(done, rows.Count));
}
lock (_sync)
{
_profile = profile;
_forecast = forecast;
}
Save(force: true);
if (rows.Count > 0) _log?.Info("APPRENDIMENTO", $"Profilo delle aste e distribuzioni delle previsioni ricostruiti da {rows.Count:N0} aste concluse");
return rows.Count;
}
private static void ObserveClosed(AuctionProfileStats profile, AuctionForecast forecast, string productKey, DateTime endUtc,
double finalPrice, double? buyNow, double? marketValue, int? paid, int? free, double? minutes)
{
var local = AppInfo.ToLocal(endUtc);
int? total = paid.HasValue || free.HasValue ? (paid ?? 0) + (free ?? 0) : null;
var trusted = AuctionIntegrity.Trusted(finalPrice, total);
double? ratio = buyNow is > 0 && finalPrice > 0 ? finalPrice / buyNow.Value : null;
profile.Observe(productKey, local, trusted, ratio);
forecast.Observe(productKey, finalPrice, marketValue ?? buyNow, BidFeatures.HourBand(local.Hour), trusted, minutes);
}
/// <summary>Studio all'avvio: con budget di tempo se l'arretrato è piccolo, fino in fondo se è grande.</summary>
public void StartBootstrap(CancellationToken ct)
{
_ = Task.Run(async () =>
{
try
{
await Task.Delay(3000, ct).ConfigureAwait(false);
var backlog = await _data.PendingCountAsync().ConfigureAwait(false);
if (backlog >= FullStudyBacklog) _fullStudyPending = true;
TimeSpan? budget = _fullStudyPending ? null : TimeSpan.FromSeconds(Math.Max(10, _settings().LearningBootstrapSecondsPerStart));
await StudyPendingAsync(budget, null, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (Exception ex) { _log?.Error("APPRENDIMENTO", $"Studio all'avvio interrotto: {ex.Message}"); }
}, ct);
}
/// <summary>Studia adesso tutte le aste chiuse non ancora apprese.</summary>
public Task<(int Done, int Usable)> StudyNowAsync(IProgress<ProgressStep>? progress, CancellationToken ct) =>
StudyPendingAsync(null, progress, ct);
private async Task<(int Done, int Usable)> StudyPendingAsync(TimeSpan? budget, IProgress<ProgressStep>? progress, CancellationToken ct)
{
if (_studying) throw new InvalidOperationException("uno studio delle aste è già in corso: aspetta che finisca");
_studying = true;
var done = 0;
var usable = 0;
try
{
await _data.FlushAsync().ConfigureAwait(false);
var pending = await _data.PendingAuctionIdsAsync().ConfigureAwait(false);
if (pending.Count == 0)
{
_fullStudyPending = false;
progress?.Report(new ProgressStep(0, 0, "nessuna asta da studiare: l'archivio è già tutto appreso"));
return (0, 0);
}
var sw = Stopwatch.StartNew();
_log?.Info("APPRENDIMENTO", budget is { } b
? $"{pending.Count:N0} aste da studiare, al massimo {b.TotalSeconds:N0} s per questo avvio"
: $"{pending.Count:N0} aste da studiare");
foreach (var id in pending)
{
if (budget is { } limit && sw.Elapsed > limit) break;
ct.ThrowIfCancellationRequested();
if (await IngestAuctionAsync(id).ConfigureAwait(false)) usable++;
done++;
Save();
if (done % 10 == 0 || done == pending.Count)
progress?.Report(new ProgressStep(done, pending.Count, $"{usable:N0} utilizzabili, {ModelUpdates:N0} esempi"));
}
Save(force: true);
if (done == pending.Count) _fullStudyPending = false;
_log?.Info("APPRENDIMENTO", $"Studiate {done:N0} aste ({usable:N0} utilizzabili) in {sw.Elapsed.TotalSeconds:N0} s; " +
(done < pending.Count ? $"ne restano {pending.Count - done:N0}" : "archivio completo"));
return (done, usable);
}
catch (OperationCanceledException)
{
Save(force: true);
_log?.Info("APPRENDIMENTO", $"Studio interrotto dopo {done:N0} aste ({usable:N0} utilizzabili)");
throw;
}
finally
{
_studying = false;
}
}
/// <summary>Impara da un'asta e la marca come appresa. True se era utilizzabile.</summary>
private async Task<bool> IngestAuctionAsync(string auctionId)
{
var session = await _data.LoadSessionAsync(auctionId, null).ConfigureAwait(false);
var usable = false;
lock (_sync)
{
if (session is { IsUsable: true })
{
foreach (var (ctx, unanswered, _) in TrainingReader.Examples(session, TypicalCloseRatioUnlocked))
{
var x = BidFeatures.Build(ctx);
var y = unanswered ? 1.0 : 0.0;
var eL = _model.PredictCalibrated(x) - y;
var eN = _challenger.PredictCalibrated(x) - y;
var k = 1.0 / Math.Min(BrierWindow, _brierSamples + 1);
_brierLogit = double.IsNaN(_brierLogit) ? eL * eL : _brierLogit + k * (eL * eL - _brierLogit);
_brierNet = double.IsNaN(_brierNet) ? eN * eN : _brierNet + k * (eN * eN - _brierNet);
_brierSamples++;
_model.Update(x, unanswered);
_challenger.Update(x, unanswered);
}
_learned++;
usable = true;
}
}
_data.MarkLearned(auctionId);
return usable;
}
private async Task<int> LearnBanditAsync(ThompsonBandit bandit, string auctionId)
{
var rows = await _data.DecisionOutcomesAsync(auctionId).ConfigureAwait(false);
foreach (var (key, outcome) in rows) bandit.Observe(key, ShadowReport.Unanswered(outcome));
return rows.Count;
}
// ── Chiusura di un'asta ──────────────────────────────────────────────
/// <summary>
/// Da chiamare a registrazione completata: aggiorna profilo, previsioni, modello, bandit,
/// correzione, scrive il motivo e salva. Restituisce una riga breve per il registro.
/// </summary>
public async Task<string?> OnAuctionClosedAsync(ClosedAuctionInfo closed)
{
lock (_sync)
{
if (!_closedSeen.Add(closed.AuctionId)) return null;
if (_closedSeen.Count > 10_000) _closedSeen.Clear();
}
await _data.FlushAsync().ConfigureAwait(false);
if (await _data.IsLearnedAsync(closed.AuctionId).ConfigureAwait(false)) return "già appresa";
lock (_sync)
{
ObserveClosed(_profile, _forecast, closed.ProductKey, closed.EndedAtUtc, closed.FinalPrice, closed.BuyNow, closed.MarketValue,
closed.WinnerBidsPaid, closed.WinnerBidsFree, closed.ObservedMinutes);
}
var learned = await IngestAuctionAsync(closed.AuctionId).ConfigureAwait(false);
int decisions;
ThompsonBandit bandit;
lock (_sync) bandit = _bandit;
decisions = await LearnBanditAsync(bandit, closed.AuctionId).ConfigureAwait(false);
var own = await _data.OwnBidOutcomesAsync(closed.AuctionId).ConfigureAwait(false);
lock (_sync)
{
foreach (var (p, outcome) in own)
{
_ownPredicted += p;
_ownObserved += outcome == "won" ? 1 : 0;
_ownBids++;
}
}
string? reason = null;
try
{
var decisionRows = await _data.DecisionsForReasonAsync(closed.AuctionId).ConfigureAwait(false);
var myBids = await _data.MyBidsForReasonAsync(closed.AuctionId).ConfigureAwait(false);
reason = LossReasons.Compute(decisionRows, myBids, closed.WonByMe, closed.Winner);
_data.WriteLossReason(closed.AuctionId, reason);
}
catch (Exception ex)
{
_log?.Warn("APPRENDIMENTO", $"Motivo non scritto per '{closed.Name}': {ex.Message}");
}
Save(force: true);
var parts = new List<string> { learned ? $"il modello ha imparato ({AuctionsLearned:N0} aste)" : "puntate non utilizzabili per il modello" };
if (decisions > 0) parts.Add($"{decisions} decisioni con esito");
if (own.Count > 0) parts.Add($"correzione mie puntate {OwnBidFactor:N2}");
if (reason != null) parts.Add(reason);
return string.Join("; ", parts);
}
// ── Operazioni dalla scheda ──────────────────────────────────────────
public async Task<(int Auctions, long Observations)> RebuildBanditAsync(IProgress<ProgressStep>? progress, CancellationToken ct)
{
await _data.FlushAsync().ConfigureAwait(false);
var ids = await _data.AuctionsWithDecisionOutcomesAsync().ConfigureAwait(false);
var fresh = new ThompsonBandit();
var done = 0;
foreach (var id in ids)
{
ct.ThrowIfCancellationRequested();
await LearnBanditAsync(fresh, id).ConfigureAwait(false);
if (++done % 20 == 0 || done == ids.Count) progress?.Report(new ProgressStep(done, ids.Count, $"{fresh.Observations:N0} osservazioni"));
}
lock (_sync) _bandit = fresh;
Save(force: true);
_log?.Info("APPRENDIMENTO", $"Bandit rifatto dalle decisioni registrate: {ids.Count:N0} aste, {fresh.Observations:N0} osservazioni");
return (ids.Count, fresh.Observations);
}
public void ResetChallenger()
{
lock (_sync)
{
_challenger = NewChallenger();
_brierLogit = double.NaN; _brierNet = double.NaN; _brierSamples = 0;
}
Save(force: true);
_log?.Info("APPRENDIMENTO", "Sfidante azzerato: la rete riparte da zero e il confronto ricomincia");
}
public void ResetCalibration()
{
lock (_sync) _model.ResetCalibration();
Save(force: true);
_log?.Info("APPRENDIMENTO", "Calibrazione azzerata: il fattore torna a 1 finché non si rimisura");
}
/// <summary>
/// Dimentica tutto: modello, sfidante, bandit, profilo, previsioni, correzione, contatore;
/// smarca le aste come non apprese (poi «Studia adesso» le ristudia).
/// </summary>
public async Task ForgetAsync()
{
lock (_sync)
{
_closedSeen.Clear();
_model = new OnlineLogit(BidFeatures.Size);
_challenger = NewChallenger();
_bandit = new ThompsonBandit();
_profile = new AuctionProfileStats();
_forecast = new AuctionForecast();
_learned = 0;
_brierLogit = double.NaN; _brierNet = double.NaN; _brierSamples = 0;
_ownPredicted = 0; _ownObserved = 0; _ownBids = 0;
}
lock (_decisions) _decisions.Clear();
_docs.DeletePrefix(_prefix);
_docs.Set(Key("features-version"), JsonSerializer.Serialize(new { version = BidFeatures.Version }));
await _data.MarkAllUnlearnedAsync().ConfigureAwait(false);
_fullStudyPending = await _data.PendingCountAsync().ConfigureAwait(false) > 0;
await RebuildProfileAsync(null, CancellationToken.None).ConfigureAwait(false);
}
public async Task<LearningEvaluator.Report> EvaluateAsync(int maxAuctions, string? me, Action<string>? progress, CancellationToken ct)
{
var report = await LearningEvaluator.RunAsync(_data, maxAuctions, me, progress, ct).ConfigureAwait(false);
_docs.Set(Key("evaluation"), JsonSerializer.Serialize(new { at = DateTime.UtcNow, text = report.Text }));
return report;
}
public string? LastEvaluation()
{
var o = ReadObject(Key("evaluation"));
return o is { } e && e.TryGetProperty("text", out var t) ? t.GetString() : null;
}
/// <summary>Solo per i test: imposta la correzione sulle mie puntate.</summary>
internal void SetOwnBidsForTests(int bids, double predicted, double observed)
{
lock (_sync) { _ownBids = bids; _ownPredicted = predicted; _ownObserved = observed; }
}
/// <summary>Solo per i test: imposta il numero di aste studiate.</summary>
internal void SetLearnedForTests(int learned)
{
lock (_sync) _learned = learned;
}
}
+167
View File
@@ -0,0 +1,167 @@
namespace BidooBidBot.Ml;
/// <summary>
/// Perché un'asta è andata come è andata, in una riga (portato dal legacy). Si scrive alla
/// chiusura in <c>auctions.loss_reason</c> e si legge nello Storico («Perché») e in
/// Apprendimento («Perché perdo»). Pura: lavora su righe già lette.
/// </summary>
public static class LossReasons
{
/// <summary>I codici brevi con cui il motore marca ogni decisione (<c>bot_decisions.kind</c>).</summary>
public static class Kind
{
public const string Punta = "punta";
public const string Esplora = "esplora";
public const string EvNegativo = "ev-negativo";
public const string NonPronto = "non-pronto";
public const string SenzaStima = "senza-stima";
public const string PrezzoMassimo = "prezzo-max";
public const string PuntateAsta = "puntate-asta";
public const string PuntateResidue = "puntate-residue";
public const string PuntateSessione = "puntate-sessione";
public const string FasciaOraria = "fascia-oraria";
public const string Rischio = "rischio";
public const string SoloLimiti = "solo-limiti";
public const string InTesta = "in-testa";
public const string Cooldown = "cooldown";
public const string NonAperta = "non-aperta";
public const string Manuale = "manuale";
}
/// <summary>Il tipo di decisione per il CSV (Appendice H della specifica).</summary>
public static string CsvKind(string? kind) => kind switch
{
Kind.Punta => "Punta",
Kind.Esplora => "Esplora",
Kind.Rischio => "Rischio",
Kind.FasciaOraria => "FasciaOraria",
Kind.PuntateAsta => "PuntateAsta",
Kind.PuntateSessione => "PuntateSessione",
Kind.PrezzoMassimo => "PrezzoMax",
Kind.PuntateResidue => "Soglia",
Kind.SoloLimiti => "SoloLimiti",
Kind.SenzaStima => "SenzaStima",
Kind.NonPronto => "NonPronto",
_ => "No"
};
public static string Describe(string? kind) => kind switch
{
Kind.Punta => "ha puntato",
Kind.Esplora => "ha puntato per esplorare",
Kind.EvNegativo => "il modello sconsigliava",
Kind.NonPronto => "modello non ancora pronto",
Kind.SenzaStima => "nessuna stima disponibile",
Kind.PrezzoMassimo => "prezzo oltre il massimo",
Kind.PuntateAsta => "limite di puntate per asta raggiunto",
Kind.PuntateResidue => "puntate residue sotto la soglia",
Kind.PuntateSessione => "limite di puntate per sessione raggiunto",
Kind.FasciaOraria => "fascia oraria sospesa",
Kind.Rischio => "fermata dal gestore del rischio",
Kind.SoloLimiti => "apprendimento spento: solo paletti",
Kind.InTesta => "era già in testa",
Kind.Cooldown => "puntata appena fatta",
Kind.NonAperta => "asta non aperta",
Kind.Manuale => "puntata a mano",
null or "" => "nessuna decisione registrata",
_ => kind
};
/// <summary>Una decisione registrata, com'è servita qui.</summary>
public sealed record DecisionRow(string Action, string? Kind, double? PWin, bool Shadow, string? Outcome);
/// <summary>Una mia puntata riuscita con la sua risposta.</summary>
public sealed record MyBidRow(double Price, double? AnsweredAfterS, string? AnsweredBy, string? AnsweredType, bool? Unanswered);
public static string Compute(IReadOnlyList<DecisionRow> allDecisions, IReadOnlyList<MyBidRow> myBids, bool wonByMe, string? winner)
{
if (wonByMe) return "vinta";
var who = string.IsNullOrEmpty(winner) ? "nessuno" : winner;
var live = allDecisions.Where(d => !d.Shadow).ToList();
if (live.Count == 0 && myBids.Count == 0)
{
var shadow = allDecisions.Where(d => d.Shadow).ToList();
if (shadow.Count == 0) return "solo osservata: nessuna decisione registrata";
var wouldBid = shadow.Where(d => d.Action == "BID").ToList();
if (wouldBid.Count == 0) return NeverBid(shadow, who);
var last = wouldBid[^1];
var fate = last.Outcome is "would_win" or "won" ? "l'ultima sarebbe rimasta senza risposta" : "l'ultima sarebbe stata coperta";
return $"in Osserva avrebbe puntato {wouldBid.Count} volte; {fate}; vinta da {who}";
}
if (myBids.Count == 0) return NeverBid(live, who);
var lastBid = myBids[^1];
var text = myBids.Count == 1 ? "puntato 1 volta" : $"puntato {myBids.Count} volte";
if (lastBid.Unanswered == true)
return $"{text}: l'ultima è rimasta senza risposta ma l'asta risulta vinta da {who}";
if (!string.IsNullOrEmpty(lastBid.AnsweredBy))
{
var when = lastBid.AnsweredAfterS is { } s ? $" dopo {s:F0} s" : "";
var how = lastBid.AnsweredType == "Auto" ? " (autopuntata)" : lastBid.AnsweredType == "Manuale" ? " (a mano)" : "";
text += $"; l'ultima coperta da {lastBid.AnsweredBy}{how}{when}";
}
else text += "; l'ultima coperta";
var lastNoOp = live.LastOrDefault(d => d.Action != "BID");
var lastBidDecision = live.LastOrDefault(d => d.Action == "BID");
if (lastNoOp != null && (lastBidDecision == null || live.IndexOf(lastNoOp) > live.IndexOf(lastBidDecision)))
text += $"; poi fermato: {Describe(lastNoOp.Kind)}";
else
text += "; poi l'asta è finita senza tornare al nostro anticipo";
return $"{text}; vinta da {who}";
}
private static string NeverBid(List<DecisionRow> decisions, string who)
{
var kinds = decisions.Where(d => d.Action != "BID").Select(d => d.Kind ?? "").ToList();
if (kinds.Count == 0) return $"mai puntato: decisioni registrate senza motivo; vinta da {who}";
var top = kinds.GroupBy(k => k).OrderByDescending(g => g.Count()).ThenByDescending(g => kinds.LastIndexOf(g.Key)).First();
var mean = decisions.Where(d => d.PWin is > 0).Select(d => d.PWin!.Value).DefaultIfEmpty(0).Average();
var extra = top.Key == Kind.EvNegativo && mean > 0 ? $" (P media {mean:P2})" : "";
// Il modello che sconsiglia è «mai puntato»; un paletto dell'utente o il rischio è «fermato».
var head = IsModelKind(top.Key) ? "mai puntato" : "fermato";
return $"{head}: {Describe(top.Key)}{extra} in {top.Count()} decisioni su {decisions.Count}; vinta da {who}";
}
private static bool IsModelKind(string kind) =>
kind is Kind.EvNegativo or Kind.NonPronto or Kind.SenzaStima or Kind.Punta or Kind.Esplora or "";
/// <summary>
/// La famiglia di un motivo, per «Perché perdo»: la parte prima del punto e virgola senza
/// i numeri. Famiglie: «mai puntato: il modello sconsigliava», «fermato: paletto X»,
/// «puntato e coperto (dall'autopuntata)», «in Osserva avrebbe puntato», «vinta».
/// </summary>
public static string Group(string? reason)
{
if (string.IsNullOrWhiteSpace(reason)) return "sconosciuto";
if (reason == "vinta") return "vinta";
var parts = reason.Split(';').Select(p => p.Trim()).ToList();
var head = parts[0];
var paren = head.IndexOf(" (", StringComparison.Ordinal);
if (paren > 0) head = head[..paren];
var inN = head.IndexOf(" in ", StringComparison.Ordinal);
if (inN > 0 && (head.StartsWith("mai puntato", StringComparison.Ordinal) || head.StartsWith("fermato", StringComparison.Ordinal)))
head = head[..inN];
if (head.StartsWith("puntato", StringComparison.Ordinal))
{
var second = parts.Count > 1 ? parts[1] : "";
return second.StartsWith("l'ultima coperta", StringComparison.Ordinal)
? "puntato e coperto" + (second.Contains("(autopuntata)", StringComparison.Ordinal) ? " dall'autopuntata" : "")
: "puntato";
}
if (head.StartsWith("in Osserva avrebbe puntato", StringComparison.Ordinal)) return "in Osserva avrebbe puntato";
return head.Trim();
}
}
+273
View File
@@ -0,0 +1,273 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace BidooBidBot.Ml;
/// <summary>
/// Una rete neurale densa (MLP) in C# puro: strati completamente connessi, ReLU
/// nascosti, uscita lineare, ottimizzatore Adam, regolarizzazione L2. Niente librerie
/// (portata dal legacy).
///
/// <para><b>A cosa serve qui.</b> È lo <i>sfidante</i> del modello logistico per
/// P(senza risposta): stesse variabili, stessi esempi, ma può imparare le interazioni fra
/// fasce che un modello lineare non vede (un ciclo lungo vale cose diverse alle 12 e a
/// mezzanotte). La valutazione prequenziale decide chi comanda: il modello che ha il
/// punteggio di Brier più basso sulle aste recenti.</para>
///
/// <para><b>Perché piccola.</b> Le variabili sono 86 indicatori a fasce; una rete
/// 86→32→16→1 ha circa tremila pesi e si addestra online, un esempio
/// alla volta, in microsecondi. Più grande non imparerebbe di più da questi dati:
/// li memorizzerebbe.</para>
///
/// <para>La calibrazione in linea è la stessa del modello logistico: il rapporto
/// osservato/previsto sugli ultimi esempi corregge la scala, perché il mercato
/// deriva e una rete addestrata su ieri sovrastima oggi.</para>
/// </summary>
public sealed class NeuralNet
{
private readonly int[] _sizes;
private readonly double[][] _w; // per strato: [out * in]
private readonly double[][] _b; // per strato: [out]
private readonly double[][] _mw, _vw, _mb, _vb; // momenti di Adam
private long _t;
// Attivazioni dell'ultimo passaggio in avanti, per la retropropagazione.
private readonly double[][] _a; // _a[0] = ingresso, _a[L] = uscita (lineare)
private readonly double[][] _z; // pre-attivazioni
public double LearningRate { get; set; } = 0.001;
public double L2 { get; set; } = 1e-5;
public double Beta1 { get; set; } = 0.9;
public double Beta2 { get; set; } = 0.999;
public long Updates { get; private set; }
// ── Calibrazione in linea (come OnlineLogit) ─────────────────────
private double _observedEma;
private double _predictedEma;
private const double CalibrationWindow = 20_000;
/// <summary>Fattore che riporta la scala delle probabilità a quella osservata di recente.</summary>
public double CalibrationFactor =>
_predictedEma > 1e-9 && Updates > 200 ? Math.Clamp(_observedEma / _predictedEma, 0.25, 4.0) : 1.0;
public int InputSize => _sizes[0];
public int OutputSize => _sizes[^1];
public IReadOnlyList<int> Sizes => _sizes;
public NeuralNet(int[] layerSizes, int seed = 42)
{
if (layerSizes == null || layerSizes.Length < 2) throw new ArgumentException("servono almeno ingresso e uscita");
_sizes = (int[])layerSizes.Clone();
var layers = _sizes.Length - 1;
_w = new double[layers][]; _b = new double[layers][];
_mw = new double[layers][]; _vw = new double[layers][];
_mb = new double[layers][]; _vb = new double[layers][];
_a = new double[_sizes.Length][];
_z = new double[_sizes.Length][];
var rng = new Random(seed);
for (var l = 0; l < layers; l++)
{
int nin = _sizes[l], nout = _sizes[l + 1];
_w[l] = new double[nout * nin];
_b[l] = new double[nout];
_mw[l] = new double[nout * nin]; _vw[l] = new double[nout * nin];
_mb[l] = new double[nout]; _vb[l] = new double[nout];
// Inizializzazione di He: adatta alla ReLU, tiene la varianza stabile in profondità.
var scale = Math.Sqrt(2.0 / nin);
for (var i = 0; i < _w[l].Length; i++) _w[l][i] = Gaussian(rng) * scale;
}
for (var l = 0; l < _sizes.Length; l++) { _a[l] = new double[_sizes[l]]; _z[l] = new double[_sizes[l]]; }
}
private static double Gaussian(Random rng)
{
var u1 = 1.0 - rng.NextDouble();
var u2 = rng.NextDouble();
return Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Cos(2.0 * Math.PI * u2);
}
// ── In avanti ────────────────────────────────────────────────────
/// <summary>Uscita lineare della rete (senza sigmoide).</summary>
public double[] Forward(double[] x)
{
if (x.Length != _sizes[0]) throw new ArgumentException($"ingresso di {x.Length} valori, attesi {_sizes[0]}");
Array.Copy(x, _a[0], x.Length);
var layers = _sizes.Length - 1;
for (var l = 0; l < layers; l++)
{
int nin = _sizes[l], nout = _sizes[l + 1];
var w = _w[l]; var b = _b[l]; var ain = _a[l]; var z = _z[l + 1]; var aout = _a[l + 1];
for (var o = 0; o < nout; o++)
{
var sum = b[o];
var row = o * nin;
for (var i = 0; i < nin; i++) sum += w[row + i] * ain[i];
z[o] = sum;
aout[o] = l == layers - 1 ? sum : Math.Max(0, sum); // ReLU nascosti, uscita lineare
}
}
return (double[])_a[layers].Clone();
}
public static double Sigmoid(double z) => z >= 0 ? 1.0 / (1.0 + Math.Exp(-z)) : Math.Exp(z) / (1.0 + Math.Exp(z));
/// <summary>Probabilità grezza (rete a una uscita, perdita logistica).</summary>
public double Predict(double[] x) => Sigmoid(Forward(x)[0]);
/// <summary>Probabilità con la scala corretta dalla calibrazione in linea.</summary>
public double PredictCalibrated(double[] x) => Math.Clamp(Predict(x) * CalibrationFactor, 1e-6, 1 - 1e-6);
// ── Addestramento ────────────────────────────────────────────────
/// <summary>
/// Un passo online con perdita logistica su un'uscita sola: è il caso
/// «P(senza risposta)». Il gradiente sull'uscita lineare è semplicemente p − y.
/// </summary>
public void Update(double[] x, bool y)
{
var p = Predict(x);
var target = y ? 1.0 : 0.0;
// Calibrazione: media mobile di osservato e previsto.
var k = Math.Min(1.0, 1.0 / Math.Min(CalibrationWindow, Math.Max(1, Updates + 1)));
_observedEma += k * (target - _observedEma);
_predictedEma += k * (p - _predictedEma);
Backward(new[] { p - target });
}
/// <summary>Un passo con perdita quadratica su tutte le uscite (regressione, funzione Q).</summary>
public double UpdateRegression(double[] x, double[] target)
{
var y = Forward(x);
var grad = new double[y.Length];
var loss = 0.0;
for (var i = 0; i < y.Length; i++)
{
grad[i] = y[i] - target[i];
loss += 0.5 * grad[i] * grad[i];
}
Backward(grad);
return loss;
}
/// <summary>
/// Come <see cref="UpdateRegression"/> ma aggiorna una sola uscita (l'azione
/// scelta): è ciò che serve al Q-learning, dove il bersaglio esiste solo per
/// l'azione presa.
/// </summary>
public double UpdateOutput(double[] x, int output, double target)
{
var y = Forward(x);
var grad = new double[y.Length];
grad[output] = y[output] - target;
Backward(grad);
return 0.5 * grad[output] * grad[output];
}
/// <summary>Retropropagazione dal gradiente sull'uscita lineare, con passo di Adam.</summary>
private void Backward(double[] gradOut)
{
var layers = _sizes.Length - 1;
var delta = (double[])gradOut.Clone();
_t++;
Updates++;
var lrT = LearningRate * Math.Sqrt(1 - Math.Pow(Beta2, _t)) / (1 - Math.Pow(Beta1, _t));
for (var l = layers - 1; l >= 0; l--)
{
int nin = _sizes[l], nout = _sizes[l + 1];
var w = _w[l]; var b = _b[l]; var ain = _a[l];
var prevDelta = l > 0 ? new double[nin] : null;
for (var o = 0; o < nout; o++)
{
var d = delta[o];
var row = o * nin;
// gradiente rispetto all'ingresso di questo strato (per lo strato sotto)
if (prevDelta != null)
for (var i = 0; i < nin; i++) prevDelta[i] += w[row + i] * d;
// Adam sui pesi
for (var i = 0; i < nin; i++)
{
var g = d * ain[i] + L2 * w[row + i];
var idx = row + i;
_mw[l][idx] = Beta1 * _mw[l][idx] + (1 - Beta1) * g;
_vw[l][idx] = Beta2 * _vw[l][idx] + (1 - Beta2) * g * g;
w[idx] -= lrT * _mw[l][idx] / (Math.Sqrt(_vw[l][idx]) + 1e-8);
}
_mb[l][o] = Beta1 * _mb[l][o] + (1 - Beta1) * d;
_vb[l][o] = Beta2 * _vb[l][o] + (1 - Beta2) * d * d;
b[o] -= lrT * _mb[l][o] / (Math.Sqrt(_vb[l][o]) + 1e-8);
}
if (prevDelta != null)
{
// derivata della ReLU: passa solo dove la pre-attivazione era positiva
for (var i = 0; i < nin; i++) if (_z[l][i] <= 0) prevDelta[i] = 0;
delta = prevDelta;
}
}
}
// ── Persistenza ──────────────────────────────────────────────────
private sealed class Snapshot
{
public int[] Sizes { get; set; } = Array.Empty<int>();
public double[][] W { get; set; } = Array.Empty<double[]>();
public double[][] B { get; set; } = Array.Empty<double[]>();
public long Updates { get; set; }
public double ObservedEma { get; set; }
public double PredictedEma { get; set; }
}
public string ToJson() => JsonSerializer.Serialize(new Snapshot
{
Sizes = _sizes, W = _w, B = _b, Updates = Updates, ObservedEma = _observedEma, PredictedEma = _predictedEma
});
/// <summary>
/// Ricarica i pesi. Passo, L2 e momenti di Adam NON si rileggono: i primi sono
/// parametri del codice, i momenti ripartono da zero (un breve riscaldamento).
/// Se la forma salvata non coincide con quella richiesta, si riparte da capo.
/// </summary>
public static NeuralNet FromJson(string json, int[] expectedSizes, int seed = 42)
{
var fresh = new NeuralNet(expectedSizes, seed);
try
{
var s = JsonSerializer.Deserialize<Snapshot>(json);
if (s == null || !s.Sizes.SequenceEqual(expectedSizes)) return fresh;
for (var l = 0; l < fresh._w.Length; l++)
{
if (s.W[l].Length != fresh._w[l].Length || s.B[l].Length != fresh._b[l].Length) return new NeuralNet(expectedSizes, seed);
Array.Copy(s.W[l], fresh._w[l], s.W[l].Length);
Array.Copy(s.B[l], fresh._b[l], s.B[l].Length);
}
fresh.Updates = s.Updates;
fresh._observedEma = s.ObservedEma;
fresh._predictedEma = s.PredictedEma;
return fresh;
}
catch
{
return fresh;
}
}
}
+238
View File
@@ -0,0 +1,238 @@
using System;
using System.Text.Json;
namespace BidooBidBot.Ml;
/// <summary>
/// Regressione logistica che impara un esempio alla volta.
///
/// <para><b>Perché proprio questa.</b> È il modello più semplice che dia una
/// <i>probabilità calibrata</i>, e la calibrazione qui non è un lusso: il numero che
/// esce entra in una formula di valore atteso, moltiplicato per euro. Un modello che
/// ordinasse bene le puntate ma sbagliasse la scala direbbe di puntare quando non
/// conviene. Si aggiorna con un passo di discesa del gradiente per esempio, senza
/// bisogno di tenere i dati: è quello che serve a un motore che deve migliorare a ogni
/// asta chiusa, senza riaddestrarsi da capo.</para>
///
/// <para><b>Nessuna libreria.</b> Sono trenta righe di aritmetica: un prodotto scalare,
/// una sigmoide, un aggiornamento dei pesi. Portarsi dietro una dipendenza per questo
/// sarebbe più codice, non meno.</para>
///
/// <para><b>Sbilanciamento delle classi.</b> Le puntate senza risposta sono una su
/// quattrocento. Non si riequilibra apposta: pesare di più i positivi gonfierebbe le
/// probabilità, e sarebbero poi confrontate con costi veri. Si lascia che il modello
/// impari la scala vera, e si accetta che serva più materiale.</para>
/// </summary>
public sealed class OnlineLogit
{
/// <summary>Pesi delle variabili; l'ultimo elemento è l'intercetta.</summary>
public double[] Weights { get; private set; }
/// <summary>
/// Media mobile dei pesi, usata per prevedere quando <see cref="UseAveraging"/> è acceso.
///
/// <para>Con un passo costante i pesi oscillano attorno al punto buono: ogni esempio
/// li strattona un po' nella sua direzione, e l'ultimo esempio di ogni asta è sempre
/// il positivo. Prevedere con la media degli ultimi qualche migliaio di passi toglie
/// l'oscillazione senza fermare l'apprendimento: i pesi vivi continuano a muoversi,
/// la media li segue con calma.</para>
/// </summary>
public double[] AveragedWeights { get; private set; }
/// <summary>
/// Prevedere con la media dei pesi invece che con i pesi vivi. Spento di serie:
/// sui dossier veri non ha migliorato né separazione né scala, e la calibrazione
/// in linea fa il lavoro che ci si aspettava dalla media.
/// </summary>
public bool UseAveraging { get; set; } = false;
/// <summary>Quanti passi «pesa» la media mobile: 2000 sono circa otto aste.</summary>
public int AveragingWindow { get; set; } = 2000;
/// <summary>Quanti esempi hanno aggiornato i pesi finora.</summary>
public long Updates { get; private set; }
// ── Calibrazione in linea ────────────────────────────────────────
//
// Sui dossier veri il modello separa bene ma la scala deriva: addestrato sui
// vecchi e giudicato sui nuovi sovrastima di 1,5-1,8 volte, e il mercato cambia
// davvero fra un mese e l'altro. Si tiene quindi il rapporto fra esiti osservati e
// probabilità previste sugli ultimi esempi, e si scala la previsione con quello. È
// il modo più semplice di restare nella scala giusta mentre il mondo si muove, e
// non richiede nessun dato in più di quelli che già passano di qui.
private double _emaObserved;
private double _emaPredicted;
/// <summary>Su quanti esempi si misura il rapporto: 20000 sono circa ottanta aste.</summary>
public int CalibrationWindow { get; set; } = 20000;
/// <summary>
/// Osservato / previsto sugli ultimi esempi, limitato fra ¼ e 4. Uno = scala giusta.
/// </summary>
public double CalibrationFactor
{
get
{
if (Updates < 2000 || _emaPredicted <= 0) return 1.0;
return Math.Clamp(_emaObserved / _emaPredicted, 0.25, 4.0);
}
}
/// <summary>Dimentica la misura recente: il fattore torna a 1 finché non si rimisura.</summary>
public void ResetCalibration()
{
_emaObserved = 0;
_emaPredicted = 0;
}
/// <summary>Probabilità riportata nella scala osservata di recente.</summary>
public double PredictCalibrated(ReadOnlySpan<double> x) =>
Math.Clamp(Predict(x) * CalibrationFactor, 0.0, 1.0);
/// <summary>
/// Passo di apprendimento. Costante, non decrescente: il mercato cambia — nuovi
/// utenti, nuove abitudini — e un passo che tende a zero smetterebbe di seguirlo.
/// </summary>
public double LearningRate { get; set; } = 0.01;
/// <summary>
/// Regolarizzazione: tiene i pesi piccoli quando una variabile ha pochi esempi.
/// Serve soprattutto per i prodotti rari, che altrimenti farebbero oscillare tutto.
/// </summary>
public double L2 { get; set; } = 1e-4;
public int FeatureCount => Weights.Length - 1;
public OnlineLogit(int featureCount)
{
if (featureCount <= 0) throw new ArgumentOutOfRangeException(nameof(featureCount));
Weights = new double[featureCount + 1];
AveragedWeights = new double[featureCount + 1];
}
private OnlineLogit(double[] weights, double[] averaged, long updates)
{
Weights = weights;
AveragedWeights = averaged;
Updates = updates;
}
/// <summary>Probabilità dell'esito positivo per queste variabili.</summary>
public double Predict(ReadOnlySpan<double> x)
{
if (x.Length != FeatureCount)
throw new ArgumentException($"attese {FeatureCount} variabili, ricevute {x.Length}");
// Nei primissimi passi la media è ancora vicina a zero: si usano i pesi vivi.
var w = UseAveraging && Updates >= 200 ? AveragedWeights : Weights;
return Sigmoid(Dot(w, x));
}
/// <summary>Un passo di apprendimento su un esempio con la sua etichetta.</summary>
public void Update(ReadOnlySpan<double> x, bool positive)
{
var p = Sigmoid(Dot(Weights, x)); // il gradiente usa i pesi vivi, sempre
var err = (positive ? 1.0 : 0.0) - p;
// La calibrazione si misura sulla previsione fatta PRIMA di imparare da questo
// esempio: è quella che il motore avrebbe usato.
var beta = 1.0 / Math.Min(Updates + 1, Math.Max(1, CalibrationWindow));
_emaObserved += ((positive ? 1.0 : 0.0) - _emaObserved) * beta;
_emaPredicted += (Predict(x) - _emaPredicted) * beta;
var w = Weights;
var lr = LearningRate;
for (var i = 0; i < x.Length; i++)
{
if (x[i] == 0) continue; // le variabili a zero non muovono niente
w[i] += lr * (err * x[i] - L2 * w[i]);
}
w[^1] += lr * err; // intercetta: senza regolarizzazione, deve poter valere quanto serve
Updates++;
// Media mobile esponenziale: nei primi passi segue da vicino (così non parte
// da zero), poi si assesta sulla finestra scelta.
var betaMedia = 1.0 / Math.Min(Updates, Math.Max(1, AveragingWindow));
var a = AveragedWeights;
for (var i = 0; i < a.Length; i++) a[i] += (w[i] - a[i]) * betaMedia;
}
private static double Dot(double[] w, ReadOnlySpan<double> x)
{
var s = w[^1];
for (var i = 0; i < x.Length; i++) s += w[i] * x[i];
return s;
}
private static double Sigmoid(double z)
{
// Oltre ±30 la sigmoide è già 0 o 1 in doppia precisione: si evita l'overflow.
if (z > 30) return 1.0;
if (z < -30) return 0.0;
return 1.0 / (1.0 + Math.Exp(-z));
}
// ── Persistenza ──────────────────────────────────────────────────
private sealed class Snapshot
{
public int Version { get; set; } = 2;
public double[] Weights { get; set; } = Array.Empty<double>();
public double[]? AveragedWeights { get; set; }
public long Updates { get; set; }
public double LearningRate { get; set; }
public double L2 { get; set; }
public bool UseAveraging { get; set; } = false;
public int AveragingWindow { get; set; } = 2000;
public double EmaObserved { get; set; }
public double EmaPredicted { get; set; }
public int CalibrationWindow { get; set; } = 20000;
}
public string ToJson() => JsonSerializer.Serialize(new Snapshot
{
Weights = Weights,
AveragedWeights = AveragedWeights,
Updates = Updates,
LearningRate = LearningRate,
L2 = L2,
UseAveraging = UseAveraging,
AveragingWindow = AveragingWindow,
EmaObserved = _emaObserved,
EmaPredicted = _emaPredicted,
CalibrationWindow = CalibrationWindow
});
/// <summary>
/// Rilegge un modello salvato. Se il numero di variabili non coincide — perché le
/// variabili sono cambiate fra una versione e l'altra — si riparte da zero: pesi
/// riferiti a variabili diverse non sono un modello, sono rumore.
/// </summary>
public static OnlineLogit FromJson(string json, int expectedFeatureCount)
{
try
{
var s = JsonSerializer.Deserialize<Snapshot>(json);
if (s?.Weights != null && s.Weights.Length == expectedFeatureCount + 1)
{
var averaged = s.AveragedWeights != null && s.AveragedWeights.Length == s.Weights.Length
? s.AveragedWeights
: (double[])s.Weights.Clone();
// Si rileggono lo STATO appreso (pesi, conteggio, calibrazione) e non i
// parametri (passo, regolarizzazione, media): quelli sono scelte del
// codice, tarate sui dossier veri, e un cambio deve valere dal riavvio
// successivo — non restare inchiodato al valore di quando il file nacque.
return new OnlineLogit(s.Weights, averaged, s.Updates)
{
_emaObserved = s.EmaObserved,
_emaPredicted = s.EmaPredicted
};
}
}
catch (JsonException) { /* file illeggibile: si riparte */ }
return new OnlineLogit(expectedFeatureCount);
}
}
+121
View File
@@ -0,0 +1,121 @@
using System.Globalization;
using System.Text;
namespace BidooBidBot.Ml;
/// <summary>
/// Cosa avrebbero reso le decisioni registrate, policy per policy, con l'esito noto (portato
/// dal legacy). Ogni decisione ha un esito alla chiusura: se il prezzo non è più salito dopo
/// quell'istante, una puntata lì sarebbe stata l'ultima. È la valutazione off-policy più
/// onesta che i dati permettono, sempre confrontata con il null-model (ROI per puntata zero),
/// con l'avvertenza che una nostra puntata può cambiare il comportamento altrui.
/// </summary>
public static class ShadowReport
{
/// <summary>Una decisione con il suo esito e i numeri per contarla in euro.</summary>
public sealed record Row(string Action, string? AltAction, string Outcome, double? Ev, double Price, double Value, double Shipping, double BidCost, bool Shadow, bool Executed);
public sealed class PolicyStats
{
public string Name { get; init; } = "";
public int Decisions { get; set; }
public int Bids { get; set; }
public int Wins { get; set; }
public double Spent { get; set; }
public double Gained { get; set; }
public double ForecastEv { get; set; }
public List<double> PerBid { get; } = new();
public double Net => Gained - Spent;
public double RoiPerBid => Bids > 0 ? Net / Bids : 0;
/// <summary>Intervallo di confidenza al 95% del ROI per puntata; null con meno di due puntate.</summary>
public (double Low, double High)? Ci95
{
get
{
if (PerBid.Count < 2) return null;
var m = PerBid.Average();
var sd = Math.Sqrt(PerBid.Sum(x => (x - m) * (x - m)) / (PerBid.Count - 1));
var half = 1.96 * sd / Math.Sqrt(PerBid.Count);
return (m - half, m + half);
}
}
/// <summary>Il null-model è battuto solo se l'estremo inferiore sta sopra zero.</summary>
public bool BeatsNullModel => Ci95 is { Low: > 0 };
}
public sealed class Report
{
public int Days { get; init; }
public int WithOutcome { get; init; }
public int LiveBids { get; init; }
public int LiveWins { get; init; }
public List<PolicyStats> Policies { get; } = new();
public string Text { get; set; } = "";
}
public static bool Unanswered(string outcome) => outcome is "won" or "would_win" or "missed";
public static Report Compute(IReadOnlyList<Row> rows, double transactionFee, int days)
{
var acting = new PolicyStats { Name = "modello (in uso)" };
var alt = new PolicyStats { Name = "bandit Thompson (shadow)" };
var always = new PolicyStats { Name = "punta sempre" };
var never = new PolicyStats { Name = "non punta mai" };
int liveBids = 0, liveWins = 0;
foreach (var r in rows)
{
var unanswered = Unanswered(r.Outcome);
var gainIfWin = r.Value - (r.Price + Theory.PriceIncrement) - transactionFee - r.Shipping;
void Apply(PolicyStats s, bool bid, double? forecast)
{
s.Decisions++;
if (!bid) return;
s.Bids++;
s.Spent += r.BidCost;
if (forecast is { } f) s.ForecastEv += f;
if (unanswered)
{
s.Wins++;
s.Gained += gainIfWin;
s.PerBid.Add(gainIfWin - r.BidCost);
}
else s.PerBid.Add(-r.BidCost);
}
Apply(acting, r.Action == "BID", r.Ev);
Apply(alt, r.AltAction == "BID", null);
Apply(always, true, null);
Apply(never, false, null);
if (!r.Shadow && r.Executed)
{
liveBids++;
if (r.Outcome == "won") liveWins++;
}
}
var report = new Report { Days = days, WithOutcome = rows.Count, LiveBids = liveBids, LiveWins = liveWins };
report.Policies.AddRange(new[] { acting, alt, always, never });
report.Text = Format(report);
return report;
}
public static string Format(Report r)
{
var c = CultureInfo.GetCultureInfo("it-IT");
var sb = new StringBuilder();
sb.AppendLine($"Decisioni con esito negli ultimi {r.Days} giorni: {r.WithOutcome:N0}. Puntate dal vivo: {r.LiveBids:N0}, vincenti {r.LiveWins:N0}.");
foreach (var p in r.Policies)
{
var ci = p.Ci95 is { } x ? $"[{x.Low.ToString("+0.000;-0.000", c)}; {x.High.ToString("+0.000;-0.000", c)}]" : "n.d.";
sb.AppendLine($"{p.Name}: {p.Bids:N0} puntate, {p.Wins:N0} vincenti, netto {p.Net.ToString("0.00", c)} EUR, ROI/puntata {p.RoiPerBid.ToString("+0.000;-0.000", c)} EUR, IC95% {ci}");
}
sb.AppendLine("Il null-model teorico prevede ROI per puntata = 0: una policy lo batte solo se l'estremo inferiore dell'intervallo è sopra zero.");
return sb.ToString();
}
}
+122
View File
@@ -0,0 +1,122 @@
namespace BidooBidBot.Ml;
/// <summary>
/// Il modello matematico delle aste al centesimo, in formule esplicite (portato dal legacy).
///
/// <para><b>Il fatto da cui partire.</b> Augenblick (2016, <i>Review of Economic Studies</i>):
/// il margine medio del banco supera il 50% del valore del bene; il 75% dei puntatori
/// abbandona prima di 50 puntate. Platt, Price e Tappen (2013) e Hinnosaar (2016): in ogni
/// equilibrio che non finisce subito il profitto atteso di ogni puntata è <b>zero</b>. Un
/// vantaggio, se esiste, viene dall'irrazionalità altrui e va dimostrato contro questo
/// <i>null-model</i>.</para>
/// </summary>
public static class Theory
{
/// <summary>Incremento di prezzo per puntata su Bidoo: un centesimo.</summary>
public const double PriceIncrement = 0.01;
/// <summary>Profitto atteso per puntata nell'equilibrio teorico.</summary>
public const double NullModelProfitPerBid = 0.0;
/// <param name="PWin">Probabilità che, puntando adesso, nessuno rilanci prima della scadenza.</param>
/// <param name="Value">Valore reale V del bene.</param>
/// <param name="CurrentPrice">Prezzo corrente p.</param>
/// <param name="BidCost">Costo effettivo della puntata c.</param>
/// <param name="TransactionFee">Fee sulla vincita (~1 €).</param>
/// <param name="Shipping">Spedizione.</param>
/// <param name="ListPrice">«Compralo Ora» L, per la copertura. Null = nessuna copertura.</param>
/// <param name="BidsSpentEuro">Già speso in puntate su quest'asta.</param>
/// <param name="HedgeEnabled">La copertura «Compralo Ora» va considerata.</param>
public readonly record struct BidSituation(
double PWin, double Value, double CurrentPrice, double BidCost, double TransactionFee,
double Shipping, double? ListPrice, double BidsSpentEuro, bool HedgeEnabled);
/// <summary>
/// <c>EV = P · (V − (p + Δ) − fee − ship − c) − (1 − P) · c</c>: la puntata si paga in
/// entrambi i rami. Con la copertura «Compralo Ora» il costo nel ramo di sconfitta è c
/// finché <c>spese + c ≤ L − V</c>, poi zero.
/// </summary>
public static double BidExpectedValue(in BidSituation s)
{
var p = Math.Clamp(s.PWin, 0, 1);
var gainIfWin = s.Value - (s.CurrentPrice + PriceIncrement) - s.TransactionFee - s.Shipping - s.BidCost;
return p * gainIfWin - (1 - p) * LossBranchCost(s);
}
public static double LossBranchCost(in BidSituation s)
{
if (!s.HedgeEnabled || s.ListPrice is not > 0) return s.BidCost;
var boundedLoss = Math.Max(0, s.ListPrice.Value - s.Value);
return s.BidsSpentEuro + s.BidCost <= boundedLoss ? s.BidCost : 0;
}
public static bool ShouldBid(in BidSituation s) => BidExpectedValue(s) > 0;
/// <summary>La P minima perché la puntata abbia valore atteso nullo.</summary>
public static double BreakEvenPWin(in BidSituation s)
{
var gainIfWin = s.Value - (s.CurrentPrice + PriceIncrement) - s.TransactionFee - s.Shipping - s.BidCost;
var lossCost = LossBranchCost(s);
var denom = gainIfWin + lossCost;
if (denom <= 0) return 1;
return Math.Clamp(lossCost / denom, 0, 1);
}
/// <summary>Il rapporto critico V/c (Hinnosaar 2016).</summary>
public static double CriticalBidders(double value, double bidCost) =>
bidCost > 0 ? value / bidCost : double.PositiveInfinity;
public readonly record struct CycleObservation(double MinTimerSeconds, bool EndedAuction);
/// <summary>
/// Probabilità empirica che, arrivati a <paramref name="leadSeconds"/> senza puntate,
/// nessuno punti fino alla fine: sopravvivenza condizionata. Null senza abbastanza cicli.
/// </summary>
public static double? WinProbabilityAtLead(IEnumerable<CycleObservation> cycles, double leadSeconds, int minCycles = 20)
{
var reached = 0;
var survived = 0;
foreach (var c in cycles)
{
if (c.EndedAuction) { reached++; survived++; continue; }
if (c.MinTimerSeconds <= leadSeconds) reached++;
}
return reached >= minCycles ? (double)survived / reached : null;
}
/// <summary>Kaplan-Meier del ciclo: (profondità dalla scadenza, sopravvivenza).</summary>
public static List<(double TimerSeconds, double Survival)> KaplanMeier(IEnumerable<CycleObservation> cycles)
{
var obs = cycles.ToList();
var result = new List<(double, double)>();
if (obs.Count == 0) return result;
var events = obs.Where(c => !c.EndedAuction).GroupBy(c => Math.Round(c.MinTimerSeconds, 1))
.Select(g => (Timer: g.Key, Count: g.Count())).OrderByDescending(e => e.Timer).ToList();
var survival = 1.0;
var atRisk = obs.Count;
foreach (var (timer, count) in events)
{
if (atRisk <= 0) break;
survival *= 1.0 - (double)count / atRisk;
result.Add((timer, survival));
atRisk -= count;
}
return result;
}
/// <summary>Poisson: probabilità che nessuno punti nei prossimi τ secondi.</summary>
public static double NoBidProbability(double lambdaPerSecond, double tauSeconds) =>
lambdaPerSecond <= 0 || tauSeconds <= 0 ? 1.0 : Math.Exp(-lambdaPerSecond * tauSeconds);
public static double? ArrivalRate(IEnumerable<double> recentGapsSeconds)
{
var gaps = recentGapsSeconds.Where(g => g > 0).ToList();
return gaps.Count == 0 ? null : 1.0 / gaps.Average();
}
/// <summary>Profitto realizzato da una vincita: valore reale meno tutto ciò che è costata.</summary>
public static double RealizedWinProfit(double value, double finalPrice, double bidsSpentEuro, double transactionFee, double shipping) =>
value - finalPrice - bidsSpentEuro - transactionFee - shipping;
}
@@ -0,0 +1,209 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace BidooBidBot.Ml;
/// <summary>
/// Un bandit contestuale con campionamento di Thompson (Agrawal e Goyal, 2013) per
/// la scelta PUNTA / NON PUNTARE.
///
/// <para><b>Come funziona.</b> Il contesto — durata del ciclo, prezzo sul valore,
/// fascia oraria, puntatori distinti — viene ridotto a una chiave; per ogni chiave si
/// tiene una distribuzione Beta(α, β) sulla probabilità che una puntata resti senza
/// risposta. Al momento di decidere si <i>estrae</i> una probabilità dalla Beta
/// invece di usarne la media, e si applica la regola del valore atteso con quella.
/// Dove si è visto poco, la Beta è larga e l'estrazione varia: è l'esplorazione, che
/// si spegne da sola man mano che i dati arrivano.</para>
///
/// <para><b>Da cosa impara.</b> Da ogni decisione registrata, anche quelle in cui non
/// si è puntato: alla chiusura dell'asta si sa se il prezzo è rimasto fermo dopo
/// quell'istante (una puntata sarebbe stata l'ultima) oppure no. È informazione
/// completa, non solo sull'azione presa — cosa rara per un bandit, e che qui rende
/// l'apprendimento molto più rapido.</para>
///
/// <para>È la seconda policy, accanto a quella del modello: gira in shadow su ogni
/// decisione e si confronta con l'altra sugli esiti. Vedi docs/ARCHITETTURA.md.</para>
/// </summary>
public sealed class ThompsonBandit
{
private sealed class Arm
{
public double Alpha;
public double Beta;
}
private readonly Dictionary<string, Arm> _arms = new(StringComparer.Ordinal);
private readonly object _sync = new();
/// <summary>Peso del prior: equivale a tante osservazioni fittizie al tasso di base.</summary>
public double PriorStrength { get; set; } = 4;
/// <summary>Tasso di base P(senza risposta) usato come prior dove non si è visto nulla.</summary>
public double BaseRate { get; set; } = 0.02;
public int Arms { get { lock (_sync) return _arms.Count; } }
public long Observations { get; private set; }
/// <summary>La chiave del contesto: le fasce che contano di più, poche per avere dati in ognuna.</summary>
public static string KeyOf(in BidContext c) =>
$"g{BidFeatures.GapBucket(Math.Max(0, c.CycleSeconds))}|r{BidFeatures.RatioBucket(c.PriceRatio)}|h{BidFeatures.HourBand(c.Hour)}|b{BidFeatures.BiddersBucket(c.DistinctBiddersRecent)}|a{(c.AutoShareRecent >= 0.5 ? 1 : 0)}";
private Arm ArmFor(string key)
{
if (!_arms.TryGetValue(key, out var arm))
{
arm = new Arm { Alpha = BaseRate * PriorStrength, Beta = (1 - BaseRate) * PriorStrength };
_arms[key] = arm;
}
return arm;
}
/// <summary>Aggiorna il braccio del contesto con un esito osservato.</summary>
public void Observe(string key, bool unanswered)
{
lock (_sync)
{
var arm = ArmFor(key);
if (unanswered) arm.Alpha += 1; else arm.Beta += 1;
Observations++;
}
}
/// <summary>La media a posteriori per il contesto.</summary>
public double Mean(string key)
{
lock (_sync)
{
var arm = ArmFor(key);
return arm.Alpha / (arm.Alpha + arm.Beta);
}
}
/// <summary>Quante osservazioni vere ha visto questo contesto.</summary>
public double Evidence(string key)
{
lock (_sync)
{
var arm = ArmFor(key);
return arm.Alpha + arm.Beta - PriorStrength;
}
}
/// <summary>Un'estrazione dalla Beta del contesto: è la probabilità «di oggi».</summary>
public double Sample(string key, Random rng)
{
double a, b;
lock (_sync)
{
var arm = ArmFor(key);
a = arm.Alpha; b = arm.Beta;
}
var x = GammaSample(a, rng);
var y = GammaSample(b, rng);
return x + y > 0 ? x / (x + y) : 0;
}
/// <summary>
/// La decisione: si estrae p e si punta se il valore atteso con quel p è positivo.
/// Restituisce anche il p estratto, per il registro.
/// </summary>
public (bool Bid, double SampledP) Decide(string key, Theory.BidSituation situation, Random rng)
{
var p = Sample(key, rng);
var s = situation with { PWin = p };
return (Theory.BidExpectedValue(s) > 0, p);
}
/// <summary>Campione da Gamma(shape, 1) con il metodo di Marsaglia e Tsang.</summary>
private static double GammaSample(double shape, Random rng)
{
if (shape < 1)
{
// Gamma(a) = Gamma(a+1) · U^(1/a)
var u = rng.NextDouble();
return GammaSample(shape + 1, rng) * Math.Pow(Math.Max(u, 1e-300), 1.0 / shape);
}
var d = shape - 1.0 / 3.0;
var c = 1.0 / Math.Sqrt(9.0 * d);
while (true)
{
double x, v;
do
{
x = Gaussian(rng);
v = 1.0 + c * x;
} while (v <= 0);
v = v * v * v;
var u = rng.NextDouble();
if (u < 1 - 0.0331 * x * x * x * x) return d * v;
if (Math.Log(u) < 0.5 * x * x + d * (1 - v + Math.Log(v))) return d * v;
}
}
private static double Gaussian(Random rng)
{
var u1 = 1.0 - rng.NextDouble();
var u2 = rng.NextDouble();
return Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Cos(2.0 * Math.PI * u2);
}
// ── Persistenza ──────────────────────────────────────────────────
private sealed class Snapshot
{
public double PriorStrength { get; set; }
public double BaseRate { get; set; }
public long Observations { get; set; }
public Dictionary<string, double[]> Arms { get; set; } = new();
}
public string ToJson()
{
lock (_sync)
{
return JsonSerializer.Serialize(new Snapshot
{
PriorStrength = PriorStrength,
BaseRate = BaseRate,
Observations = Observations,
Arms = _arms.ToDictionary(kv => kv.Key, kv => new[] { kv.Value.Alpha, kv.Value.Beta })
});
}
}
public static ThompsonBandit FromJson(string json)
{
var bandit = new ThompsonBandit();
try
{
var s = JsonSerializer.Deserialize<Snapshot>(json);
if (s == null) return bandit;
bandit.PriorStrength = s.PriorStrength > 0 ? s.PriorStrength : 4;
bandit.BaseRate = s.BaseRate > 0 ? s.BaseRate : 0.02;
bandit.Observations = s.Observations;
foreach (var kv in s.Arms)
bandit._arms[kv.Key] = new Arm { Alpha = kv.Value[0], Beta = kv.Value[1] };
}
catch { }
return bandit;
}
/// <summary>Le braccia con più evidenza, per la scheda.</summary>
public IReadOnlyList<(string Key, double Mean, double Evidence)> TopArms(int max = 30)
{
lock (_sync)
{
return _arms
.Select(kv => (kv.Key, kv.Value.Alpha / (kv.Value.Alpha + kv.Value.Beta), kv.Value.Alpha + kv.Value.Beta - PriorStrength))
.OrderByDescending(t => t.Item3)
.Take(max)
.ToList();
}
}
}
@@ -0,0 +1,127 @@
namespace BidooBidBot.Ml;
/// <summary>
/// Un'asta conclusa nella forma che serve ad addestrare: le puntate in ordine di tempo
/// dichiarato dal server, chi ha vinto, a quanto (portato da <c>DossierTrainingReader</c>).
/// La fonte è il database (<see cref="ILearningData"/>); i test costruiscono le sessioni a mano.
/// </summary>
public static class TrainingReader
{
public sealed record Bid(double T, string User, long UnixSeconds, string BidType, bool Mine, double Price);
public sealed class Session
{
public string AuctionId { get; init; } = "";
public string ProductKey { get; init; } = "";
public double? BuyNowPrice { get; init; }
public DateTime AddedAtLocal { get; init; }
public List<Bid> Bids { get; init; } = new();
public string Winner { get; init; } = "";
public double FinalPrice { get; init; }
public bool HasSummary { get; init; }
public string Me { get; init; } = "";
/// <summary>
/// Chiusa, con almeno tre puntate, e con l'ultima registrata davvero del vincitore: se
/// non lo è la registrazione ha un buco in fondo, e l'etichetta sarebbe sbagliata.
/// </summary>
public bool IsUsable =>
HasSummary && Bids.Count >= 3 && !string.IsNullOrEmpty(Winner) &&
string.Equals(Bids[^1].User, Winner, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Chiusura tipica (prezzo/valore) del prodotto a un'ora, o null: la passa chi addestra.</summary>
public delegate double? TypicalCloseRatio(string productKey, DateTime whenLocal);
/// <summary>Ordina le puntate nel tempo del server e marca le nostre dal nome utente.</summary>
public static Session Finish(Session s)
{
s.Bids.Sort((a, b) =>
{
var c = a.UnixSeconds.CompareTo(b.UnixSeconds);
return c != 0 ? c : a.Price.CompareTo(b.Price);
});
if (s.Me.Length > 0)
{
for (var i = 0; i < s.Bids.Count; i++)
if (!s.Bids[i].Mine && string.Equals(s.Bids[i].User, s.Me, StringComparison.OrdinalIgnoreCase))
s.Bids[i] = s.Bids[i] with { Mine = true };
}
return s;
}
/// <summary>
/// Gli esempi di un'asta: uno per puntata, etichetta «è rimasta senza risposta» (vera solo
/// per l'ultima). La prima puntata non ha un ciclo da misurare e si salta.
/// </summary>
public static IEnumerable<(BidContext Context, bool Unanswered, bool Mine)> Examples(Session s, TypicalCloseRatio? typical = null)
{
var bids = s.Bids;
if (bids.Count < 2) yield break;
var recentTimes = new List<long>(12);
for (var i = 1; i < bids.Count; i++)
{
var b = bids[i];
var prev = bids[i - 1];
var gap = b.UnixSeconds > 0 && prev.UnixSeconds > 0 ? b.UnixSeconds - prev.UnixSeconds : -1;
var when = b.UnixSeconds > 0
? AppInfo.ToLocal(DateTimeOffset.FromUnixTimeSeconds(b.UnixSeconds).UtcDateTime)
: s.AddedAtLocal.AddSeconds(b.T);
recentTimes.Clear();
for (var k = i - 1; k >= 0 && recentTimes.Count < 11; k--) recentTimes.Add(bids[k].UnixSeconds);
double? ratio = s.BuyNowPrice is > 0 ? b.Price / s.BuyNowPrice.Value : null;
double? vsTypical = null;
if (typical != null && ratio is { } r && typical(s.ProductKey, when) is { } close && close > 0)
vsTypical = r / close;
var ctx = new BidContext(
CycleSeconds: gap,
AutoShareRecent: AutoShare(bids, i, 10),
DistinctBiddersRecent: Distinct(bids, i, 20),
PriceRatio: ratio,
Hour: when.Hour,
Day: when.DayOfWeek,
OpenHour: s.AddedAtLocal == DateTime.MinValue ? when.Hour : s.AddedAtLocal.Hour,
IsAutoBid: string.Equals(b.BidType, "Auto", StringComparison.OrdinalIgnoreCase),
CyclesSinceManual: SinceManual(bids, i),
AuctionDepthCents: (int)Math.Round(b.Price * 100),
SameBidderAsTwoAgo: i >= 2 && string.Equals(bids[i - 2].User, b.User, StringComparison.OrdinalIgnoreCase),
ProductKey: s.ProductKey,
DeepCyclesRecent: BidFeatures.CountDeepCycles(recentTimes),
PriceVsTypicalClose: vsTypical);
yield return (ctx, i == bids.Count - 1, b.Mine);
}
}
private static double AutoShare(List<Bid> bids, int i, int window)
{
int n = 0, auto = 0;
for (var k = i - 1; k >= 0 && n < window; k--, n++)
if (string.Equals(bids[k].BidType, "Auto", StringComparison.OrdinalIgnoreCase)) auto++;
return n == 0 ? -1 : (double)auto / n;
}
private static int Distinct(List<Bid> bids, int i, int window)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (int k = i - 1, n = 0; k >= 0 && n < window; k--, n++) seen.Add(bids[k].User);
return Math.Max(1, seen.Count);
}
private static int SinceManual(List<Bid> bids, int i)
{
var n = 0;
for (var k = i - 1; k >= 0; k--)
{
if (!string.Equals(bids[k].BidType, "Auto", StringComparison.OrdinalIgnoreCase)) return n;
if (++n >= 20) break;
}
return -1;
}
}
@@ -0,0 +1,141 @@
using System.Globalization;
using System.Text;
namespace BidooBidBot.Products;
/// <summary>
/// I limiti consigliati per un prodotto (dal vecchio <c>PriceAdvisor</c> del legacy): solo un
/// <b>consiglio</b> scritto con il suo ragionamento, applicato unicamente se l'utente preme
/// «Usa consigliati». Il modello resta l'unico decisore; questi sono paletti proposti.
///
/// <para><b>Massimo</b> = il più stretto fra due vincoli: dove il prodotto si vende davvero
/// (il prezzo che copre l'85% delle chiusure passate: la sola moda ne coprirebbe il 15-44%)
/// e quanto si può spendere (<c>valore × (1 + tolleranza) − puntate × costo − spedizione</c>).
/// <b>Puntate</b> = il più stretto fra il 75° percentile di quelle spese dai vincitori e quelle
/// pagabili restando nel valore. Il 10° percentile delle chiusure si dice nella spiegazione:
/// sotto, l'asta non si chiude quasi mai. Con meno di 5 aste nessun consiglio. Pura.</para>
/// </summary>
public static class ProductAdvice
{
public const int MinimumSample = 5;
/// <summary>Puntate massime quando lo storico dei vincitori non basta.</summary>
public const int FallbackMaxBids = 25;
public readonly record struct Input(
IReadOnlyList<double> FinalPrices,
IReadOnlyList<int> WinnerBids,
double? Value,
double? Shipping,
int MaxBids,
double BidCostEuro,
double TolerancePercent,
double Coverage,
double MinPercentile);
public readonly record struct Advice(
bool HasAdvice, double? MaxPrice, int? MaxBids, double Floor, double Mode, double Median,
double CoverageReached, bool LimitedByBudget, bool NotWorthwhile, int Sample, string Explanation);
public static Advice Suggest(Input input)
{
var it = CultureInfo.GetCultureInfo("it-IT");
var prices = (input.FinalPrices ?? Array.Empty<double>()).Where(p => p > 0).OrderBy(p => p).ToList();
if (prices.Count < MinimumSample)
return new Advice(false, null, null, 0, 0, 0, 0, false, false, prices.Count,
$"Servono almeno {MinimumSample} aste concluse per un consiglio attendibile (finora {prices.Count}).");
var coverage = input.Coverage is > 0 and < 1 ? input.Coverage : 0.85;
var mode = Mode(prices);
var median = Percentile(prices, 0.5);
var byMarket = Percentile(prices, coverage);
var budget = BudgetCeiling(input);
var max = budget.HasValue ? Math.Min(byMarket, budget.Value) : byMarket;
var limitedByBudget = budget.HasValue && budget.Value < byMarket;
var notWorthwhile = max < mode;
var floor = Math.Floor(Percentile(prices, Math.Clamp(input.MinPercentile, 0, 0.5)) * 100) / 100;
max = Math.Floor(max * 100) / 100;
var reached = prices.Count(p => p <= max) * 100.0 / prices.Count;
var maxBids = SuggestMaxBids(input, max);
var text = new StringBuilder();
text.Append($"Su {prices.Count} aste concluse si aggiudica più spesso intorno a {mode.ToString("0.00", it)} €, mediana {median.ToString("0.00", it)} €. ");
text.Append($"Fermandosi a {max.ToString("0.00", it)} € saresti stato in gioco nel {reached.ToString("0", it)}% dei casi");
if (floor > 0 && floor < max) text.Append($"; sotto {floor.ToString("0.00", it)} € l'asta non si è chiusa quasi mai");
text.Append('.');
if (limitedByBudget && budget.HasValue)
text.Append($" Il tetto viene dal budget: valore {input.Value!.Value.ToString("0.00", it)} € più {input.TolerancePercent:0}% di tolleranza, meno {input.MaxBids} puntate da {input.BidCostEuro.ToString("0.00", it)} € e la spedizione, lascia {budget.Value.ToString("0.00", it)} €.");
else if (input.MaxBids <= 0)
text.Append(" Puntate illimitate: il tetto non tiene conto del loro costo; con un massimo di puntate il consiglio è più solido.");
if (maxBids is { } mb)
text.Append($" Puntate: {mb} (i tre quarti dei vincitori ne hanno spese meno" + (input.Value is > 0 ? ", e restano nel valore" : "") + ").");
if (notWorthwhile)
text.Append(" Attenzione: con queste puntate il tetto sta sotto la chiusura più frequente, il prodotto non conviene.");
return new Advice(true, max, maxBids, floor, mode, median, reached, limitedByBudget, notWorthwhile, prices.Count, text.ToString());
}
public static int? SuggestMaxBids(Input input, double plannedMaxPrice)
{
var observed = (input.WinnerBids ?? Array.Empty<int>()).Where(b => b > 0).OrderBy(b => b).Select(b => (double)b).ToList();
var needed = observed.Count >= MinimumSample ? (int)Math.Ceiling(Percentile(observed, 0.75)) : FallbackMaxBids;
var payable = int.MaxValue;
if (input.Value is > 0)
{
var bidCost = Math.Max(0.01, input.BidCostEuro);
var ceiling = input.Value.Value * (1 + input.TolerancePercent / 100.0);
var left = ceiling - plannedMaxPrice - (input.Shipping ?? 0);
payable = left <= 0 ? 0 : (int)Math.Floor(left / bidCost);
}
var suggested = Math.Min(needed, payable);
return suggested > 0 ? suggested : null;
}
private static double? BudgetCeiling(Input input)
{
if (input.Value is not > 0 || input.MaxBids <= 0) return null;
var ceiling = input.Value.Value * (1 + input.TolerancePercent / 100.0)
- input.MaxBids * Math.Max(0, input.BidCostEuro)
- (input.Shipping ?? 0);
return Math.Max(0, ceiling);
}
/// <summary>Percentile con interpolazione lineare su valori già ordinati.</summary>
public static double Percentile(IReadOnlyList<double> sorted, double p)
{
if (sorted.Count == 0) return 0;
if (sorted.Count == 1) return sorted[0];
var pos = (sorted.Count - 1) * Math.Clamp(p, 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);
}
/// <summary>La chiusura più frequente: centro dell'intervallo più affollato (Freedman-Diaconis).</summary>
public static double Mode(IReadOnlyList<double> sorted)
{
if (sorted.Count == 0) return 0;
if (sorted.Count < 3) return Percentile(sorted, 0.5);
var iqr = Percentile(sorted, 0.75) - Percentile(sorted, 0.25);
var width = iqr > 0 ? 2 * iqr / Math.Pow(sorted.Count, 1.0 / 3.0) : (sorted[^1] - sorted[0]) / 10.0;
width = Math.Max(width <= 0 ? 0.01 : width, 0.01);
var buckets = new Dictionary<long, int>();
long best = 0;
var bestCount = 0;
foreach (var price in sorted)
{
var b = (long)(price / width);
buckets.TryGetValue(b, out var c);
buckets[b] = ++c;
if (c > bestCount) { bestCount = c; best = b; }
}
return Percentile(sorted.Where(p => (long)(p / width) == best).ToList(), 0.5);
}
}
@@ -0,0 +1,76 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace BidooBidBot.Products;
/// <summary>
/// La chiave prodotto normalizzata dal nome di un'asta (portata dal legacy): raggruppa le
/// aste dello stesso articolo per statistiche, profilo del modello e prodotti seguiti.
/// Minuscole, niente accenti, niente parentesi (varianti), punteggiatura unificata; i numeri
/// restano, perché distinguono i modelli.
/// </summary>
public static partial class ProductKey
{
public static string From(string? productName)
{
if (string.IsNullOrWhiteSpace(productName)) return "";
var text = RemoveDiacritics(productName.Trim().ToLowerInvariant());
text = Parentheses().Replace(text, " ");
text = NonAlphanumeric().Replace(text, " ");
text = Spaces().Replace(text, " ").Trim();
return text;
}
private static string RemoveDiacritics(string text)
{
var normalized = text.Normalize(NormalizationForm.FormD);
var sb = new StringBuilder(normalized.Length);
foreach (var c in normalized)
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) sb.Append(c);
return sb.ToString().Normalize(NormalizationForm.FormC);
}
[GeneratedRegex(@"\([^)]*\)")] private static partial Regex Parentheses();
[GeneratedRegex(@"[^a-z0-9]+")] private static partial Regex NonAlphanumeric();
[GeneratedRegex(@"\s+")] private static partial Regex Spaces();
}
/// <summary>
/// Il conteggio delle puntate del vincitore è credibile? (portato dal legacy) Il prezzo
/// finale in centesimi è il totale delle puntate dell'asta: il vincitore non può averne fatte
/// di più, né zero. Una statistica storta è peggio di una assente: ciò che non torna si
/// scarta e si scrive nel registro.
/// </summary>
public static class AuctionIntegrity
{
public readonly record struct Check(bool IsTrustworthy, string? Reason)
{
public static Check Ok() => new(true, null);
public static Check No(string reason) => new(false, reason);
}
public static Check CheckWinnerBids(double finalPrice, int? winnerBids)
{
if (winnerBids is null) return Check.No("puntate del vincitore non registrate");
if (winnerBids < 1) return Check.No("puntate del vincitore a zero: l'ultima puntata è per forza sua");
if (finalPrice <= 0) return Check.No("prezzo finale mancante: non c'è nulla con cui confrontare");
var totalBids = (int)Math.Round(finalPrice * 100) + 1;
if (winnerBids > totalBids)
return Check.No($"puntate del vincitore ({winnerBids}) oltre il totale dell'asta ({totalBids})");
return Check.Ok();
}
public static int? Trusted(double finalPrice, int? winnerBids) =>
CheckWinnerBids(finalPrice, winnerBids).IsTrustworthy ? winnerBids : null;
/// <summary>Quanta parte dell'asta è stata osservata (0-1): reset visti sulle puntate totali.</summary>
public static double? ObservedCoverage(double finalPrice, int observedBids)
{
if (finalPrice <= 0) return null;
var total = Math.Round(finalPrice * 100);
return total <= 0 ? null : Math.Min(1.0, Math.Max(0, observedBids) / total);
}
}
@@ -0,0 +1,103 @@
using BidooBidBot.Bidoo;
using BidooBidBot.Engine;
using BidooBidBot.Settings;
namespace BidooBidBot.Products;
/// <summary>
/// La scheda di un prodotto (tabella <c>products</c>): paletti propri e valore reale scelti
/// dall'utente, stellina «segui». I campi annullabili valgono «nessuna preferenza, usa il
/// predefinito»; uno zero pieno è una scelta vera (nessun tetto).
/// </summary>
public sealed class ProductRecord
{
public string ProductKey { get; set; } = "";
public int BidooProductId { get; set; }
public string DisplayName { get; set; } = "";
public double? MaxPrice { get; set; }
public int? MaxBids { get; set; }
/// <summary>Valore reale V scelto dall'utente; null = vale il «Compralo Ora».</summary>
public double? MarketValue { get; set; }
/// <summary>Orizzonte proprio dell'aggiunta automatica in minuti; 0 = nessun limite; null = predefinito.</summary>
public int? HorizonMinutes { get; set; }
/// <summary>La stellina: le aste nuove del prodotto entrano da sole.</summary>
public bool Followed { get; set; }
/// <summary>Modo delle aste aggiunte da sole per questo prodotto; null = predefinito.</summary>
public string? AutoState { get; set; }
public bool? QuietHours { get; set; }
public int AutoAddedCount { get; set; }
public DateTime AddedAtUtc { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAtUtc { get; set; } = DateTime.UtcNow;
public bool HasCustomLimits => MaxPrice.HasValue || MaxBids.HasValue || HorizonMinutes.HasValue ||
!string.IsNullOrEmpty(AutoState) || MarketValue.HasValue || QuietHours.HasValue;
/// <summary>Stesso prodotto? Prima l'id di Bidoo (non cambia), poi il nome normalizzato.</summary>
public bool Matches(CatalogAuction auction)
{
if (BidooProductId > 0 && auction.ProductId > 0) return BidooProductId == auction.ProductId;
return !string.IsNullOrEmpty(ProductKey) && ProductKey == Products.ProductKey.From(auction.Name);
}
public bool MatchesName(string? name) =>
!string.IsNullOrEmpty(ProductKey) && !string.IsNullOrWhiteSpace(name) && ProductKey == Products.ProductKey.From(name);
public ProductRecord Clone() => (ProductRecord)MemberwiseClone();
}
/// <summary>
/// Con quali paletti nasce un'asta nuova (portato da <c>ProductRuleResolver</c>): il valore
/// del prodotto se c'è, altrimenti il predefinito delle impostazioni. Un punto solo, perché le
/// aste entrano da tre strade (a mano, dal catalogo, dalla sorveglianza).
/// </summary>
public static class ProductRules
{
public readonly record struct Limits(double MaxPrice, int MaxBids, RunMode Mode, bool FromProduct, int HorizonMinutes);
public static Limits Resolve(ProductRecord? product, AppSettings settings, bool autoAdded)
{
var modeText = product?.AutoState ?? (autoAdded ? settings.AutoAddNewAuctionState : settings.DefaultNewAuctionState);
return new Limits(
MaxPrice: product?.MaxPrice ?? settings.DefaultMaxPrice,
MaxBids: product?.MaxBids ?? settings.DefaultMaxClicks,
Mode: ParseMode(modeText),
FromProduct: product?.HasCustomLimits == true,
HorizonMinutes: Math.Max(0, product?.HorizonMinutes ?? settings.AutoAddMaxStartMinutes));
}
/// <summary>Orizzonte dell'aggiunta automatica in secondi (0 = nessun limite).</summary>
public static int HorizonSeconds(ProductRecord? product, AppSettings settings)
{
var minutes = product?.HorizonMinutes ?? settings.AutoAddMaxStartMinutes;
return minutes <= 0 ? 0 : minutes * 60;
}
/// <summary>Ciò che non si riconosce diventa Osserva: un'asta che entra da sola non punta mai senza che l'utente l'abbia vista.</summary>
public static RunMode ParseMode(string? state) => RunModes.Parse(state, RunMode.Watch);
/// <summary>
/// Il valore reale V di un'asta: quello scritto sul prodotto, altrimenti il Compralo Ora.
/// </summary>
public static double? ValueOf(ProductRecord? product, double? buyNow) =>
product?.MarketValue is > 0 ? product.MarketValue : buyNow is > 0 ? buyNow : null;
/// <summary>L'utente ha scritto il valore reale? Solo allora vale la copertura Compralo Ora.</summary>
public static bool HasExplicitValue(ProductRecord? product) => product?.MarketValue is > 0;
/// <summary>La fascia oraria vale per quest'asta? L'asta scavalca il prodotto, il prodotto le impostazioni.</summary>
public static bool QuietHoursApply(bool? auctionOverride, ProductRecord? product, AppSettings settings) =>
auctionOverride ?? product?.QuietHours ?? settings.QuietHoursEnabled;
/// <summary>
/// L'asta è già cominciata? Il criterio è il puntatore, non il timer; il prezzo fa da
/// riserva (su Bidoo si parte da un centesimo).
/// </summary>
public static bool HasStarted(CatalogAuction auction) =>
!string.IsNullOrWhiteSpace(auction.LastBidder) || auction.CurrentPrice > 0.01m;
}
@@ -0,0 +1,143 @@
using System.Text.Json;
using BidooBidBot.Data;
namespace BidooBidBot.Products;
/// <summary>
/// Com'è andata finora per un prodotto: si ricalcola in SQL a ogni asta chiusa e si salva in
/// <c>product_stats</c>, così la scheda Prodotti non rilegge l'intero storico.
/// </summary>
public sealed class ProductStatsData
{
public int Auctions { get; set; }
public int Won { get; set; }
public int WithMyBids { get; set; }
public int MyBidsTotal { get; set; }
public double MyBidsCost { get; set; }
public double AvgFinal { get; set; }
public double MinFinal { get; set; }
public double MaxFinal { get; set; }
public double? LastFinal { get; set; }
public DateTime? LastClosedAtUtc { get; set; }
public double? BuyNow { get; set; }
public double? Shipping { get; set; }
public string? ImageUrl { get; set; }
public string? Name { get; set; }
public double? AvgWinnerBids { get; set; }
public int WinnerBidsSamples { get; set; }
public double? AvgRealCostWon { get; set; }
public double? AvgSavingWon { get; set; }
public int CompleteObservations { get; set; }
public double AvgObservedMinutes { get; set; }
/// <summary>Ultimi prezzi finali, dal più recente (al massimo 300): istogramma e consigli.</summary>
public List<double> RecentCloses { get; set; } = new();
/// <summary>Ultime puntate del vincitore attendibili, dal più recente (al massimo 300).</summary>
public List<int> RecentWinnerBids { get; set; } = new();
/// <summary>Chiusura mediana per fascia oraria (0-5, come in BidFeatures): la «previsione tipica».</summary>
public Dictionary<int, double> MedianCloseByHourBand { get; set; } = new();
public Dictionary<int, int> CountByHourBand { get; set; } = new();
}
/// <summary>Letture e ricalcoli delle statistiche per prodotto.</summary>
public static class ProductStatsRepository
{
private static readonly JsonSerializerOptions Json = new();
/// <summary>Le statistiche di un prodotto, dalle aste concluse.</summary>
public static async Task<ProductStatsData?> ComputeAsync(Db db, string productKey, double transactionFee)
{
var agg = await db.QueryOneAsync(
"SELECT COUNT(*) AS n, SUM(CASE WHEN won_by_me THEN 1 ELSE 0 END) AS won, " +
" SUM(CASE WHEN my_bids > 0 THEN 1 ELSE 0 END) AS with_mine, COALESCE(SUM(my_bids), 0) AS my_total, " +
" COALESCE(SUM(my_bids_cost), 0) AS my_cost, AVG(final_price) AS avg_final, MIN(final_price) AS min_final, " +
" MAX(final_price) AS max_final, SUM(CASE WHEN observed_from_start AND observed_to_end THEN 1 ELSE 0 END) AS complete, " +
" AVG(observed_minutes) AS avg_minutes, MAX(end_time) AS last_end " +
"FROM auctions WHERE product_key = $1 AND outcome IS NOT NULL AND final_price IS NOT NULL",
r => new ProductStatsData
{
Auctions = r.Int("n"), Won = r.Int("won"), WithMyBids = r.Int("with_mine"), MyBidsTotal = r.Int("my_total"),
MyBidsCost = r.Dbl("my_cost"), AvgFinal = r.Dbl("avg_final"), MinFinal = r.Dbl("min_final"), MaxFinal = r.Dbl("max_final"),
CompleteObservations = r.Int("complete"), AvgObservedMinutes = r.Dbl("avg_minutes"), LastClosedAtUtc = r.Date("last_end")
}, productKey).ConfigureAwait(false);
if (agg == null || agg.Auctions == 0) return null;
var recent = await db.QueryAsync(
"SELECT a.name, a.final_price, a.winner_bids_paid, a.winner_bids_free, a.buy_now_price, a.shipping, a.won_by_me, " +
" a.my_bids_cost, a.market_value, a.end_time, a.transaction_fee, i.image_url " +
"FROM auctions a LEFT JOIN items i ON i.product_key = a.product_key " +
"WHERE a.product_key = $1 AND a.outcome IS NOT NULL AND a.final_price IS NOT NULL ORDER BY a.end_time DESC LIMIT 300",
r => (Name: r.Str("name"), Final: r.Dbl("final_price"), Paid: r.IntOrNull("winner_bids_paid"), Free: r.IntOrNull("winner_bids_free"),
BuyNow: r.DblOrNull("buy_now_price"), Ship: r.DblOrNull("shipping"), Won: r.Bool("won_by_me"), MyCost: r.Dbl("my_bids_cost"),
Value: r.DblOrNull("market_value"), End: r.Date("end_time"), Fee: r.DblOrNull("transaction_fee"), Img: r.StrOrNull("image_url")),
productKey).ConfigureAwait(false);
var s = agg;
s.Name = recent.FirstOrDefault().Name;
s.LastFinal = recent.Count > 0 ? recent[0].Final : null;
s.BuyNow = recent.Select(r => r.BuyNow).FirstOrDefault(v => v is > 0);
s.Shipping = recent.Select(r => r.Ship).FirstOrDefault(v => v != null);
s.ImageUrl = recent.Select(r => r.Img).FirstOrDefault(v => !string.IsNullOrEmpty(v));
s.RecentCloses = recent.Select(r => r.Final).ToList();
foreach (var r in recent)
{
var total = r.Paid.HasValue || r.Free.HasValue ? (r.Paid ?? 0) + (r.Free ?? 0) : (int?)null;
if (AuctionIntegrity.Trusted(r.Final, total) is { } t) s.RecentWinnerBids.Add(t);
}
s.WinnerBidsSamples = s.RecentWinnerBids.Count;
s.AvgWinnerBids = s.RecentWinnerBids.Count > 0 ? s.RecentWinnerBids.Average() : null;
var won = recent.Where(r => r.Won).ToList();
if (won.Count > 0)
{
var costs = won.Select(r => r.Final + r.MyCost + (r.Fee ?? transactionFee) + (r.Ship ?? 0)).ToList();
s.AvgRealCostWon = costs.Average();
var savings = won.Where(r => (r.Value ?? r.BuyNow) is > 0)
.Select(r => (r.Value ?? r.BuyNow)!.Value - (r.Final + r.MyCost + (r.Fee ?? transactionFee) + (r.Ship ?? 0))).ToList();
s.AvgSavingWon = savings.Count > 0 ? savings.Average() : null;
}
foreach (var g in recent.Where(r => r.End != null).GroupBy(r => Ml.BidFeatures.HourBand(AppInfo.ToLocal(r.End!.Value).Hour)))
{
var closes = g.Select(r => r.Final).OrderBy(x => x).ToList();
s.MedianCloseByHourBand[g.Key] = ProductAdvice.Percentile(closes, 0.5);
s.CountByHourBand[g.Key] = closes.Count;
}
return s;
}
/// <summary>Ricalcola e salva (dalla coda) le statistiche di un prodotto.</summary>
public static async Task<ProductStatsData?> RefreshAsync(Db db, WriteQueue queue, string productKey, double transactionFee)
{
var stats = await ComputeAsync(db, productKey, transactionFee).ConfigureAwait(false);
if (stats == null) return null;
queue.Enqueue(
"INSERT INTO product_stats(product_key, value, updated_at) VALUES($1, $2, now()) " +
"ON CONFLICT(product_key) DO UPDATE SET value = excluded.value, updated_at = now()",
productKey, new Jsonb(JsonSerializer.Serialize(stats, Json)));
return stats;
}
public static async Task<Dictionary<string, ProductStatsData>> LoadAllAsync(Db db)
{
var rows = await db.QueryAsync("SELECT product_key, value::text AS v FROM product_stats",
r => (Key: r.Str("product_key"), V: r.Str("v"))).ConfigureAwait(false);
var dict = new Dictionary<string, ProductStatsData>(StringComparer.Ordinal);
foreach (var (key, v) in rows)
{
try { if (JsonSerializer.Deserialize<ProductStatsData>(v, Json) is { } d) dict[key] = d; }
catch (JsonException) { /* si rifà al prossimo ricalcolo */ }
}
return dict;
}
/// <summary>I prodotti con almeno un'asta conclusa: per il ricalcolo completo.</summary>
public static Task<List<string>> ProductKeysAsync(Db db) =>
db.QueryAsync("SELECT DISTINCT product_key FROM auctions WHERE outcome IS NOT NULL AND product_key <> '' ORDER BY product_key",
r => r.Str("product_key"));
}
@@ -0,0 +1,198 @@
using System.Collections.Concurrent;
using System.Text.Json;
using BidooBidBot.Bidoo;
using BidooBidBot.Data;
namespace BidooBidBot.Products;
/// <summary>
/// Le schede prodotto e le aste già trattate dalla sorveglianza, in memoria (il motore le
/// legge a ogni decisione) con le scritture accodate su <c>products</c> e
/// <c>watched_products</c>.
///
/// <para>Le aste proposte dalla sorveglianza e quelle tolte a mano non tornano più da sole:
/// rimettere un'asta che l'utente ha tolto sarebbe una lotta contro l'utente.</para>
/// </summary>
public sealed class ProductStore
{
private readonly ConcurrentDictionary<string, ProductRecord> _products = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, (HashSet<string> Proposed, HashSet<string> Removed)> _handled = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, byte> _handledIds = new(StringComparer.Ordinal);
private readonly WriteQueue? _queue;
private const int MaxHandledPerProduct = 2000;
public ProductStore(WriteQueue? queue) => _queue = queue;
/// <summary>Qualcosa è cambiato in una scheda (per l'interfaccia).</summary>
public event Action<string>? Changed;
public async Task LoadAsync(Db db)
{
var rows = await db.QueryAsync(
"SELECT product_key, bidoo_product_id, display_name, max_price, max_bids, market_value, horizon_minutes, " +
"followed, auto_state, quiet_hours, auto_added_count, added_at, updated_at FROM products",
r => new ProductRecord
{
ProductKey = r.Str("product_key"),
BidooProductId = r.Int("bidoo_product_id"),
DisplayName = r.Str("display_name"),
MaxPrice = r.DblOrNull("max_price"),
MaxBids = r.IntOrNull("max_bids"),
MarketValue = r.DblOrNull("market_value"),
HorizonMinutes = r.IntOrNull("horizon_minutes"),
Followed = r.Bool("followed"),
AutoState = r.StrOrNull("auto_state"),
QuietHours = r.BoolOrNull("quiet_hours"),
AutoAddedCount = r.Int("auto_added_count"),
AddedAtUtc = r.Date("added_at") ?? DateTime.UtcNow,
UpdatedAtUtc = r.Date("updated_at") ?? DateTime.UtcNow
}).ConfigureAwait(false);
_products.Clear();
foreach (var p in rows) _products[p.ProductKey] = p;
var handled = await db.QueryAsync(
"SELECT product_key, proposed_auction_ids::text AS p, removed_auction_ids::text AS r FROM watched_products",
r => (Key: r.Str("product_key"), P: r.Str("p"), R: r.Str("r"))).ConfigureAwait(false);
_handled.Clear();
_handledIds.Clear();
foreach (var (key, p, r) in handled)
{
var proposed = ParseIds(p);
var removed = ParseIds(r);
_handled[key] = (proposed, removed);
foreach (var id in proposed.Concat(removed)) _handledIds[id] = 0;
}
}
private static HashSet<string> ParseIds(string json)
{
try { return (JsonSerializer.Deserialize<List<string>>(json) ?? new()).ToHashSet(StringComparer.Ordinal); }
catch (JsonException) { return new HashSet<string>(StringComparer.Ordinal); }
}
// ── Lettura ──────────────────────────────────────────────────────────
public IReadOnlyList<ProductRecord> All() => _products.Values.Select(p => p.Clone()).ToList();
public IReadOnlyList<ProductRecord> Followed() => _products.Values.Where(p => p.Followed).Select(p => p.Clone()).ToList();
public ProductRecord? Find(string? key) =>
!string.IsNullOrEmpty(key) && _products.TryGetValue(key, out var p) ? p : null;
public ProductRecord? FindByName(string? name) => Find(ProductKey.From(name));
/// <summary>La scheda di un'asta del catalogo: prima per id di Bidoo, poi per nome.</summary>
public ProductRecord? FindFor(CatalogAuction auction)
{
if (auction.ProductId > 0)
{
var byId = _products.Values.FirstOrDefault(p => p.BidooProductId == auction.ProductId);
if (byId != null) return byId;
}
return FindByName(auction.Name);
}
// ── Scrittura ────────────────────────────────────────────────────────
public void Upsert(ProductRecord product)
{
if (string.IsNullOrEmpty(product.ProductKey)) product.ProductKey = ProductKey.From(product.DisplayName);
if (string.IsNullOrEmpty(product.ProductKey)) return;
product.UpdatedAtUtc = DateTime.UtcNow;
_products[product.ProductKey] = product.Clone();
_queue?.EnqueueGroup(new (string, object?[])[]
{
("INSERT INTO products(product_key, bidoo_product_id, display_name, max_price, max_bids, market_value, horizon_minutes, " +
" followed, auto_state, quiet_hours, auto_added_count, added_at, updated_at) " +
"VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now()) " +
"ON CONFLICT(product_key) DO UPDATE SET bidoo_product_id = excluded.bidoo_product_id, display_name = excluded.display_name, " +
" max_price = excluded.max_price, max_bids = excluded.max_bids, market_value = excluded.market_value, " +
" horizon_minutes = excluded.horizon_minutes, followed = excluded.followed, auto_state = excluded.auto_state, " +
" quiet_hours = excluded.quiet_hours, auto_added_count = excluded.auto_added_count, updated_at = now()",
new object?[]
{
product.ProductKey, product.BidooProductId > 0 ? product.BidooProductId : null, product.DisplayName,
product.MaxPrice, product.MaxBids, product.MarketValue, product.HorizonMinutes, product.Followed,
product.AutoState, product.QuietHours, product.AutoAddedCount, product.AddedAtUtc
}),
// Il valore reale finisce anche sul prodotto dell'archivio: le aste nuove lo ereditano.
("INSERT INTO items(product_key, title, market_price_est, market_price_source) VALUES($1, $2, $3, CASE WHEN $3::numeric IS NULL THEN NULL ELSE 'utente' END) " +
"ON CONFLICT(product_key) DO UPDATE SET market_price_est = excluded.market_price_est, " +
" market_price_source = excluded.market_price_source, updated_at = now()",
new object?[] { product.ProductKey, product.DisplayName, product.MarketValue })
});
Changed?.Invoke(product.ProductKey);
}
/// <summary>La stellina. Spegnendola, la scheda resta solo se ha limiti scritti a mano.</summary>
public ProductRecord SetFollowed(string key, string displayName, int bidooProductId, bool followed)
{
var p = Find(key)?.Clone() ?? new ProductRecord { ProductKey = key, DisplayName = displayName };
if (bidooProductId > 0) p.BidooProductId = bidooProductId;
if (string.IsNullOrEmpty(p.DisplayName)) p.DisplayName = displayName;
p.Followed = followed;
if (!followed && !p.HasCustomLimits) Delete(key);
else Upsert(p);
return p;
}
public void Delete(string key)
{
if (!_products.TryRemove(key, out _)) return;
_queue?.Enqueue("DELETE FROM products WHERE product_key = $1", key);
Changed?.Invoke(key);
}
// ── Aste già trattate dalla sorveglianza ─────────────────────────────
public bool IsHandled(string auctionId) => _handledIds.ContainsKey(auctionId);
public void MarkProposed(string productKey, string auctionId) => Mark(productKey, auctionId, removed: false);
public void MarkRemoved(string productKey, string auctionId) => Mark(productKey, auctionId, removed: true);
private void Mark(string productKey, string auctionId, bool removed)
{
if (string.IsNullOrEmpty(productKey) || string.IsNullOrEmpty(auctionId)) return;
_handledIds[auctionId] = 0;
var sets = _handled.GetOrAdd(productKey, _ => (new HashSet<string>(StringComparer.Ordinal), new HashSet<string>(StringComparer.Ordinal)));
string proposedJson, removedJson;
lock (sets.Proposed)
{
(removed ? sets.Removed : sets.Proposed).Add(auctionId);
Trim(sets.Proposed);
Trim(sets.Removed);
proposedJson = JsonSerializer.Serialize(sets.Proposed);
removedJson = JsonSerializer.Serialize(sets.Removed);
}
_queue?.Enqueue(
"INSERT INTO watched_products(product_key, proposed_auction_ids, removed_auction_ids, updated_at) VALUES($1, $2, $3, now()) " +
"ON CONFLICT(product_key) DO UPDATE SET proposed_auction_ids = excluded.proposed_auction_ids, " +
" removed_auction_ids = excluded.removed_auction_ids, updated_at = now()",
productKey, new Jsonb(proposedJson), new Jsonb(removedJson));
}
private static void Trim(HashSet<string> set)
{
if (set.Count <= MaxHandledPerProduct) return;
foreach (var id in set.OrderBy(x => x, StringComparer.Ordinal).Take(set.Count - MaxHandledPerProduct).ToList())
set.Remove(id);
}
/// <summary>Un'asta in più aggiunta da sola per questo prodotto.</summary>
public void CountAutoAdded(string productKey)
{
var p = Find(productKey)?.Clone();
if (p == null) return;
p.AutoAddedCount++;
Upsert(p);
}
}
@@ -0,0 +1,215 @@
using System.Globalization;
using BidooBidBot.Bidoo;
using BidooBidBot.Engine;
using BidooBidBot.Ml;
using BidooBidBot.Products;
using BidooBidBot.Settings;
namespace BidooBidBot.Strategy;
/// <summary>Il saldo del conto come lo conosce il bot.</summary>
public readonly record struct AccountBalance(int? Total, int? Paid, int? Free);
/// <summary>Il verdetto su un ciclo, con i numeri che l'hanno prodotto.</summary>
public sealed class BidDecision
{
public bool ShouldBid { get; set; }
/// <summary>Il tipo, in codice breve (<see cref="LossReasons.Kind"/>).</summary>
public string Kind { get; set; } = "";
public string Reason { get; set; } = "";
public double? PModel { get; set; }
public double? PWin { get; set; }
public double? OwnBidFactor { get; set; }
public double? Ev { get; set; }
public double? BidCost { get; set; }
public double? Value { get; set; }
public string? ContextKey { get; set; }
public string? AltAction { get; set; }
public double? PBandit { get; set; }
public BidContext? Context { get; set; }
/// <summary>La decisione l'ha presa il modello (non un paletto né il rischio).</summary>
public bool FromModel => Kind is LossReasons.Kind.Punta or LossReasons.Kind.Esplora or LossReasons.Kind.EvNegativo or LossReasons.Kind.NonPronto;
public static BidDecision No(string kind, string reason) => new() { ShouldBid = false, Kind = kind, Reason = reason };
public static BidDecision Yes(string kind, string reason) => new() { ShouldBid = true, Kind = kind, Reason = reason };
}
/// <summary>
/// Decide se puntare (specifica §7.1, portato da <c>BidStrategyService</c> e dai controlli del
/// monitor del legacy). Tre passi, sempre nello stesso ordine:
///
/// <list type="number">
/// <item><b>Rischio</b> (solo dal vivo): HALT, stop-loss, drawdown, tetto del giorno, aste
/// in gioco insieme. In Osserva la decisione si registra com'è, per poterla giudicare.</item>
/// <item><b>Paletti dell'utente</b>: già in testa, puntate residue sotto la soglia (sul
/// totale pagate + gratis), puntata appena fatta, fascia oraria, puntate massime per asta e
/// per sessione, prezzo massimo. Tutti a zero di fabbrica = nessuno.</item>
/// <item><b>Modello</b>: <c>P = P_modello × correzione sulle mie puntate</c>, costo
/// effettivo della puntata, <c>EV = Theory.BidExpectedValue</c>. EV &gt; 0 → punta. EV ≤ 0
/// ma contesto poco visto dal bandit e budget d'esplorazione → esplora. Altrimenti no.</item>
/// </list>
/// Non c'è altra strategia. Il <i>quando</i> (l'anticipo) sta nel cecchino.
/// </summary>
public sealed class BidStrategy
{
private readonly RiskManager _risk;
private readonly LearningService _learning;
private readonly ProductStore _products;
private readonly Func<AccountBalance> _account;
private readonly Random _rng = new();
private readonly object _rngSync = new();
private int _sessionBids;
/// <summary>Pausa minima dopo una nostra puntata sulla stessa asta.</summary>
public const int CooldownMs = 800;
public BidStrategy(RiskManager risk, LearningService learning, ProductStore products, Func<AccountBalance> account)
{
_risk = risk;
_learning = learning;
_products = products;
_account = account;
}
public int SessionBids => Volatile.Read(ref _sessionBids);
/// <summary>
/// Il costo vero della prossima puntata: Bidoo alterna pagate e gratis, quindi in media
/// costa <c>costo × pagate / (pagate + gratis)</c>. Senza il dettaglio, il costo pieno.
/// </summary>
public static double EffectiveBidCost(AppSettings settings, AccountBalance balance)
{
var cost = Math.Max(0.01, settings.AverageBidCostEuro);
if (balance is { Paid: { } paid, Free: { } free } && paid + free > 0) return cost * paid / (paid + free);
return cost;
}
public BidDecision Decide(AuctionInfo auction, AuctionState state, AppSettings settings,
IReadOnlyCollection<AuctionInfo>? all, bool shadow, string? me, DateTime nowLocal)
{
var it = CultureInfo.GetCultureInfo("it-IT");
var balance = _account();
var cost = EffectiveBidCost(settings, balance);
// ── 1. Rischio (solo dal vivo) ────────────────────────────────────
if (!shadow)
{
var verdict = _risk.Authorize(auction, settings, cost, all);
if (!verdict.Allowed) return BidDecision.No(LossReasons.Kind.Rischio, verdict.Reason ?? "gestore del rischio");
}
// ── 2. Paletti dell'utente ────────────────────────────────────────
if (state.IsMyBid) return BidDecision.No(LossReasons.Kind.InTesta, "già in testa");
if (settings.MinimumRemainingBids > 0 && balance.Total is { } total && total <= settings.MinimumRemainingBids)
return BidDecision.No(LossReasons.Kind.PuntateResidue,
$"puntate residue {total.ToString("N0", it)} entro la soglia di protezione ({settings.MinimumRemainingBids.ToString("N0", it)})");
if (auction.LastClickAtUtc is { } lastClick && (DateTime.UtcNow - lastClick).TotalMilliseconds < CooldownMs)
return BidDecision.No(LossReasons.Kind.Cooldown, $"puntata fatta {(DateTime.UtcNow - lastClick).TotalMilliseconds:F0} ms fa");
var product = _products.Find(auction.ProductKey);
if (ProductRules.QuietHoursApply(auction.QuietHoursOverride, product, settings) &&
BiddingHours.IsQuiet(nowLocal, settings.QuietHoursStart, settings.QuietHoursEnd))
return BidDecision.No(LossReasons.Kind.FasciaOraria, BiddingHours.Explanation(settings.QuietHoursStart, settings.QuietHoursEnd));
var used = auction.MyBidsForLimits;
if (auction.MaxBids > 0 && used >= auction.MaxBids)
return BidDecision.No(LossReasons.Kind.PuntateAsta, $"limite di puntate dell'asta raggiunto ({used}/{auction.MaxBids})");
if (settings.MaxBidsPerAuction > 0 && auction.SessionBidCount >= settings.MaxBidsPerAuction)
return BidDecision.No(LossReasons.Kind.PuntateAsta, $"limite di puntate per asta raggiunto ({auction.SessionBidCount}/{settings.MaxBidsPerAuction})");
if (settings.MaxBidsPerSession > 0 && SessionBids >= settings.MaxBidsPerSession)
return BidDecision.No(LossReasons.Kind.PuntateSessione, $"limite di puntate per sessione raggiunto ({SessionBids}/{settings.MaxBidsPerSession})");
if (auction.MaxPrice > 0 && state.Price > auction.MaxPrice + 1e-9)
return BidDecision.No(LossReasons.Kind.PrezzoMassimo,
$"prezzo {state.Price.ToString("0.00", it)} EUR oltre il massimo {auction.MaxPrice.ToString("0.00", it)} EUR");
if (!settings.LearningEnabled)
return BidDecision.Yes(LossReasons.Kind.SoloLimiti, "apprendimento spento: si punta entro i paletti");
// ── 3. Modello ────────────────────────────────────────────────────
var value = ProductRules.ValueOf(product, auction.BuyNowPrice);
if (value is not > 0)
return new BidDecision { ShouldBid = true, Kind = LossReasons.Kind.SenzaStima, Reason = "valore del prodotto ignoto: si punta entro i paletti", BidCost = cost };
var ctx = _learning.BuildContext(auction, state, nowLocal, me);
if (ctx is not { } c)
return new BidDecision { ShouldBid = true, Kind = LossReasons.Kind.SenzaStima, Reason = "nessuna puntata recente da cui stimare: si punta entro i paletti", BidCost = cost, Value = value };
var pModel = _learning.PredictUnanswered(c);
var factor = _learning.OwnBidFactor;
var p = Math.Clamp(pModel * factor, 0, 1);
var spent = auction.MyBidsCost;
var hedge = settings.BuyNowHedgeEnabled && ProductRules.HasExplicitValue(product);
var situation = new Theory.BidSituation(
PWin: p, Value: value.Value, CurrentPrice: state.Price, BidCost: cost, TransactionFee: settings.TransactionFeeEuro,
Shipping: auction.Shipping ?? 0, ListPrice: auction.BuyNowPrice, BidsSpentEuro: spent, HedgeEnabled: hedge);
var ev = Theory.BidExpectedValue(situation);
var breakEven = Theory.BreakEvenPWin(situation);
var key = ThompsonBandit.KeyOf(c);
bool altBid;
double altP;
lock (_rngSync) (altBid, altP) = _learning.Bandit.Decide(key, situation, _rng);
var numbers = Math.Abs(factor - 1) > 0.001
? $"P {pModel.ToString("P2", it)} x correzione {factor.ToString("N2", it)} = {p.ToString("P2", it)}, serve {breakEven.ToString("P2", it)}, puntata {cost.ToString("0.00", it)} EUR, valore atteso {ev.ToString("+0.000;-0.000", it)} EUR"
: $"P {p.ToString("P2", it)}, serve {breakEven.ToString("P2", it)}, puntata {cost.ToString("0.00", it)} EUR, valore atteso {ev.ToString("+0.000;-0.000", it)} EUR";
var decision = new BidDecision
{
PModel = pModel, PWin = p, OwnBidFactor = factor, Ev = ev, BidCost = cost, Value = value,
ContextKey = key, AltAction = altBid ? "BID" : "NO-OP", PBandit = altP, Context = c
};
if (!_learning.IsReady(settings))
{
decision.ShouldBid = true;
decision.Kind = LossReasons.Kind.NonPronto;
decision.Reason = $"modello non ancora pronto ({_learning.AuctionsLearned}/{settings.LearningMinAuctions} aste): si punta entro i paletti; parere {numbers}";
return decision;
}
if (ev > 0)
{
decision.ShouldBid = true;
decision.Kind = LossReasons.Kind.Punta;
decision.Reason = numbers;
return decision;
}
// Esplorazione: qualche puntata al giorno dove il bandit ha visto poco e la sua
// estrazione dice che potrebbe convenire. Solo dal vivo: in Osserva non c'è niente
// da imparare puntando.
var evidence = _learning.Bandit.Evidence(key);
if (!shadow && altBid && evidence < LearningService.ExplorationEvidence && _learning.ExplorationAvailable(settings))
{
decision.ShouldBid = true;
decision.Kind = LossReasons.Kind.Esplora;
decision.Reason = $"esplorazione ({_learning.ExplorationUsedToday + 1}/{settings.ExplorationBidsPerDay} oggi): contesto visto {evidence.ToString("N0", it)} volte, P estratta {altP.ToString("P2", it)}; {numbers}";
return decision;
}
decision.ShouldBid = false;
decision.Kind = LossReasons.Kind.EvNegativo;
decision.Reason = numbers;
return decision;
}
/// <summary>Una puntata inviata dal motore, riuscita o no.</summary>
public void NoteBidSent(AuctionInfo auction, bool success)
{
auction.SessionBidCount++;
Interlocked.Increment(ref _sessionBids);
if (success)
{
auction.SuccessfulBids++;
auction.LastMyBidAtUtc = DateTime.UtcNow;
}
else auction.FailedBids++;
}
}
@@ -0,0 +1,73 @@
namespace BidooBidBot.Strategy;
/// <summary>
/// Fascia oraria in cui non si punta (portata dal legacy).
///
/// <para><b>Perché.</b> Su 6060 aste concluse la chiusura mediana in percentuale del valore è
/// il 4,6% alle 12 ma l'8,6% a mezzanotte e il 9,7% alle 9: di notte Bidoo sospende e la
/// concorrenza si concentra sulle poche aste rimaste. Di fabbrica la fascia è spenta (il
/// modello vede l'ora e ne tiene conto da sé); chi la vuole la accende.</para>
///
/// <para><b>Cosa fa.</b> Sospende le puntate, non il monitoraggio: l'asta resta Attiva e
/// riprende da sola a fine fascia. Classe pura, l'ora arriva da fuori.</para>
/// </summary>
public static class BiddingHours
{
public const int DefaultStart = 0;
public const int DefaultEnd = 10;
/// <summary>
/// L'ora cade nella fascia? Inizio incluso, fine esclusa; una fascia a cavallo della
/// mezzanotte (22-6) funziona; inizio uguale a fine = filtro spento.
/// </summary>
public static bool IsQuiet(int hour, int start, int end)
{
hour = Normalize(hour);
start = Normalize(start);
end = Normalize(end);
if (start == end) return false;
return start < end ? hour >= start && hour < end : hour >= start || hour < end;
}
public static bool IsQuiet(DateTime when, int start, int end) => IsQuiet(when.Hour, start, end);
public static string Explanation(int start, int end) =>
$"puntata saltata: fascia oraria sospesa ({Normalize(start):00}:00-{Normalize(end):00}:00). " +
"L'asta resta attiva e riprende a puntare da sola alla fine della fascia.";
private static int Normalize(int hour)
{
var h = hour % 24;
return h < 0 ? h + 24 : h;
}
}
/// <summary>
/// Se un'asta conclusa può sparire da sola dall'elenco (portata dal legacy). Si toglie di
/// serie ciò che è stato solo osservato; si trattiene ciò su cui c'è stato un esborso, le
/// vinte (da confermare su Bidoo) e le finite mentre erano Attive (il registro dice perché
/// non ha puntato). Nel dubbio si trattiene. Classe pura.
/// </summary>
public static class FinishedAuctionCleanup
{
public sealed class Options
{
public bool Enabled { get; set; } = true;
public bool KeepWithMyBids { get; set; } = true;
public bool KeepWon { get; set; } = true;
public bool KeepEndedWhileActive { get; set; } = true;
}
public readonly record struct Verdict(bool Remove, string Reason);
public static Verdict Decide(bool concluded, bool won, int myBids, bool wasActive, Options? options)
{
options ??= new Options();
if (!options.Enabled) return new Verdict(false, "rimozione automatica spenta");
if (!concluded) return new Verdict(false, "asta non conclusa");
if (options.KeepWon && won) return new Verdict(false, "vinta: resta in elenco per la conferma su Bidoo");
if (options.KeepWithMyBids && myBids > 0) return new Verdict(false, $"trattenuta: ci hai speso {myBids} puntate, controllala a mano");
if (options.KeepEndedWhileActive && wasActive) return new Verdict(false, "trattenuta: era Attiva quando è finita, il registro dice perché non ha puntato");
return new Verdict(true, "conclusa senza puntate mie: tolta dall'elenco");
}
}
@@ -0,0 +1,240 @@
using System.Globalization;
using System.Text.Json;
using BidooBidBot.Data;
using BidooBidBot.Engine;
using BidooBidBot.Logging;
using BidooBidBot.Settings;
namespace BidooBidBot.Strategy;
/// <summary>Dove finiscono le righe della contabilità del rischio.</summary>
public interface IRiskLedger
{
void Append(string kind, double amountEuro, string? auctionId, string? note);
}
/// <summary>Contabilità su PostgreSQL (tabella <c>risk_ledger</c>), scritta dalla coda.</summary>
public sealed class DbRiskLedger : IRiskLedger
{
private readonly WriteQueue _queue;
public DbRiskLedger(WriteQueue queue) => _queue = queue;
public void Append(string kind, double amountEuro, string? auctionId, string? note) =>
_queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro, auction_id, note) VALUES(now(), $1, $2, $3, $4)",
kind, Math.Round(amountEuro, 2), auctionId, note);
}
/// <summary>
/// Il gestore del rischio (portato dal legacy, specifica §3.4): i paletti duri che il modello
/// non può scavalcare. Ogni puntata dal vivo passa da <see cref="Authorize"/>.
///
/// <list type="bullet">
/// <item><b>HALT persistente</b>: scritto nel documento <c>risk/halt</c>, sopravvive al
/// riavvio e si toglie solo a mano dalle Impostazioni (registro + Telegram).</item>
/// <item>Stop-loss del giorno e drawdown dal picco portano in HALT da soli.</item>
/// <item>Tetto di spesa del giorno e aste in gioco insieme fermano la puntata, non tutto.</item>
/// </list>
/// Tutti a zero di fabbrica = nessun limite. La contabilità del giorno sta in memoria (si
/// legge dal database all'avvio): la verifica per puntata non tocca mai il database.
/// </summary>
public sealed class RiskManager
{
public readonly record struct Verdict(bool Allowed, string? Reason);
public sealed record HaltInfo(string Reason, DateTime AtUtc, bool Automatic);
public const string HaltDocument = "risk/halt";
private readonly object _sync = new();
private readonly IDocumentStore _docs;
private readonly IRiskLedger _ledger;
private readonly Func<DateTime> _localNow;
private readonly AppLog? _log;
private DateTime _day;
private double _todaySpent;
private double _todayGained;
private double _cumulative;
private double _peak;
private HaltInfo? _halt;
/// <summary>Scatta a ogni HALT e a ogni ripresa (Telegram, interfaccia).</summary>
public event Action<HaltInfo?>? HaltChanged;
public RiskManager(IDocumentStore docs, IRiskLedger ledger, Func<DateTime>? localNow = null, AppLog? log = null)
{
_docs = docs;
_ledger = ledger;
_localNow = localNow ?? (() => AppInfo.LocalNow);
_log = log;
_day = _localNow().Date;
_halt = ReadHalt();
}
private HaltInfo? ReadHalt()
{
var json = _docs.Get(HaltDocument);
if (string.IsNullOrEmpty(json)) return null;
try { return JsonSerializer.Deserialize<HaltInfo>(json); }
catch (JsonException) { return new HaltInfo("HALT registrato in un formato illeggibile", DateTime.UtcNow, false); }
}
/// <summary>Carica la contabilità dal database: spesi e incassati oggi, saldo cumulato e picco.</summary>
public async Task LoadAsync(Db db)
{
var dayStartUtc = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(_localNow().Date, DateTimeKind.Unspecified), AppInfo.TimeZone);
var today = await db.QueryOneAsync(
"SELECT COALESCE(SUM(CASE WHEN kind = 'bid' THEN -amount_euro ELSE 0 END), 0) AS spent, " +
" COALESCE(SUM(CASE WHEN kind = 'win' THEN amount_euro ELSE 0 END), 0) AS gained " +
"FROM risk_ledger WHERE ts >= $1 AND kind IN ('bid', 'win')",
r => new[] { r.Dbl("spent"), r.Dbl("gained") }, dayStartUtc).ConfigureAwait(false);
var totals = await db.QueryOneAsync(
"SELECT COALESCE(SUM(amount_euro), 0) AS cum, COALESCE(MAX(running), 0) AS peak FROM (" +
" SELECT amount_euro, SUM(amount_euro) OVER (ORDER BY id) AS running FROM risk_ledger WHERE kind IN ('bid', 'win')) t",
r => new[] { r.Dbl("cum"), r.Dbl("peak") }).ConfigureAwait(false);
lock (_sync)
{
_day = _localNow().Date;
_todaySpent = today?[0] ?? 0;
_todayGained = today?[1] ?? 0;
_cumulative = totals?[0] ?? 0;
_peak = Math.Max(0, totals?[1] ?? 0);
_halt = ReadHalt();
}
}
// ── HALT ─────────────────────────────────────────────────────────────
public HaltInfo? Halt { get { lock (_sync) return _halt; } }
public bool Halted => Halt != null;
public void SetHalt(string reason, bool automatic)
{
HaltInfo info;
lock (_sync)
{
if (_halt != null) return;
info = new HaltInfo(reason, DateTime.UtcNow, automatic);
_halt = info;
}
_docs.Set(HaltDocument, JsonSerializer.Serialize(info));
_ledger.Append("halt", 0, null, reason);
_log?.Warn("RISCHIO", $"HALT {(automatic ? "automatico" : "manuale")}: {reason}");
HaltChanged?.Invoke(info);
}
/// <summary>Toglie l'HALT (solo dalle Impostazioni). Restituisce false se non c'era.</summary>
public bool Resume()
{
lock (_sync)
{
if (_halt == null) return false;
_halt = null;
}
_docs.Delete(HaltDocument);
_ledger.Append("resume", 0, null, "HALT tolto a mano");
_log?.Info("RISCHIO", "HALT tolto: le puntate dal vivo possono riprendere");
HaltChanged?.Invoke(null);
return true;
}
// ── Contabilità ──────────────────────────────────────────────────────
private void RollDay()
{
var today = _localNow().Date;
if (today == _day) return;
_day = today;
_todaySpent = 0;
_todayGained = 0;
}
/// <summary>Una puntata dal vivo riuscita: esce il suo costo effettivo.</summary>
public void NoteBidSpent(string auctionId, double bidCost)
{
if (bidCost <= 0) return;
lock (_sync)
{
RollDay();
_todaySpent += bidCost;
_cumulative -= bidCost;
}
_ledger.Append("bid", -bidCost, auctionId, null);
}
/// <summary>Una vincita: entra il valore reale meno prezzo, fee e spedizione (le puntate sono già uscite).</summary>
public void NoteWin(string auctionId, double netGain, string note)
{
lock (_sync)
{
RollDay();
_todayGained += netGain;
_cumulative += netGain;
if (_cumulative > _peak) _peak = _cumulative;
}
_ledger.Append("win", netGain, auctionId, note);
}
public readonly record struct Numbers(double TodaySpent, double TodayGained, double TodayNet, double Cumulative, double Peak, double Drawdown);
public Numbers Snapshot()
{
lock (_sync)
{
RollDay();
return new Numbers(_todaySpent, _todayGained, _todayGained - _todaySpent, _cumulative, _peak, _peak - _cumulative);
}
}
// ── Autorizzazione ───────────────────────────────────────────────────
/// <summary>
/// Può partire una puntata dal vivo su quest'asta? Nell'ordine: HALT, stop-loss del
/// giorno, drawdown, tetto di spesa del giorno (la puntata che sta per partire compresa),
/// aste in gioco insieme.
/// </summary>
public Verdict Authorize(AuctionInfo auction, AppSettings settings, double bidCost, IReadOnlyCollection<AuctionInfo>? all = null)
{
var halt = Halt;
if (halt != null) return new Verdict(false, $"HALT del gestore del rischio: {halt.Reason}. Si toglie dalle Impostazioni");
string? haltReason = null;
Verdict verdict = new(true, null);
var it = CultureInfo.GetCultureInfo("it-IT");
lock (_sync)
{
RollDay();
if (settings.DailyStopLossEuro > 0 && _todaySpent - _todayGained >= settings.DailyStopLossEuro)
{
haltReason = $"stop-loss giornaliero raggiunto: perdita netta di oggi {(_todaySpent - _todayGained).ToString("0.00", it)} EUR >= {settings.DailyStopLossEuro.ToString("0.00", it)} EUR";
}
else if (settings.MaxDrawdownEuro > 0 && _peak - _cumulative >= settings.MaxDrawdownEuro)
{
haltReason = $"drawdown massimo raggiunto: {(_peak - _cumulative).ToString("0.00", it)} EUR sotto il picco (limite {settings.MaxDrawdownEuro.ToString("0.00", it)} EUR)";
}
else if (settings.DailyBudgetEuro > 0 && _todaySpent + Math.Max(0, bidCost) > settings.DailyBudgetEuro + 1e-9)
{
verdict = new Verdict(false, $"tetto di spesa del giorno: spesi {_todaySpent.ToString("0.00", it)} EUR su {settings.DailyBudgetEuro.ToString("0.00", it)} EUR");
}
}
if (haltReason != null)
{
SetHalt(haltReason, automatic: true);
return new Verdict(false, haltReason);
}
if (!verdict.Allowed) return verdict;
if (settings.MaxConcurrentActiveAuctions > 0 && all != null && auction.SessionBidCount == 0)
{
var inPlay = all.Count(a => a.Mode == RunMode.Active && a.SessionBidCount > 0 && !a.IsFinished && a.Id != auction.Id);
if (inPlay >= settings.MaxConcurrentActiveAuctions)
return new Verdict(false, $"già {inPlay} aste in gioco insieme (limite {settings.MaxConcurrentActiveAuctions})");
}
return new Verdict(true, null);
}
}
@@ -0,0 +1,362 @@
using BidooBidBot.Ml;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Le formule del modello matematico (portati dal legacy).</summary>
public class TheoryTests
{
private static Theory.BidSituation S(double p, double value = 11, double price = 0.50, double c = 0.20,
double fee = 1.0, double ship = 0, double? list = null, double spent = 0, bool hedge = false) =>
new(p, value, price, c, fee, ship, list, spent, hedge);
[Fact]
public void Senza_copertura_la_puntata_si_paga_in_entrambi_i_rami()
{
Assert.Equal(0.5 * 9.29 - 0.5 * 0.20, Theory.BidExpectedValue(S(0.5)), 6);
Assert.Equal(-0.20, Theory.BidExpectedValue(S(0)), 6);
}
[Fact]
public void Il_pareggio_e_dove_il_valore_atteso_e_zero()
{
var s = S(0.123);
Assert.Equal(0, Theory.BidExpectedValue(s with { PWin = Theory.BreakEvenPWin(s) }), 6);
var hopeless = S(0.9, value: 1.0, price: 0.90);
Assert.Equal(1, Theory.BreakEvenPWin(hopeless));
Assert.False(Theory.ShouldBid(hopeless));
}
[Fact]
public void La_copertura_azzera_il_costo_di_sconfitta_solo_oltre_la_perdita_coperta()
{
Assert.Equal(0.20, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 1.00, hedge: true)));
Assert.Equal(0, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 2.20, hedge: true)));
Assert.Equal(0, Theory.LossBranchCost(S(0.01, value: 11, list: 11, hedge: true)));
Assert.Equal(0.20, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 5, hedge: false)));
}
[Fact]
public void Con_V_uguale_al_listino_la_copertura_rende_gratis_ogni_puntata()
{
var s = new Theory.BidSituation(0.001, 11, 1.48, 0.20, 1, 0, 11, 0, true);
Assert.True(Theory.BidExpectedValue(s) > 0);
Assert.True(Theory.BidExpectedValue(s with { HedgeEnabled = false }) < 0);
}
[Fact]
public void Sopravvivenza_kaplan_meier_e_poisson()
{
var cycles = new List<Theory.CycleObservation>();
for (var i = 0; i < 30; i++) cycles.Add(new(5.0, false));
for (var i = 0; i < 15; i++) cycles.Add(new(1.0, false));
for (var i = 0; i < 5; i++) cycles.Add(new(0, true));
Assert.Equal(0.25, Theory.WinProbabilityAtLead(cycles, 2.0)!.Value, 6);
Assert.Equal(0.10, Theory.WinProbabilityAtLead(cycles, 6.0)!.Value, 6);
Assert.Null(Theory.WinProbabilityAtLead(cycles.Take(10), 2.0));
var km = Theory.KaplanMeier(new[] { new Theory.CycleObservation(8, false), new(8, false), new(3, false), new(0, true) });
Assert.Equal(0.5, km[0].Survival, 6);
Assert.Equal(0.25, km[1].Survival, 6);
Assert.Equal(Math.Exp(-1), Theory.NoBidProbability(0.5, 2), 9);
Assert.Equal(55, Theory.CriticalBidders(11, 0.20), 6);
}
}
public class OnlineLogitTests
{
[Fact]
public void Impara_una_regola_semplice_e_resta_calibrato()
{
var m = new OnlineLogit(2);
var rnd = new Random(7);
for (var i = 0; i < 20000; i++)
{
var a = rnd.Next(2) == 1;
m.Update(new[] { a ? 1.0 : 0.0, rnd.Next(2) }, a);
}
Assert.True(m.Predict(new[] { 1.0, 0.0 }) > 0.9);
Assert.True(m.Predict(new[] { 0.0, 1.0 }) < 0.1);
var rare = new OnlineLogit(1);
for (var i = 0; i < 40000; i++) rare.Update(new[] { 1.0 }, rnd.NextDouble() < 0.02);
Assert.InRange(rare.Predict(new[] { 1.0 }), 0.01, 0.04);
}
[Fact]
public void Si_salva_e_i_parametri_vengono_dal_codice()
{
var m = new OnlineLogit(3) { LearningRate = 0.5 };
m.Update(new[] { 1.0, 0.0, 1.0 }, true);
var back = OnlineLogit.FromJson(m.ToJson(), 3);
Assert.Equal(m.Weights, back.Weights);
Assert.Equal(new OnlineLogit(3).LearningRate, back.LearningRate);
Assert.Equal(0, OnlineLogit.FromJson(m.ToJson(), 5).Updates);
}
}
public class NeuralNetTests
{
[Fact]
public void Impara_lo_xor()
{
var net = new NeuralNet(new[] { 2, 8, 1 }, seed: 3) { LearningRate = 0.02 };
var data = new[] { (new[] { 0.0, 0.0 }, false), (new[] { 0.0, 1.0 }, true), (new[] { 1.0, 0.0 }, true), (new[] { 1.0, 1.0 }, false) };
var rng = new Random(1);
for (var i = 0; i < 6000; i++)
{
var (x, y) = data[rng.Next(4)];
net.Update(x, y);
}
Assert.True(net.Predict(new[] { 0.0, 0.0 }) < 0.2);
Assert.True(net.Predict(new[] { 0.0, 1.0 }) > 0.8);
Assert.True(net.Predict(new[] { 1.0, 1.0 }) < 0.2);
}
[Fact]
public void Si_salva_identica_e_una_forma_diversa_riparte()
{
var net = new NeuralNet(new[] { 3, 4, 1 }, seed: 9);
for (var i = 0; i < 100; i++) net.Update(new[] { 0.1 * i, 0.5, 1.0 }, i % 3 == 0);
var back = NeuralNet.FromJson(net.ToJson(), new[] { 3, 4, 1 });
Assert.Equal(net.Predict(new[] { 0.3, 0.5, 1.0 }), back.Predict(new[] { 0.3, 0.5, 1.0 }), 12);
Assert.Equal(0, NeuralNet.FromJson(net.ToJson(), new[] { 5, 4, 1 }).Updates);
}
}
public class ThompsonBanditTests
{
[Fact]
public void Parte_dal_prior_e_converge_all_evidenza()
{
var b = new ThompsonBandit { BaseRate = 0.05, PriorStrength = 4 };
Assert.Equal(0.05, b.Mean("k"), 6);
for (var i = 0; i < 100; i++) b.Observe("k", i % 2 == 0);
Assert.True(Math.Abs(b.Mean("k") - 0.5) < 0.05);
Assert.Equal(100, b.Evidence("k"), 6);
Assert.Equal(b.Mean("k"), ThompsonBandit.FromJson(b.ToJson()).Mean("k"), 9);
}
[Fact]
public void Decide_con_il_valore_atteso_sul_p_estratto()
{
var b = new ThompsonBandit { BaseRate = 0.5, PriorStrength = 1000 };
var good = new Theory.BidSituation(0, 11, 0.50, 0.20, 1.0, 0, null, 0, false);
Assert.True(b.Decide("k", good, new Random(1)).Bid);
Assert.False(b.Decide("k", good with { Value = 1.0, CurrentPrice = 0.95 }, new Random(1)).Bid);
}
}
public class BidFeaturesTests
{
private static BidContext Ctx(double gap = 7, double auto = 0.8, double? ratio = 0.05) =>
new(gap, auto, 3, ratio, 12, DayOfWeek.Tuesday, 11, false, 2, 120, false, "50 bidoo shop");
[Fact]
public void Dimensione_nomi_e_una_casella_per_gruppo()
{
Assert.Equal(BidFeatures.Size, BidFeatures.Names.Length);
var x = BidFeatures.Build(Ctx());
Assert.Equal(BidFeatures.Size, x.Length);
int On(string prefix) => BidFeatures.Names.Select((n, i) => (n, i)).Count(t => t.n.StartsWith(prefix, StringComparison.Ordinal) && x[t.i] == 1);
Assert.Equal(1, On("ciclo"));
Assert.Equal(1, On("puntatori"));
Assert.Equal(1, On("prodotto#"));
Assert.Equal(1, On("tipico"));
Assert.Equal(1, On("aggancio"));
}
[Theory]
[InlineData(0, 0)] [InlineData(8, 0)] [InlineData(9, 1)] [InlineData(12, 2)] [InlineData(13, 3)] [InlineData(20, 4)] [InlineData(23, 5)]
public void Le_fasce_orarie_ricalcano_la_curva_misurata(int hour, int band) => Assert.Equal(band, BidFeatures.HourBand(hour));
[Fact]
public void Cicli_lunghi_cassetti_stabili_e_descrizioni()
{
Assert.Equal(2, BidFeatures.CountDeepCycles(new long[] { 100, 90, 88, 86, 70 }));
Assert.Equal(1, BidFeatures.CountDeepCycles(new long[] { 100, 0, 90, 60 }));
Assert.Equal(BidFeatures.ProductBucket("50 Bidoo Shop"), BidFeatures.ProductBucket("50 bidoo shop"));
foreach (var n in BidFeatures.Names)
{
Assert.All(n, ch => Assert.True(ch < 128));
Assert.NotEqual(n, BidFeatures.Describe(n));
}
var ignoto = BidFeatures.Build(Ctx(gap: -1, auto: -1, ratio: null));
Assert.Equal(1, ignoto[Array.IndexOf(BidFeatures.Names, "valoreIgnoto")]);
Assert.Equal(1, ignoto[Array.IndexOf(BidFeatures.Names, "quotaAutoIgnota")]);
}
}
public class AuctionProfileStatsTests
{
private static readonly DateTime Mon12 = new(2026, 9, 7, 12, 0, 0);
private static readonly DateTime Sat21 = new(2026, 9, 12, 21, 0, 0);
[Fact]
public void Si_restringe_verso_il_livello_sopra_con_pochi_esempi()
{
var s = new AuctionProfileStats();
for (var i = 0; i < 200; i++) s.Observe("altro", Mon12, 25, 0.05);
s.Observe("raro", Sat21, 100, 0.30);
Assert.InRange(s.Expect("raro", Sat21)!.Value.WinnerBids, 25, 40);
for (var i = 0; i < 200; i++) s.Observe("caro", Sat21, 100, 0.30);
Assert.InRange(s.Expect("caro", Sat21)!.Value.WinnerBids, 90, 100);
Assert.Null(new AuctionProfileStats().Expect("x", Mon12));
}
}
public class TrainingReaderTests
{
private static TrainingReader.Session Session(string winner, params (string User, int Sec, string Type)[] bids) =>
TrainingReader.Finish(new TrainingReader.Session
{
AuctionId = "1", ProductKey = "prova", BuyNowPrice = 10, AddedAtLocal = new DateTime(2026, 9, 7, 11, 0, 0),
Winner = winner, FinalPrice = bids.Length / 100.0, HasSummary = true, Me = "carla",
Bids = bids.Select((b, i) => new TrainingReader.Bid(i, b.User, 1_788_000_000 + b.Sec, b.Type, false, (i + 1) / 100.0)).ToList()
});
[Fact]
public void Etichetta_solo_l_ultima_e_marca_le_mie()
{
var s = Session("anna", ("bruno", 0, "Auto"), ("carla", 6, "Manuale"), ("anna", 16, "Auto"));
Assert.True(s.IsUsable);
var ex = TrainingReader.Examples(s).ToList();
Assert.Equal(2, ex.Count);
Assert.False(ex[0].Unanswered);
Assert.True(ex[0].Mine);
Assert.True(ex[1].Unanswered);
Assert.Equal(10, ex[1].Context.CycleSeconds);
}
[Fact]
public void Un_buco_in_fondo_rende_l_asta_inutilizzabile()
{
Assert.False(Session("zeta", ("bruno", 0, "Auto"), ("carla", 6, "Manuale"), ("anna", 16, "Auto")).IsUsable);
Assert.False(Session("anna", ("anna", 0, "Auto")).IsUsable);
}
}
/// <summary>Perché un'asta è andata così (famiglie allineate al mockup di «Perché perdo»).</summary>
public class LossReasonsTests
{
private static LossReasons.DecisionRow D(string action, string kind, bool shadow = false, double? p = null, string? outcome = null) =>
new(action, kind, p, shadow, outcome);
[Fact]
public void Mai_puntato_dice_il_motivo_piu_frequente()
{
var decisions = Enumerable.Repeat(D("NO-OP", LossReasons.Kind.EvNegativo, p: 0.003), 4).Append(D("NO-OP", LossReasons.Kind.PrezzoMassimo)).ToList();
var reason = LossReasons.Compute(decisions, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
Assert.StartsWith("mai puntato: il modello sconsigliava", reason);
Assert.Contains("4 decisioni su 5", reason);
Assert.Contains("vinta da anna", reason);
Assert.Equal("mai puntato: il modello sconsigliava", LossReasons.Group(reason));
}
[Fact]
public void Un_paletto_che_ferma_e_la_famiglia_fermato()
{
var decisions = Enumerable.Repeat(D("NO-OP", LossReasons.Kind.PrezzoMassimo), 3).ToList();
var reason = LossReasons.Compute(decisions, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
Assert.Equal("fermato: prezzo oltre il massimo", LossReasons.Group(reason));
}
[Fact]
public void Puntato_e_coperto_dice_da_chi_e_dopo_quanto()
{
var decisions = new[] { D("BID", LossReasons.Kind.Punta, p: 0.02), D("NO-OP", LossReasons.Kind.PrezzoMassimo) };
var bids = new[] { new LossReasons.MyBidRow(4.85, 6, "anna", "Auto", false) };
var reason = LossReasons.Compute(decisions, bids, false, "anna");
Assert.StartsWith("puntato 1 volta; l'ultima coperta da anna (autopuntata) dopo 6 s", reason);
Assert.Contains("poi fermato: prezzo oltre il massimo", reason);
Assert.Equal("puntato e coperto dall'autopuntata", LossReasons.Group(reason));
}
[Fact]
public void In_Osserva_si_dice_cosa_avrebbe_fatto()
{
var shadowOnly = new[] { D("NO-OP", LossReasons.Kind.EvNegativo, shadow: true), D("BID", LossReasons.Kind.Punta, shadow: true, outcome: "would_be_answered") };
var reason = LossReasons.Compute(shadowOnly, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
Assert.StartsWith("in Osserva avrebbe puntato 1 volte", reason);
Assert.Equal("in Osserva avrebbe puntato", LossReasons.Group(reason));
Assert.Equal("vinta", LossReasons.Compute(shadowOnly, Array.Empty<LossReasons.MyBidRow>(), true, "io"));
Assert.StartsWith("solo osservata", LossReasons.Compute(Array.Empty<LossReasons.DecisionRow>(), Array.Empty<LossReasons.MyBidRow>(), false, "x"));
}
}
public class ShadowReportTests
{
[Fact]
public void Il_ROI_per_puntata_ha_il_suo_intervallo_e_il_null_model()
{
var rows = new List<ShadowReport.Row>();
// 100 decisioni «punta»: 2 vincenti su un bene da 11 € a 0,50 €.
for (var i = 0; i < 100; i++)
rows.Add(new ShadowReport.Row("BID", "NO-OP", i < 2 ? "would_win" : "would_be_answered", 0.01, 0.50, 11, 0, 0.20, true, false));
var r = ShadowReport.Compute(rows, 1.0, 7);
var model = r.Policies[0];
Assert.Equal(100, model.Bids);
Assert.Equal(2, model.Wins);
Assert.Equal(2 * (11 - 0.51 - 1.0) - 100 * 0.20, model.Net, 6);
Assert.NotNull(model.Ci95);
Assert.False(model.BeatsNullModel);
Assert.Equal(0, r.Policies[3].Bids); // «non punta mai»
}
}
public class ForecastTests
{
[Fact]
public void La_previsione_e_condizionata_al_prezzo_e_copre_l_ottanta_per_cento()
{
var f = new AuctionForecast();
var rng = new Random(5);
var closes = new List<double>();
for (var i = 0; i < 200; i++)
{
var c = Math.Round(1 + rng.NextDouble() * rng.NextDouble() * 10, 2);
closes.Add(c);
f.Observe("buono", c, 50, 2, 40 + rng.Next(40), 10);
}
var at1 = f.Forecast(new ForecastInput("buono", 1.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!;
var at4 = f.Forecast(new ForecastInput("buono", 4.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!;
Assert.True(at4.Close >= 4.00);
Assert.True(at4.P10 >= 4.00);
Assert.True(at1.P10 <= at1.Close && at1.Close <= at1.P90);
Assert.NotNull(at1.WinnerBids);
Assert.NotNull(at1.MinutesLeft);
Assert.NotNull(at1.EvIfEnter);
// Copertura: nuove chiusure dalla stessa distribuzione cadono nell'intervallo circa 8 volte su 10.
var inside = 0;
for (var i = 0; i < 400; i++)
{
var c = Math.Round(1 + rng.NextDouble() * rng.NextDouble() * 10, 2);
if (c >= at1.P10 && c <= at1.P90) inside++;
}
Assert.InRange(inside / 400.0, 0.70, 0.90);
var back = AuctionForecast.FromJson(f.ToJson());
Assert.Equal(at1.Close, back.Forecast(new ForecastInput("buono", 1.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!.Close);
}
[Fact]
public void Senza_dati_non_si_inventa_e_gli_errori_si_riassumono()
{
Assert.Null(new AuctionForecast().Forecast(new ForecastInput("mai visto", 1, null, 2, null, null, 0.2, 1, 0, 2, 0)));
var s = ForecastErrors.Summarize(new[]
{
new ForecastErrors.Row(5, 3, 8, 6, 50, 60),
new ForecastErrors.Row(5, 3, 8, 9, 50, 40),
new ForecastErrors.Row(5, 3, 8, 4, null, null)
});
Assert.Equal(3, s.Auctions);
Assert.Equal(2.0 / 3, s.Coverage!.Value, 6);
Assert.Equal(1, s.MedianAbsError!.Value, 6);
}
}
@@ -0,0 +1,171 @@
using BidooBidBot.Bidoo;
using BidooBidBot.Data;
using BidooBidBot.Engine;
using BidooBidBot.Ml;
using BidooBidBot.Products;
using BidooBidBot.Settings;
using BidooBidBot.Strategy;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Il registratore delle aste su PostgreSQL (AuctionRecorderTests del legacy, rifatti).</summary>
[Collection("Database")]
public class RecorderTests
{
private readonly DatabaseFixture _fx;
public RecorderTests(DatabaseFixture fx) => _fx = fx;
private static BidHistoryEntry Bid(int cents, string user, long unix, string type, bool mine = false) =>
new() { Price = cents / 100m, Username = user, Timestamp = unix, BidType = type, IsMyBid = mine };
[DbFact]
public async Task Una_storia_completa_da_risposte_esiti_e_previsione_realta()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var recorder = new AuctionRecorder(queue, db, () => new AppSettings(), () => "io");
await recorder.InitAsync();
var a = new AuctionInfo("900") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", Url = "u", BuyNowPrice = 50, Shipping = 1 };
var rec = (await recorder.PrepareAsync(a))!;
// Storico: 4,10 anna, 4,11 io, 4,12 bruno (risponde a me dopo 6 s), 4,13 io (l'ultima).
rec.ForeignBid(Bid(410, "anna", 1000, "Manuale"));
rec.ForeignBid(Bid(411, "io", 1004, "Manuale", mine: true));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto"));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto")); // doppione: non si riscrive
rec.ForeignBid(Bid(413, "io", 1016, "", mine: true));
rec.ForeignBid(Bid(413, "io", 1016, "Manuale", mine: true)); // il tipo arriva dopo: si aggiorna
rec.Reset(1, 4.12, "bruno");
var state = new AuctionState { Price = 4.10, Timer = 1.2 };
var d1 = recorder.RecordDecision(a, state, new DecisionRecord("punta", "BID", 0.02, 0.03, 1, 0.02, 0.1, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false,
new DecisionState { Ctx = new BidContext(9, 0.5, 2, 0.08, 12, DayOfWeek.Monday, 11, false, 0, 410, false, "buono amazon 50"), Price = 4.10 }));
rec.MyBid(4.10, 500, 480, 0.3, 60, 70, true, null, 1, 1406, 926, 480, d1, 0.02, "punta", manual: false);
var d2 = recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("punta", "BID", 0.03, null, 1, 0.03, 0.2, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false, new DecisionState()));
rec.MyBid(4.12, 500, 490, 0.2, 60, 70, true, null, 2, 1405, 925, 480, d2, 0.03, "punta", manual: false);
recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("ev-negativo", "NO-OP", 0.001, null, 1, 0.001, -0.1, 0.13, 50, "no", "k", "logit", "v", "NO-OP", 500, true, new DecisionState()));
recorder.RecordForecast(a, new ForecastResult(4.50, 3.00, 6.00, 40, 5, 0.1, 1, 0.5, "prova", 20, DateTime.UtcNow, 4.10), initial: true);
recorder.Close(a, new CloseSummary(DateTime.UtcNow, "vinta", "EndedWon", true, "io", 4.13, 50, 1, null, 0.13, 1, 2, 0.26,
3, 1, 1, 3, 4, 0.5, true, true, 12, DateTime.UtcNow.AddMinutes(-12), DateTime.UtcNow.AddMinutes(-12), 60, 80, 120, 500, 0,
500, false, 0, 2, 0, 0.3, "[]", "{}", "attiva", null));
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(0, queue.Failed);
Assert.Equal(4L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = '900'"));
Assert.Equal("Manuale", await db.ScalarAsync<string>("SELECT bid_type FROM bids WHERE auction_id = '900' AND price_after = 4.13"));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM resets WHERE auction_id = '900'"));
// La mia a 4,10 (prezzo dopo 4,11) è stata coperta da bruno a 4,12 dopo 6 s; quella a 4,12 è rimasta l'ultima.
var first = await db.QueryOneAsync("SELECT answered_by, answered_type, answered_after_s, unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.10",
r => new { By = r.StrOrNull("answered_by"), Type = r.StrOrNull("answered_type"), After = r.DblOrNull("answered_after_s"), U = r.BoolOrNull("unanswered") });
Assert.Equal("bruno", first!.By);
Assert.Equal("Auto", first.Type);
Assert.Equal(6, first.After);
Assert.False(first.U);
Assert.True(await db.ScalarAsync<bool>("SELECT unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.12"));
Assert.Equal("answered", await db.ScalarAsync<string>("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d1));
Assert.Equal("won", await db.ScalarAsync<string>("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d2));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bot_decisions WHERE auction_id = '900' AND shadow AND outcome = 'right_skip'"));
Assert.True(await db.ScalarAsync<bool>("SELECT bool_and(has_my_bid) FROM bot_decisions WHERE auction_id = '900'"));
var f = await db.QueryOneAsync("SELECT actual_close, error_close, in_interval FROM auction_forecasts WHERE auction_id = '900'",
r => new { Actual = r.Dbl("actual_close"), Err = r.Dbl("error_close"), In = r.Bool("in_interval") });
Assert.Equal(4.13, f!.Actual, 6);
Assert.Equal(4.13 - 4.50, f.Err, 6);
Assert.True(f.In);
Assert.Equal("vinta", await db.ScalarAsync<string>("SELECT outcome FROM auctions WHERE auction_id = '900'"));
Assert.Equal(1, await db.ScalarAsync<int>("SELECT win_count FROM bidders WHERE username = 'io'"));
Assert.Equal(2, await db.ScalarAsync<int>("SELECT n_bids FROM bidders WHERE username = 'io'"));
}
[DbFact]
public async Task Riaprendo_un_asta_gia_seguita_non_si_duplicano_le_puntate()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var a = new AuctionInfo("901") { Name = "X", ProductKey = "x" };
var first = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
(await first.PrepareAsync(a))!.ForeignBid(Bid(101, "anna", 1000, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var restarted = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
var rec = (await restarted.PrepareAsync(a))!;
rec.ForeignBid(Bid(101, "anna", 1000, "Auto"));
rec.ForeignBid(Bid(102, "bruno", 1005, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.Equal(2L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = '901'"));
}
[DbFact]
public async Task Senza_registrazione_non_si_scrive_nulla()
{
await _fx.TruncateAsync();
var off = new AuctionRecorder(null, null, () => new AppSettings(), () => null);
Assert.Null(await off.PrepareAsync(new AuctionInfo("902")));
Assert.False(off.Enabled);
}
[DbFact]
public async Task Il_rischio_rilegge_la_contabilita_del_giorno()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var docs = new MemoryDocumentStore();
var risk = new RiskManager(docs, new DbRiskLedger(queue));
risk.NoteBidSpent("a", 0.20);
risk.NoteBidSpent("a", 0.20);
risk.NoteWin("a", 1.50, "vinta");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var reloaded = new RiskManager(docs, new DbRiskLedger(queue));
await reloaded.LoadAsync(db);
var n = reloaded.Snapshot();
Assert.Equal(0.40, n.TodaySpent, 2);
Assert.Equal(1.50, n.TodayGained, 2);
Assert.Equal(1.10, n.Cumulative, 2);
Assert.Equal(1.10, n.Peak, 2);
}
[DbFact]
public async Task Prodotti_e_statistiche_si_salvano_e_si_ricalcolano()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var store = new ProductStore(queue);
store.Upsert(new ProductRecord { ProductKey = "buono", DisplayName = "Buono", MarketValue = 45, Followed = true, MaxPrice = 6.5 });
store.MarkProposed("buono", "777");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var again = new ProductStore(queue);
await again.LoadAsync(db);
Assert.Equal(45, again.Find("buono")!.MarketValue);
Assert.True(again.IsHandled("777"));
Assert.Equal(45.0, await db.ScalarAsync<double>("SELECT market_price_est FROM items WHERE product_key = 'buono'"));
for (var i = 0; i < 6; i++)
await db.ExecuteAsync("INSERT INTO auctions(auction_id, product_key, name, outcome, final_price, end_time, winner_bids_paid, winner_bids_free, won_by_me, my_bids, my_bids_cost, buy_now_price) " +
"VALUES($1, 'buono', 'Buono', 'persa', $2, now(), 5, 20, $3, $4, $5, 50)", $"s{i}", 3.0 + i, i == 0, i == 0 ? 10 : 0, i == 0 ? 1.3 : 0);
var stats = (await ProductStatsRepository.RefreshAsync(db, queue, "buono", 1.0))!;
Assert.Equal(6, stats.Auctions);
Assert.Equal(1, stats.Won);
Assert.Equal(5.5, stats.AvgFinal, 6);
Assert.Equal(25, stats.AvgWinnerBids);
Assert.Equal(3.0 + 1.3 + 1.0, stats.AvgRealCostWon!.Value, 6);
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.True((await ProductStatsRepository.LoadAllAsync(db)).ContainsKey("buono"));
}
}
@@ -0,0 +1,442 @@
using BidooBidBot.Bidoo;
using BidooBidBot.Data;
using BidooBidBot.Engine;
using BidooBidBot.Ml;
using BidooBidBot.Products;
using BidooBidBot.Settings;
using BidooBidBot.Strategy;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Dati dell'apprendimento in memoria, per provare servizio e strategia senza PostgreSQL.</summary>
public sealed class MemoryLearningData : ILearningData
{
public Dictionary<string, TrainingReader.Session> Sessions { get; } = new();
public HashSet<string> Learned { get; } = new();
public Dictionary<string, string> Reasons { get; } = new();
public List<(double PWin, string Outcome)> Own { get; } = new();
public Task FlushAsync() => Task.CompletedTask;
public Task<List<string>> PendingAuctionIdsAsync() => Task.FromResult(Sessions.Keys.Where(k => !Learned.Contains(k)).ToList());
public Task<int> PendingCountAsync() => Task.FromResult(Sessions.Keys.Count(k => !Learned.Contains(k)));
public Task<List<string>> ClosedAuctionIdsAsync(int max) => Task.FromResult(Sessions.Keys.ToList());
public Task<TrainingReader.Session?> LoadSessionAsync(string id, string? me) => Task.FromResult(Sessions.GetValueOrDefault(id));
public Task<bool> IsLearnedAsync(string id) => Task.FromResult(Learned.Contains(id));
public void MarkLearned(string id) => Learned.Add(id);
public Task MarkAllUnlearnedAsync() { Learned.Clear(); return Task.CompletedTask; }
public Task<List<(double PWin, string Outcome)>> OwnBidOutcomesAsync(string? id) => Task.FromResult(id == null ? Own.ToList() : new List<(double, string)>());
public Task<List<(string ContextKey, string Outcome)>> DecisionOutcomesAsync(string id) => Task.FromResult(new List<(string, string)>());
public Task<List<string>> AuctionsWithDecisionOutcomesAsync() => Task.FromResult(new List<string>());
public Task<List<LossReasons.DecisionRow>> DecisionsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.DecisionRow>());
public Task<List<LossReasons.MyBidRow>> MyBidsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.MyBidRow>());
public void WriteLossReason(string id, string reason) => Reasons[id] = reason;
public Task<List<ClosedAuctionRow>> ClosedAuctionsAsync(int max) => Task.FromResult(new List<ClosedAuctionRow>());
public Task<List<(string Reason, int Count)>> LossReasonSummaryAsync(int days) => Task.FromResult(new List<(string, int)>());
public Task<List<ShadowReport.Row>> ShadowRowsAsync(int days, bool? shadow, double cost) => Task.FromResult(new List<ShadowReport.Row>());
}
internal sealed class ListLedger : IRiskLedger
{
public List<(string Kind, double Amount)> Rows { get; } = new();
public void Append(string kind, double amountEuro, string? auctionId, string? note) => Rows.Add((kind, amountEuro));
}
/// <summary>Il gestore del rischio (portati dal legacy, senza database).</summary>
public class RiskManagerTests
{
private static AuctionInfo Auction(string id, RunMode mode = RunMode.Active, int bids = 0) =>
new(id) { Name = "Prova", Mode = mode, SessionBidCount = bids };
[Fact]
public void Lo_stop_loss_porta_in_halt_e_l_halt_resta_dopo_il_riavvio()
{
var docs = new MemoryDocumentStore();
var ledger = new ListLedger();
var risk = new RiskManager(docs, ledger);
var s = new AppSettings { DailyStopLossEuro = 1.00 };
for (var i = 0; i < 4; i++) risk.NoteBidSpent("a", 0.20);
Assert.True(risk.Authorize(Auction("a"), s, 0.20).Allowed);
risk.NoteBidSpent("a", 0.20);
Assert.False(risk.Authorize(Auction("a"), s, 0.20).Allowed);
Assert.True(risk.Halted);
Assert.True(risk.Halt!.Automatic);
// Un nuovo gestore sugli stessi documenti (il riavvio) vede ancora l'HALT.
var again = new RiskManager(docs, ledger);
Assert.True(again.Halted);
Assert.False(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
Assert.True(again.Resume());
Assert.True(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
Assert.Contains(ledger.Rows, r => r.Kind == "halt");
Assert.Contains(ledger.Rows, r => r.Kind == "resume");
}
[Fact]
public void Vincite_drawdown_e_tetto_del_giorno()
{
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
for (var i = 0; i < 5; i++) risk.NoteBidSpent("a", 0.20);
risk.NoteWin("a", 3.00, "vinta");
var n = risk.Snapshot();
Assert.Equal(1.00, n.TodaySpent, 6);
Assert.Equal(2.00, n.Cumulative, 6);
Assert.True(risk.Authorize(Auction("a"), new AppSettings { DailyStopLossEuro = 1.0 }, 0.2).Allowed);
var dd = new RiskManager(new MemoryDocumentStore(), new ListLedger());
dd.NoteWin("a", 5.00, "vinta");
dd.NoteBidSpent("b", 0.20);
dd.NoteBidSpent("b", 0.20);
Assert.True(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
dd.NoteBidSpent("b", 0.20);
Assert.False(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
var budget = new RiskManager(new MemoryDocumentStore(), new ListLedger());
budget.NoteBidSpent("a", 0.20);
budget.NoteBidSpent("a", 0.20);
Assert.False(budget.Authorize(Auction("a"), new AppSettings { DailyBudgetEuro = 0.50 }, 0.20).Allowed);
Assert.False(budget.Halted);
}
[Fact]
public void Le_aste_in_gioco_insieme_hanno_un_tetto()
{
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
var all = new List<AuctionInfo> { Auction("a", bids: 3), Auction("b", bids: 1), Auction("c"), Auction("d", RunMode.Watch, bids: 9) };
var s = new AppSettings { MaxConcurrentActiveAuctions = 2 };
Assert.False(risk.Authorize(all[2], s, 0.2, all).Allowed);
Assert.True(risk.Authorize(all[0], s, 0.2, all).Allowed);
}
[Fact]
public void Il_giorno_nuovo_azzera_la_spesa_del_giorno()
{
var now = new DateTime(2026, 9, 26, 23, 50, 0);
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger(), () => now);
risk.NoteBidSpent("a", 0.40);
Assert.Equal(0.40, risk.Snapshot().TodaySpent, 6);
now = now.AddMinutes(20);
Assert.Equal(0, risk.Snapshot().TodaySpent, 6);
Assert.Equal(-0.40, risk.Snapshot().Cumulative, 6);
}
}
public class BiddingHoursAndCleanupTests
{
[Theory]
[InlineData(0, true)] [InlineData(9, true)] [InlineData(10, false)] [InlineData(23, false)]
public void La_fascia_0_10(int hour, bool quiet) => Assert.Equal(quiet, BiddingHours.IsQuiet(hour, 0, 10));
[Fact]
public void Mezzanotte_ore_fuori_scala_e_filtro_spento()
{
Assert.True(BiddingHours.IsQuiet(23, 22, 6));
Assert.False(BiddingHours.IsQuiet(6, 22, 6));
for (var h = 0; h < 24; h++) Assert.False(BiddingHours.IsQuiet(h, 3, 3));
Assert.Equal(BiddingHours.IsQuiet(1, 0, 10), BiddingHours.IsQuiet(25, 0, 10));
Assert.Contains("00:00-10:00", BiddingHours.Explanation(0, 10));
}
[Fact]
public void La_pulizia_trattiene_cio_che_e_costato()
{
var o = new FinishedAuctionCleanup.Options();
Assert.True(FinishedAuctionCleanup.Decide(true, false, 0, false, o).Remove);
Assert.False(FinishedAuctionCleanup.Decide(false, false, 0, false, o).Remove);
Assert.Contains("12 puntate", FinishedAuctionCleanup.Decide(true, false, 12, false, o).Reason);
Assert.Contains("vinta", FinishedAuctionCleanup.Decide(true, true, 30, false, o).Reason);
Assert.Contains("Attiva", FinishedAuctionCleanup.Decide(true, false, 0, true, o).Reason);
Assert.False(FinishedAuctionCleanup.Decide(true, false, 0, false, new FinishedAuctionCleanup.Options { Enabled = false }).Remove);
}
}
public class ProductTests
{
[Theory]
[InlineData("SMARTPHONE XY ", "smartphone xy")]
[InlineData("Macchina Caffè Espresso", "macchina caffe espresso")]
[InlineData("Cuffie Wireless (Nero)", "cuffie wireless")]
[InlineData("Set 24 Pennelli Make-Up", "set 24 pennelli make up")]
[InlineData("Buono Amazon 50 €", "buono amazon 50")]
public void La_chiave_prodotto_normalizza(string name, string key) => Assert.Equal(key, ProductKey.From(name));
[Fact]
public void I_numeri_distinguono_i_modelli() =>
Assert.NotEqual(ProductKey.From("PowerBank 20000"), ProductKey.From("PowerBank 10000"));
[Fact]
public void Le_regole_del_prodotto_vincono_sui_predefiniti()
{
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50, AutoAddNewAuctionState = "Osserva" };
var none = ProductRules.Resolve(null, s, autoAdded: true);
Assert.Equal(20, none.MaxPrice);
Assert.Equal(RunMode.Watch, none.Mode);
var p = new ProductRecord { ProductKey = "x", MaxPrice = 8, MaxBids = 0, AutoState = "Attiva" };
var own = ProductRules.Resolve(p, s, autoAdded: true);
Assert.Equal(8, own.MaxPrice);
Assert.Equal(0, own.MaxBids); // lo zero esplicito è una scelta vera
Assert.Equal(RunMode.Active, own.Mode);
Assert.Equal(RunMode.Watch, ProductRules.ParseMode("boh"));
}
[Fact]
public void Il_valore_reale_scritto_vince_e_abilita_la_copertura()
{
Assert.Equal(11, ProductRules.ValueOf(null, 11));
Assert.False(ProductRules.HasExplicitValue(new ProductRecord()));
var p = new ProductRecord { MarketValue = 9.5 };
Assert.Equal(9.5, ProductRules.ValueOf(p, 11));
Assert.True(ProductRules.HasExplicitValue(p));
}
[Fact]
public void L_orizzonte_e_l_asta_gia_cominciata()
{
var s = new AppSettings { AutoAddMaxStartMinutes = 60 };
Assert.Equal(3600, ProductRules.HorizonSeconds(null, s));
Assert.Equal(0, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 0 }, s));
Assert.Equal(180 * 60, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 180 }, s));
Assert.False(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.01m }));
Assert.True(ProductRules.HasStarted(new CatalogAuction { LastBidder = "tizio" }));
Assert.True(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.05m }));
}
[Fact]
public void I_limiti_consigliati_seguono_la_copertura_e_il_budget()
{
var closes = new List<double>();
for (var i = 0; i < 100; i++) closes.Add(0.5 + i * 0.05); // 0,50 .. 5,45
var input = new ProductAdvice.Input(closes, Enumerable.Range(10, 50).ToList(), 50, 1, 25, 0.13, 10, 0.85, 0.10);
var advice = ProductAdvice.Suggest(input);
Assert.True(advice.HasAdvice);
Assert.InRange(advice.MaxPrice!.Value, 4.5, 4.8);
Assert.InRange(advice.CoverageReached, 84, 87);
Assert.NotNull(advice.MaxBids);
Assert.Contains("aste concluse", advice.Explanation);
var tight = ProductAdvice.Suggest(input with { Value = 5, MaxBids = 40 });
Assert.True(tight.LimitedByBudget);
Assert.False(ProductAdvice.Suggest(input with { FinalPrices = closes.Take(3).ToList() }).HasAdvice);
}
[Fact]
public void La_coerenza_delle_puntate_del_vincitore()
{
Assert.True(AuctionIntegrity.CheckWinnerBids(8.38, 25).IsTrustworthy);
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, null).IsTrustworthy);
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, 0).IsTrustworthy);
Assert.Contains("oltre il totale", AuctionIntegrity.CheckWinnerBids(0.10, 50).Reason);
Assert.True(AuctionIntegrity.CheckWinnerBids(0.03, 3).IsTrustworthy);
}
[Fact]
public void La_stellina_toglie_la_scheda_solo_senza_limiti_propri()
{
var store = new ProductStore(null);
store.SetFollowed("buono", "Buono", 1, true);
Assert.True(store.Find("buono")!.Followed);
store.SetFollowed("buono", "Buono", 1, false);
Assert.Null(store.Find("buono"));
store.Upsert(new ProductRecord { ProductKey = "caro", DisplayName = "Caro", Followed = true, MaxPrice = 5 });
store.SetFollowed("caro", "Caro", 0, false);
Assert.NotNull(store.Find("caro"));
store.MarkRemoved("caro", "123");
Assert.True(store.IsHandled("123"));
Assert.Equal("caro", store.FindFor(new CatalogAuction { Name = "Caro", ProductId = 0 })!.ProductKey);
}
}
/// <summary>La strategia: rischio solo dal vivo, poi i paletti, poi il modello.</summary>
public class BidStrategyTests
{
private static (BidStrategy Strategy, LearningService Learning, ProductStore Products, RiskManager Risk) Make(AccountBalance? balance = null)
{
var docs = new MemoryDocumentStore();
var settings = new AppSettings();
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, null);
var products = new ProductStore(null);
var risk = new RiskManager(docs, new ListLedger());
return (new BidStrategy(risk, learning, products, () => balance ?? new AccountBalance(1407, 927, 480)), learning, products, risk);
}
private static AuctionInfo Auction()
{
var a = new AuctionInfo("1") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", BuyNowPrice = 50, Mode = RunMode.Active };
lock (a.BidsLock)
{
a.RecentBids.Add(new BidHistoryEntry { Price = 4.12m, Username = "marco", Timestamp = 1_788_000_010, BidType = BidHistoryEntry.TypeAuto });
a.RecentBids.Add(new BidHistoryEntry { Price = 4.11m, Username = "lulu", Timestamp = 1_788_000_001, BidType = BidHistoryEntry.TypeManual });
}
return a;
}
private static AuctionState State(double price = 4.12, bool mine = false) =>
new() { Price = price, ServerUnixSeconds = 1_788_000_019, ExpiryUnixSeconds = 1_788_000_020, Status = AuctionStatus.Running, IsMyBid = mine };
[Fact]
public void Il_costo_effettivo_scala_per_la_quota_di_pagate()
{
var s = new AppSettings { AverageBidCostEuro = 0.20 };
Assert.Equal(0.20 * 927 / 1407, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, 927, 480)), 9);
Assert.Equal(0.20, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, null, null)), 9);
}
[Fact]
public void Il_rischio_vale_solo_dal_vivo()
{
var (strategy, _, _, risk) = Make();
risk.SetHalt("prova", automatic: false);
var live = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: false, "io", new DateTime(2026, 9, 26, 12, 0, 0));
Assert.Equal(LossReasons.Kind.Rischio, live.Kind);
var shadow = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: true, "io", new DateTime(2026, 9, 26, 12, 0, 0));
Assert.NotEqual(LossReasons.Kind.Rischio, shadow.Kind);
}
[Fact]
public void I_paletti_fermano_prima_del_modello()
{
var (strategy, _, _, _) = Make(new AccountBalance(900, 500, 400));
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
Assert.Equal(LossReasons.Kind.InTesta, strategy.Decide(Auction(), State(mine: true), new AppSettings(), null, true, "io", noon).Kind);
Assert.Equal(LossReasons.Kind.PuntateResidue, strategy.Decide(Auction(), State(), new AppSettings { MinimumRemainingBids = 1000 }, null, true, "io", noon).Kind);
var capped = Auction();
capped.MaxPrice = 4.00;
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(capped, State(), new AppSettings(), null, true, "io", noon).Kind);
var quiet = new AppSettings { QuietHoursEnabled = true, QuietHoursStart = 0, QuietHoursEnd = 10 };
Assert.Equal(LossReasons.Kind.FasciaOraria, strategy.Decide(Auction(), State(), quiet, null, true, "io", new DateTime(2026, 9, 26, 3, 0, 0)).Kind);
var full = Auction();
full.MaxBids = 2;
full.BidsUsedOnAuction = 2;
Assert.Equal(LossReasons.Kind.PuntateAsta, strategy.Decide(full, State(), new AppSettings(), null, true, "io", noon).Kind);
}
[Fact]
public void Col_modello_non_pronto_si_punta_entro_i_paletti_e_poi_decide_il_valore_atteso()
{
var (strategy, learning, _, _) = Make();
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
var early = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
Assert.Equal(LossReasons.Kind.NonPronto, early.Kind);
Assert.True(early.ShouldBid);
Assert.NotNull(early.Context);
learning.SetLearnedForTests(500);
var ready = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
Assert.True(ready.Kind is LossReasons.Kind.Punta or LossReasons.Kind.EvNegativo);
Assert.Equal(ready.Ev > 0, ready.ShouldBid);
Assert.Contains("valore atteso", ready.Reason);
}
[Fact]
public void Senza_valore_del_prodotto_si_punta_entro_i_paletti()
{
var (strategy, _, _, _) = Make();
var a = Auction();
a.BuyNowPrice = null;
Assert.Equal(LossReasons.Kind.SenzaStima, strategy.Decide(a, State(), new AppSettings(), null, true, "io", DateTime.Now).Kind);
}
[Fact]
public void La_correzione_sulle_mie_puntate_e_nei_limiti()
{
var (_, learning, _, _) = Make();
learning.SetOwnBidsForTests(10, 3.0, 6);
Assert.Equal(1.0, learning.OwnBidFactor);
learning.SetOwnBidsForTests(30, 3.0, 6);
Assert.Equal(6.5 / 3.5, learning.OwnBidFactor, 6);
learning.SetOwnBidsForTests(30, 0.5, 30);
Assert.Equal(4.0, learning.OwnBidFactor);
learning.SetOwnBidsForTests(30, 30, 0);
Assert.Equal(0.25, learning.OwnBidFactor);
}
}
public class LearningServiceTests
{
private static TrainingReader.Session Session(string id, int bids, Random rng)
{
var list = new List<TrainingReader.Bid>();
long t = 1_788_000_000;
var users = new[] { "anna", "bruno", "carla", "dino" };
for (var i = 0; i < bids; i++)
{
t += 2 + rng.Next(9);
list.Add(new TrainingReader.Bid(i, users[rng.Next(users.Length)], t, rng.Next(2) == 0 ? "Auto" : "Manuale", false, (i + 1) / 100.0));
}
return TrainingReader.Finish(new TrainingReader.Session
{
AuctionId = id, ProductKey = "buono", BuyNowPrice = 50, AddedAtLocal = new DateTime(2026, 9, 7, 11, 0, 0),
Bids = list, Winner = list[^1].User, FinalPrice = bids / 100.0, HasSummary = true
});
}
[Fact]
public async Task Studia_le_aste_chiuse_e_salva_nei_documenti()
{
var docs = new MemoryDocumentStore();
var data = new MemoryLearningData();
var rng = new Random(3);
for (var i = 0; i < 12; i++) data.Sessions[$"a{i}"] = Session($"a{i}", 30 + rng.Next(60), rng);
var settings = new AppSettings();
var learning = new LearningService(docs, data, () => settings, null);
await learning.LoadAsync();
var (done, usable) = await learning.StudyNowAsync(null, CancellationToken.None);
Assert.Equal(12, done);
Assert.Equal(12, usable);
Assert.Equal(12, learning.AuctionsLearned);
Assert.True(learning.ModelUpdates > 300);
Assert.NotNull(docs.Get("ml/model"));
Assert.Contains("\"count\":12", docs.Get("ml/learned"));
// Un secondo servizio sugli stessi documenti riparte da dove era.
var again = new LearningService(docs, data, () => settings, null);
await again.LoadAsync();
Assert.Equal(12, again.AuctionsLearned);
Assert.Equal(learning.ModelUpdates, again.ModelUpdates);
// La stessa asta chiusa non si impara due volte.
var closed = new ClosedAuctionInfo("a0", "Buono", "buono", DateTime.UtcNow, 0.5, 50, null, null, 3, false, "anna", 10);
Assert.Equal("già appresa", await again.OnAuctionClosedAsync(closed));
Assert.Null(await again.OnAuctionClosedAsync(closed));
}
[Fact]
public async Task Cambiare_le_variabili_fa_ristudiare_tutto()
{
var docs = new MemoryDocumentStore();
docs.Set("ml/model", new OnlineLogit(BidFeatures.Size).ToJson());
docs.Set("ml/features-version", """{"version":1}""");
docs.Set("ml/learned", """{"count":99}""");
var data = new MemoryLearningData();
data.Sessions["x"] = new TrainingReader.Session { AuctionId = "x", HasSummary = true };
var learning = new LearningService(docs, data, () => new AppSettings(), null);
await learning.LoadAsync();
Assert.Equal(0, learning.AuctionsLearned);
Assert.True(learning.FullStudyPending);
Assert.Contains("\"version\":2", docs.Get("ml/features-version"));
}
[Fact]
public async Task L_esplorazione_ha_un_budget_al_giorno()
{
var learning = new LearningService(new MemoryDocumentStore(), new MemoryLearningData(), () => new AppSettings(), null);
var s = new AppSettings { ExplorationBidsPerDay = 2 };
Assert.True(learning.ExplorationAvailable(s));
learning.NoteExplorationBid();
learning.NoteExplorationBid();
Assert.False(learning.ExplorationAvailable(s));
Assert.False(learning.ExplorationAvailable(new AppSettings { ExplorationBidsPerDay = 0 }));
await Task.CompletedTask;
}
}