La vecchia AutoBidder (WPF, SQLite, WebView2) resta in legacy/ in sola lettura: contiene il protocollo di Bidoo, l'orologio del server e il modello verificati, da portare nella riscrittura come servizio Docker per Unraid. La specifica della riscrittura passa in docs/SPECIFICA.md, i mockup dell'interfaccia in docs/mockup/, e CLAUDE.md diventa il file delle regole del nuovo progetto. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
8.9 KiB
C#
202 lines
8.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using AutoBidder.Data;
|
|
|
|
namespace AutoBidder.Ml
|
|
{
|
|
/// <summary>
|
|
/// Porta un'asta conclusa nella forma che serve ad addestrare: la sequenza delle
|
|
/// puntate in ordine di tempo dichiarato dal server, chi ha vinto, a quanto.
|
|
///
|
|
/// <para>La fonte è il database (<see cref="FromDatabase"/>). I test costruiscono le
|
|
/// sessioni direttamente, senza passare dal disco.</para>
|
|
/// </summary>
|
|
public static class DossierTrainingReader
|
|
{
|
|
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; }
|
|
|
|
/// <summary>Il nostro nome utente, dall'asta o da fuori.</summary>
|
|
public string Me { get; init; } = "";
|
|
|
|
/// <summary>
|
|
/// Utilizzabile per l'addestramento: chiusa, con almeno qualche puntata, e con
|
|
/// l'ultima puntata registrata che sia davvero del vincitore. Se non lo è, la
|
|
/// registrazione ha un buco proprio 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 del prodotto (prezzo finale in rapporto al valore) a una data
|
|
/// ora, oppure null se il profilo non sa niente. La passa chi addestra: è il
|
|
/// profilo del momento, e il lettore non deve conoscerlo.
|
|
/// </summary>
|
|
public delegate double? TypicalCloseRatio(string productKey, DateTime whenLocal);
|
|
|
|
// ── Dal database ─────────────────────────────────────────────────
|
|
|
|
/// <summary>L'asta indicata, dal database. Null se non esiste.</summary>
|
|
public static Session? FromDatabase(AuctionDatabase db, string auctionId, string? me = null)
|
|
{
|
|
var a = db.QueryOne(
|
|
"SELECT auction_id, product_key, buy_now_price, added_at, winner_user, final_price, outcome, me " +
|
|
"FROM auctions WHERE auction_id = ?1", auctionId);
|
|
if (a == null) return null;
|
|
|
|
var chiSonoIo = a.StrOrNull("me") ?? me ?? "";
|
|
|
|
var bids = db.Query(
|
|
"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", auctionId)
|
|
.Select(r => new Bid(
|
|
T: r.Dbl("seen_t"),
|
|
User: r.Str("username"),
|
|
UnixSeconds: r.LongOrNull("server_ts") ?? 0,
|
|
BidType: r.Str("bid_type"),
|
|
Mine: r.Bool("is_mine"),
|
|
Price: r.Dbl("price_after")))
|
|
.ToList();
|
|
|
|
return Finish(new Session
|
|
{
|
|
AuctionId = a.Str("auction_id"),
|
|
ProductKey = a.Str("product_key"),
|
|
BuyNowPrice = a.DblOrNull("buy_now_price"),
|
|
AddedAtLocal = (a.Date("added_at") ?? DateTime.MinValue) == DateTime.MinValue
|
|
? DateTime.MinValue
|
|
: a.Date("added_at")!.Value.ToLocalTime(),
|
|
Bids = bids,
|
|
Winner = a.Str("winner_user"),
|
|
FinalPrice = a.Dbl("final_price"),
|
|
HasSummary = a.StrOrNull("outcome") != null,
|
|
Me = chiSonoIo
|
|
});
|
|
}
|
|
|
|
/// <summary>Gli id delle aste concluse, dalla più vecchia alla più recente.</summary>
|
|
public static List<string> ClosedAuctionIds(AuctionDatabase db, int max = 0)
|
|
{
|
|
var ids = db.Query("SELECT auction_id FROM auctions WHERE outcome IS NOT NULL ORDER BY end_time")
|
|
.Select(r => r.Str("auction_id")).ToList();
|
|
return max > 0 && ids.Count > max ? ids.Skip(ids.Count - max).ToList() : ids;
|
|
}
|
|
|
|
/// <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 addestramento di un'asta: uno per puntata, con 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;
|
|
|
|
// Gli istanti dal più recente, per contare i cicli lunghi come li vedrebbe il
|
|
// motore nell'istante della decisione.
|
|
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
|
|
? DateTimeOffset.FromUnixTimeSeconds(b.UnixSeconds).ToLocalTime().DateTime
|
|
: 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? tipico = null;
|
|
if (typical != null && ratio is { } r && typical(s.ProductKey, when) is { } chiusura && chiusura > 0)
|
|
tipico = r / chiusura;
|
|
|
|
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: tipico);
|
|
|
|
yield return (ctx, i == bids.Count - 1, b.Mine);
|
|
}
|
|
}
|
|
|
|
// Le finestre guardano le puntate PRIMA di questa: sono quelle che si sarebbero
|
|
// viste nell'istante di decidere.
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|