Dal livello che sblocca il commercio la compagnia può comprare e vendere merci in proprio. Così può fare arbitraggio tra un produttore con il magazzino pieno e un consumatore a secco anche dove il vettore non ha contratti. Le regole sono nell'ADR 0016. - Ogni stazione della compagnia ha un magazzino: 500 unità e una giacenza di 25 centesimi per unità al mese, in balance.json, blocco «trading». La merce in magazzino rientra nell'invariante delle merci. - BuyGoods compra al prezzo locale marginale dell'ADR 0004, unità per unità, partendo dal più economico, dai produttori del bacino e dagli hub. La merce presa dagli hub conta come importata. - SellGoods vende ai consumatori del bacino partendo dal prezzo più alto, entro lo spazio libero e la cassa di ciascuno. Vende anche agli hub, e quella merce conta come esportata. - Il denaro di entrambi i comandi passa dal registro, sulla voce «Commercio». - ShipGoods (comando 40) spedisce la merce propria come pacchetto senza tariffa né consumatore. Il pacchetto entra nel magazzino di destinazione, che riserva lo spazio alla partenza. Il percorso dei pacchetti già esistenti non cambia: l'accettazione F4 dà ancora 35/20 guasti senza la linea e 75/2 con la linea. - Il salvataggio passa al corpo versione 4 (TradingSerializer). I salvataggi più vecchi si caricano con i magazzini vuoti, e i magazzini entrano nell'hash di stato. - MarketReport porta i magazzini nel blocco 1. Il Mercato globale ha il riquadro «Compravendita in proprio». - Le IA non commerciano ancora. Refs #31. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
207 lines
9.3 KiB
C#
207 lines
9.3 KiB
C#
using RailEnterprise.Core.Economy;
|
||
using RailEnterprise.Core.Rail;
|
||
|
||
namespace RailEnterprise.Core.Simulation.Systems;
|
||
|
||
/// <summary>Venditore o compratore nel bacino di una stazione per la compravendita in proprio.</summary>
|
||
public enum TradePartyKind : byte { Industry = 0, Hub = 1 }
|
||
|
||
/// <summary>
|
||
/// Controparte di uno scambio: industria (con l'indice dell'output o dell'input del bene) o hub;
|
||
/// <see cref="Limit"/> è il massimo di unità che può dare o ricevere, <see cref="Units"/> quelle
|
||
/// già scambiate, <see cref="Cents"/> il loro valore non arrotondato.
|
||
/// </summary>
|
||
public sealed class TradeParty
|
||
{
|
||
public required TradePartyKind Kind { get; init; }
|
||
public required int Target { get; init; }
|
||
public required int Slot { get; init; }
|
||
public required int Limit { get; init; }
|
||
public int Units { get; set; }
|
||
public double Cents { get; set; }
|
||
}
|
||
|
||
/// <summary>Quotazione di un bene in una stazione: prezzo della prossima unità e unità disponibili (−1 senza controparti).</summary>
|
||
public readonly record struct TradeQuote(double BuyPrice, int BuyUnits, double SellPrice, int SellUnits);
|
||
|
||
/// <summary>
|
||
/// Formule della compravendita in proprio (ADR 0016), senza stato: prezzi locali marginali
|
||
/// (ADR 0004 §3) di produttori e consumatori del bacino, prezzi degli hub, spazio del magazzino.
|
||
/// </summary>
|
||
public static class TradingMath
|
||
{
|
||
/// <summary>
|
||
/// Prezzo locale della prossima unità comprata da un produttore che ne ha <paramref name="stock"/>
|
||
/// in magazzino: Dl = spazio libero del magazzino dell'output, Sl = giacenza. Pieno vale
|
||
/// (1 − λ)·Pg, a metà Pg, quasi vuoto fino a (1 + λ)·Pg, entro ±maxDeviation.
|
||
/// </summary>
|
||
public static double ProducerPrice(World w, Industry ind, int output, int stock)
|
||
{
|
||
int capacity = IndustryMath.OutputCapacity(ind, output, w.Calendar.DaysPerMonth);
|
||
int good = ind.Def.Recipe.Outputs[output].GoodIndex;
|
||
return Market.LocalPrice(w.Market.GlobalPrice[good], Math.Max(0, capacity - stock), stock, w.Data.Balance.LocalPrice);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Prezzo locale della prossima unità venduta a un consumatore che ne ha <paramref name="stock"/>
|
||
/// nell'input: Dl = capienza dell'input (scorta desiderata), Sl = giacenza, come «Dove conviene vendere».
|
||
/// </summary>
|
||
public static double ConsumerPrice(World w, Industry ind, int input, int stock)
|
||
{
|
||
int desired = IndustryMath.InputCapacity(ind, input, w.Calendar.DaysPerMonth);
|
||
int good = ind.Def.Recipe.Inputs[input].GoodIndex;
|
||
return Market.LocalPrice(w.Market.GlobalPrice[good], desired, stock, w.Data.Balance.LocalPrice);
|
||
}
|
||
|
||
/// <summary>Venditori del bene nel bacino: produttori aperti con il bene in magazzino e hub con capacità.</summary>
|
||
public static List<TradeParty> Sellers(World w, Station s, int good)
|
||
{
|
||
var list = new List<TradeParty>();
|
||
foreach (var id in s.Industries)
|
||
{
|
||
var ind = w.Industries[id.Value];
|
||
int o = ind.OutputIndexOf(good);
|
||
if (ind.Closed || o < 0 || ind.OutputStock[o] <= 0) continue;
|
||
list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = o, Limit = ind.OutputStock[o] });
|
||
}
|
||
foreach (var id in s.Hubs)
|
||
{
|
||
var hub = w.Hubs[id.Value];
|
||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/// <summary>Compratori del bene nel bacino: industrie aperte con il bene in ricetta e spazio nell'input, hub con capacità.</summary>
|
||
public static List<TradeParty> Buyers(World w, Station s, int good)
|
||
{
|
||
var list = new List<TradeParty>();
|
||
int dpm = w.Calendar.DaysPerMonth;
|
||
foreach (var id in s.Industries)
|
||
{
|
||
var ind = w.Industries[id.Value];
|
||
int i = ind.InputIndexOf(good);
|
||
if (ind.Closed || ind.Level <= 0 || i < 0) continue;
|
||
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
|
||
if (free > 0) list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = i, Limit = free });
|
||
}
|
||
foreach (var id in s.Hubs)
|
||
{
|
||
var hub = w.Hubs[id.Value];
|
||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/// <summary>Prezzo della prossima unità comprata dal venditore (dopo quelle già prese).</summary>
|
||
public static double NextBuyPrice(World w, TradeParty p, int good)
|
||
{
|
||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].SellPrice(w.Market.GlobalPrice[good]);
|
||
var ind = w.Industries[p.Target];
|
||
return ProducerPrice(w, ind, p.Slot, ind.OutputStock[p.Slot] - p.Units);
|
||
}
|
||
|
||
/// <summary>Prezzo della prossima unità venduta al compratore (dopo quelle già date).</summary>
|
||
public static double NextSellPrice(World w, TradeParty p, int good)
|
||
{
|
||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].BuyPrice(w.Market.GlobalPrice[good]);
|
||
var ind = w.Industries[p.Target];
|
||
return ConsumerPrice(w, ind, p.Slot, ind.InputStock[p.Slot] + p.Units);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Venditore con la prossima unità più conveniente (prezzo crescente, poi industrie prima degli
|
||
/// hub, poi id), null se nessuno ha ancora unità.
|
||
/// </summary>
|
||
public static TradeParty? CheapestSeller(World w, List<TradeParty> sellers, int good, out double price)
|
||
{
|
||
TradeParty? best = null;
|
||
price = double.PositiveInfinity;
|
||
foreach (var p in sellers)
|
||
{
|
||
if (p.Units >= p.Limit) continue;
|
||
double q = NextBuyPrice(w, p, good);
|
||
if (best is null || q < price || (q == price && Before(p, best)))
|
||
{
|
||
best = p;
|
||
price = q;
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Compratore che paga di più la prossima unità (prezzo decrescente, poi industrie prima degli
|
||
/// hub, poi id), null se nessuno ha ancora spazio; le industrie senza cassa per l'unità si saltano.
|
||
/// </summary>
|
||
public static TradeParty? BestBuyer(World w, List<TradeParty> buyers, int good, out double price)
|
||
{
|
||
TradeParty? best = null;
|
||
price = double.NegativeInfinity;
|
||
foreach (var p in buyers)
|
||
{
|
||
if (p.Units >= p.Limit) continue;
|
||
double q = NextSellPrice(w, p, good);
|
||
if (p.Kind == TradePartyKind.Industry && !CanPay(w.Industries[p.Target], p.Cents + q)) continue;
|
||
if (best is null || q > price || (q == price && Before(p, best)))
|
||
{
|
||
best = p;
|
||
price = q;
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
|
||
/// <summary>L'industria ha cassa per pagare <paramref name="cents"/> (arrotondati al centesimo).</summary>
|
||
public static bool CanPay(Industry ind, double cents) => Common.Money.FromCentsRounded(cents).Cents <= ind.Cash.Cents;
|
||
|
||
private static bool Before(TradeParty a, TradeParty b) => a.Kind != b.Kind ? a.Kind < b.Kind : a.Target < b.Target;
|
||
|
||
/// <summary>
|
||
/// Unità di merce della compagnia in viaggio (pacchetti propri in stazione e a bordo) verso
|
||
/// ciascuna stazione: occupano già il magazzino di destinazione.
|
||
/// </summary>
|
||
public static int[] ReservedByStation(World w)
|
||
{
|
||
var reserved = new int[w.Network.Stations.Count];
|
||
foreach (var s in w.Network.Stations) AddReserved(s.Waiting, reserved);
|
||
foreach (var t in w.Trains) AddReserved(t.Cargo, reserved);
|
||
return reserved;
|
||
}
|
||
|
||
private static void AddReserved(List<Packet> packets, int[] reserved)
|
||
{
|
||
foreach (var p in packets)
|
||
{
|
||
if (!p.Owned || p.Kind != PacketKind.Freight) continue;
|
||
int d = p.Destination.Value;
|
||
if (d >= 0 && d < reserved.Length) reserved[d] += p.Units;
|
||
}
|
||
}
|
||
|
||
/// <summary>Spazio libero nel magazzino di una stazione (capacità − giacenza − spedizioni in arrivo).</summary>
|
||
public static int FreeSpace(World w, Station s, int reserved) =>
|
||
Math.Max(0, w.Data.Balance.Trading.WarehouseCapacity - s.StockTotal - reserved);
|
||
|
||
/// <summary>Aggiunge unità al magazzino della compagnia nella stazione (allarga il vettore se serve).</summary>
|
||
public static void AddToWarehouse(Station s, int good, int units, int goodCount)
|
||
{
|
||
if (s.Stock.Length < goodCount) s.Stock = [.. s.Stock, .. new int[goodCount - s.Stock.Length]];
|
||
s.Stock[good] += units;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Quotazione di un bene in una stazione: prezzo della prossima unità al venditore più
|
||
/// conveniente e al compratore migliore, con le unità disponibili (cassa delle industrie esclusa).
|
||
/// </summary>
|
||
public static TradeQuote Quote(World w, Station s, int good)
|
||
{
|
||
var sellers = Sellers(w, s, good);
|
||
var buyers = Buyers(w, s, good);
|
||
double buy = -1, sell = -1;
|
||
if (CheapestSeller(w, sellers, good, out double p) is not null) buy = p;
|
||
foreach (var b in buyers) sell = Math.Max(sell, NextSellPrice(w, b, good));
|
||
return new TradeQuote(buy, sellers.Sum(x => x.Limit), sell, buyers.Sum(x => x.Limit));
|
||
}
|
||
}
|