/** * Trade helper: estimates what a cargo run between two known markets would earn. * * PRICE MODEL (flagged for team review). Per the docs, a good's price is * "its base price times its baseline over its supply, within a clamp", with a spread * either side, and "every unit you trade moves the supply". So with the listed price * p₀ at supply s₀, the i-th unit (0-based) is estimated at: * buying (supply falls): p₀ · s₀ / (s₀ − i) * selling (supply rises): p₀ · s₀ / (s₀ + i) * We ignore the clamp (we don't know it), assume the spread is proportional, and assume * prices don't drift back during the trip. Snapshots age; routes from old snapshots * are marked `stale`. * * Travel and fuel come from `navigation.ts`/`rules.ts` (estimates too). */ import type { MarketGood } from '../types'; import { planTrip, type GalaxyGraph, type TripPlan } from './navigation'; export interface MarketSnapshot { station: string; system: string; goods: MarketGood[]; /** ISO time the snapshot was read. */ at: string; } /** Price of the i-th unit bought (0-based); Infinity once supply would run out. */ export function unitBuyPrice(g: MarketGood, i: number): number { const left = g.supply - i; return left <= 0 ? Infinity : (g.buy * g.supply) / left; } /** Price of the i-th unit sold (0-based). */ export function unitSellPrice(g: MarketGood, i: number): number { return (g.sell * g.supply) / (g.supply + i); } export function buyCost(g: MarketGood, units: number): number { let total = 0; for (let i = 0; i < units; i++) total += unitBuyPrice(g, i); return total; } export function sellRevenue(g: MarketGood, units: number): number { let total = 0; for (let i = 0; i < units; i++) total += unitSellPrice(g, i); return total; } /** Most units worth carrying from `buy` to `sell`: stop when a unit stops paying, space or credits run out. */ export function bestLot( buy: MarketGood, sell: MarketGood, maxUnits: number, credits: number ): { units: number; cost: number; revenue: number } { let units = 0; let cost = 0; let revenue = 0; while (units < maxUnits) { const b = unitBuyPrice(buy, units); const s = unitSellPrice(sell, units); if (s <= b || cost + b > credits) break; cost += b; revenue += s; units++; } return { units, cost, revenue }; } export interface ShipForTrade { /** Where the ship is, or will be when its current trip ends. */ waypoint: string; speed: number; cargoCapacity: number; fuel: number; fuelCapacity: number; /** Seconds until the ship can act (remaining trip), 0 if idle. */ busySeconds?: number; } export interface TradeRoute { good: string; from: string; to: string; units: number; cost: number; revenue: number; /** Fuel for the loaded leg, at the buy station's fuel price. */ fuelCost: number; profit: number; /** Ship → buy station → sell station. */ seconds: number; profitPerMinute: number; toBuy: TripPlan; loaded: TripPlan; /** Fuel enough to reach the buy station now, and a full tank covers the loaded leg. */ fuelOk: boolean; stale: boolean; } export interface RankOptions { snapshots: readonly MarketSnapshot[]; graph: GalaxyGraph; ship: ShipForTrade; credits: number; now: number; /** Snapshots older than this mark their routes stale. Default 10 minutes. */ staleAfterMs?: number; limit?: number; } const FUEL = 'fuel'; /** Best cargo runs for a ship, by profit per minute. Only profitable, plannable routes. */ export function rankRoutes({ snapshots, graph, ship, credits, now, staleAfterMs = 10 * 60_000, limit = 5 }: RankOptions): TradeRoute[] { const routes: TradeRoute[] = []; const plans = new Map(); const plan = (a: string, b: string) => { const key = `${a}>${b}`; if (!plans.has(key)) plans.set(key, planTrip(graph, a, b, ship.speed)); return plans.get(key)!; }; for (const from of snapshots) { const toBuy = plan(ship.waypoint, from.station); if (!toBuy) continue; const fuelPrice = from.goods.find((g) => g.good === FUEL)?.buy ?? 0; for (const buy of from.goods) { for (const to of snapshots) { if (to.station === from.station) continue; const sell = to.goods.find((g) => g.good === buy.good); if (!sell || sell.sell <= buy.buy) continue; const loaded = plan(from.station, to.station); if (!loaded) continue; const lot = bestLot(buy, sell, ship.cargoCapacity, credits); if (lot.units === 0) continue; const fuelCost = loaded.fuel * fuelPrice; const profit = lot.revenue - lot.cost - fuelCost; if (profit <= 0) continue; const seconds = (ship.busySeconds ?? 0) + toBuy.seconds + loaded.seconds; const age = now - Math.min(Date.parse(from.at), Date.parse(to.at)); routes.push({ good: buy.good, from: from.station, to: to.station, units: lot.units, cost: Math.round(lot.cost), revenue: Math.round(lot.revenue), fuelCost: Math.round(fuelCost), profit: Math.round(profit), seconds, profitPerMinute: profit / Math.max(seconds / 60, 1 / 60), toBuy, loaded, fuelOk: toBuy.fuel <= ship.fuel && loaded.fuel <= ship.fuelCapacity, stale: age > staleAfterMs }); } } } routes.sort((a, b) => Number(b.fuelOk) - Number(a.fuelOk) || b.profitPerMinute - a.profitPerMinute); return routes.slice(0, limit); } /** Where a good sells best among known markets, other than `except`. */ export function bestSellFor( good: string, snapshots: readonly MarketSnapshot[], except?: string ): { station: string; price: number } | null { let best: { station: string; price: number } | null = null; for (const s of snapshots) { if (s.station === except) continue; const g = s.goods.find((x) => x.good === good); if (g && (!best || g.sell > best.price)) best = { station: s.station, price: g.sell }; } return best; } /** Cheapest known place to buy `units` of a good, with the estimated total. */ export function cheapestSource( good: string, units: number, snapshots: readonly MarketSnapshot[] ): { station: string; cost: number } | null { let best: { station: string; cost: number } | null = null; for (const s of snapshots) { const g = s.goods.find((x) => x.good === good); if (!g || g.supply <= units) continue; const cost = Math.round(buyCost(g, units)); if (!best || cost < best.cost) best = { station: s.station, cost }; } return best; }