market

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Market Intelligence Package

pkg/market is a standalone SQLite store for game market data, separate from the main knowledge base. It preserves individual orders (not just aggregates) so the data can support deep analysis, cross-station arbitrage detection, and time-series pattern discovery.

  • Database: /home/robert/spacemolt/spacemolt/data/market.db (overridable via market.Config)
  • Schema: normalized — items, stations, market_orders (raw orders), market_ohlcv (hourly OHLC+VWAP aggregates), arbitrage_opportunities
  • Collection: station agents run update_market (manually or via schedule_add hourly update_market in play_as); each call upserts the station + items and inserts every buy/sell order in one atomic transaction, then computes the hourly OHLCV bucket.

Verifying data collection

After deploying to station agents:

  1. Stats tool:

    go run ./cmd/tools/market-stats
    
  2. Query directly:

    sqlite3 data/market.db "SELECT COUNT(*) FROM market_orders"
    sqlite3 data/market.db "SELECT station_id, COUNT(*) FROM market_orders GROUP BY station_id"
    
  3. Check hourly buckets:

    sqlite3 data/market.db "SELECT bucket_utc, COUNT(*) FROM market_orders GROUP BY bucket_utc ORDER BY bucket_utc DESC LIMIT 10"
    
  4. Item time series (OHLCV):

    sqlite3 data/market.db "SELECT bucket_utc, close_price, vwap, volume FROM market_ohlcv WHERE item_id='iron_ore' AND side='buy' ORDER BY bucket_utc DESC LIMIT 24"
    

Package layout

File Responsibility
types.go Core types: Item, Station, Order, OHLCV, MarketSnapshot, ArbitrageOpportunity
schema.sql / migrations.go Embedded normalized schema + idempotent runMigrations
collector.go Collector (Open/Close), atomic WriteSnapshot, OHLCV aggregation, write-retry for SQLITE_BUSY
capture.go parseViewMarket + CaptureFromClient bridging the game client to the collector
query.go Read helpers: GetStats, GetLatestOrders
integration_test.go Build-tagged manual verification notes

Documentation

Overview

Package market — order-book depth helpers.

Package market provides a separate SQLite database for collecting and analyzing game market data across all stations. Unlike the main knowledge base's market_demand_history (which stores aggregated hourly samples), this system preserves individual orders for deep analysis, cross-station arbitrage detection, and time-series pattern discovery.

Database location: /home/robert/spacemolt/spacemolt/data/market.db

The schema is normalized with dimension tables (items, stations) and fact tables (market_orders, market_ohlcv, arbitrage_opportunities).

Index

Constants

View Source
const NotForSalePrice = 999999.0

NotForSalePrice is the game's "not for sale" sentinel price. The server stamps this on order-book rungs that are placeholders rather than genuine offers (a round 1000000 sibling is also documented in the wild). It is NOT a real ask.

view_market exposes only resting orders — there is no executed-trade feed — so everything in market_orders/market_ohlcv is order-book data. A sentinel rung that never trades must be excluded from every aggregate: folding it into volume/vwap/high drags the number wildly (iron_ore's sell VWAP read 382cr against a ~2cr live ask before this filter). The highest genuine observed price is ~600k, well clear of the cutoff, so the exclusion is safe.

Variables

This section is empty.

Functions

func CaptureFromClient

func CaptureFromClient(ctx context.Context, client game.GameClient, collector *Collector) error

CaptureFromClient captures market data from a game client's last view_market response and persists it via the collector. It is a no-op (returns nil) when the client has no state, is not at a station, or has no cached market payload.

func CaptureFuelFromClient

func CaptureFuelFromClient(ctx context.Context, client game.GameClient, collector *Collector, capturedBy string) error

CaptureFuelFromClient reads the get_base response the client last cached and upserts the docked station's fuel price. No-op (nil) when the collector is nil, the ship is not at a station, or the payload has no fuel price.

func CostToAcquire

func CostToAcquire(asks []AskLevel, qty float64) (totalCost, filled, avgPrice float64, enoughDepth bool)

CostToAcquire walks asks cheapest-first, filling up to qty. asks MUST be sorted ascending by PriceEach. It returns the total cost of the filled units, how many units were fillable, the volume-weighted average price (0 when nothing filled), and whether the ladder had enough depth to fill qty in full.

Types

type AdmitResult

type AdmitResult struct {
	OK          bool   // false = book at capacity, or no candidate still claimable
	ClaimID     int64  // haul_book_claims.claim_id (valid when OK)
	OppID       int    // admitted opportunity row (valid when OK)
	ToStationID string // its destination (valid when OK)
}

AdmitResult reports the outcome of AdmitBookClaim.

type ArbitrageOpportunity

type ArbitrageOpportunity struct {
	ID              int     `json:"id"`
	FromStationID   string  `json:"from_station_id"`
	ToStationID     string  `json:"to_station_id"`
	ItemID          string  `json:"item_id"`
	ActionType      string  `json:"action_type"` // "buy_then_sell" or "sell_then_buy"
	BuyPrice        float64 `json:"buy_price"`
	SellPrice       float64 `json:"sell_price"`
	Quantity        float64 `json:"quantity"`
	SourceUnits     float64 `json:"source_units"` // book's source best-ask depth (src.AskQty); shared across a book's dest rows
	GrossProfit     float64 `json:"gross_profit"`
	FuelCost        float64 `json:"fuel_cost"`
	TravelTicks     int     `json:"travel_ticks"`
	CargoRequired   float64 `json:"cargo_required"`
	RiskScore       float64 `json:"risk_score"`
	ClaimedBy       string  `json:"claimed_by"`
	ClaimedAt       string  `json:"claimed_at"`
	CompletedAt     string  `json:"completed_at"` // set when status transitions to "completed"
	CyclesSeen      int     `json:"cycles_seen"`  // consecutive scan cycles this route has appeared in (1=new)
	Status          string  `json:"status"`       // "available", "claimed", "completed", "expired"
	ExpiresAt       string  `json:"expires_at"`
	DiscoveredAt    string  `json:"discovered_at"`
	DiscoveredBy    string  `json:"discovered_by"`
	Notes           string  `json:"notes"`
	FromStationName string  `json:"from_station_name"` // joined on read
	FromSystemName  string  `json:"from_system_name"`  // joined on read
	ToStationName   string  `json:"to_station_name"`   // joined on read
	ToSystemName    string  `json:"to_system_name"`    // joined on read
	ItemName        string  `json:"item_name"`         // joined on read
}

ArbitrageOpportunity represents a profitable trading opportunity.

type AskLevel

type AskLevel struct {
	PriceEach float64
	Quantity  float64
}

AskLevel is one price level of the sell side of the book.

func ConsumeAsks

func ConsumeAsks(asks []AskLevel, qty float64) []AskLevel

ConsumeAsks returns the residual ask ladder after filling qty units cheapest-first (the inverse bookkeeping of CostToAcquire). Levels fully consumed are dropped; a partially consumed level keeps its remaining Quantity. qty <= 0 returns the ladder unchanged; qty exceeding total depth returns an empty (nil) ladder. Does not mutate the input slice.

type BestPrice

type BestPrice struct {
	ItemID      string    `json:"item_id"`
	StationID   string    `json:"station_id"`
	StationName string    `json:"station_name"`
	SystemID    string    `json:"system_id"`
	SystemName  string    `json:"system_name"`
	Price       float64   `json:"price"`
	Quantity    float64   `json:"quantity"`
	ListingType string    `json:"listing_type"` // "buy" or "sell"
	CapturedAt  time.Time `json:"captured_at"`
}

BestPrice is the best available price for an item at a station, used for cross-station comparison.

type BookCandidate

type BookCandidate struct {
	OppID       int
	ToStationID string
}

BookCandidate is one destination row of a book, offered to AdmitBookClaim in ranked (best-first) order. OppID is the arbitrage_opportunities row id.

type BookKey

type BookKey struct {
	ItemID        string
	FromStationID string
}

BookKey identifies a haul "book": one item at one source station.

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector handles market data collection.

func Open

func Open(cfg Config) (*Collector, error)

Open creates a new collector with the market database.

func (*Collector) AdmitBookClaim

func (c *Collector) AdmitBookClaim(ctx context.Context, book BookKey, candidates []BookCandidate, agentID string, capN int, expiresIn time.Duration) (AdmitResult, error)

AdmitBookClaim atomically admits agentID onto a book if it is under capacity, assigning the best still-available destination not already held by another active claimant (fan-out; degrades to reusing the best destination when all are taken). The whole decision — cap count, taken-destination read, per-row claim, and roster insert — runs in one IMMEDIATE transaction, so a losing racer observes the winner's committed state and never re-collides. Returns OK=false (no error) when the book is at capacity or every candidate row was claimed by someone else first.

func (*Collector) ClaimOpportunity

func (c *Collector) ClaimOpportunity(ctx context.Context, id int, agentID string) (bool, error)

ClaimOpportunity atomically claims an available opportunity for agentID. Returns true if claimed, false if it was already claimed/expired/gone — including a row still flagged 'available' whose expires_at has passed, which is what a released-but-stale row looks like once the scanner's sweep has missed it.

func (*Collector) Close

func (c *Collector) Close() error

Close closes the database connection.

func (*Collector) CompleteBookClaim

func (c *Collector) CompleteBookClaim(ctx context.Context, claimID int64, agentID string) error

CompleteBookClaim marks a claim done after its sell leg completes, freeing its cap slot. Owner-scoped; no-op otherwise.

func (*Collector) CompleteOpportunity

func (c *Collector) CompleteOpportunity(ctx context.Context, id int, agentID string) (bool, error)

CompleteOpportunity atomically marks a claimed opportunity completed, but only if agentID owns the claim. Returns false (no error) if not owned/claimed.

func (*Collector) FindBestPrices

func (c *Collector) FindBestPrices(ctx context.Context, itemID, side string, limit int) ([]BestPrice, error)

FindBestPrices returns the best prices for an item on the given side across all stations, using each station's most recent order for that item. side "sell" ranks ascending (cheapest first); "buy" ranks descending.

func (*Collector) FindItemSellers

func (c *Collector) FindItemSellers(ctx context.Context, itemID string, minQty float64) ([]ItemSeller, error)

FindItemSellers returns every station currently selling the item, one row per station aggregated over its latest capture: cheapest ask, total sell depth, and order count. Stations whose total depth is below minQty are excluded (pass 0 for no floor). Rows are ordered cheapest-first; callers that want distance ranking compose this with pkg/finditem.

func (*Collector) GetActiveBookClaim

func (c *Collector) GetActiveBookClaim(ctx context.Context, itemID, fromStation, agentID string) (int64, bool, error)

GetActiveBookClaim returns the claim_id of agentID's active (claimed/bought) claim on a book, if any. The partial unique index idx_bookclaims_active_agent guarantees at most one such row. Used to recover the claim id when resuming a haul (e.g. across a process restart) so the resumed completion still frees the cap slot.

func (*Collector) GetAskLadder

func (c *Collector) GetAskLadder(ctx context.Context, itemID, stationID string) ([]AskLevel, error)

GetAskLadder returns the sell-side price levels (ascending by price) for an item at a station's latest capture. Empty when the item has no sell orders there. Callers pass the result straight to CostToAcquire.

func (*Collector) GetCaptureHealth

func (c *Collector) GetCaptureHealth(ctx context.Context) ([]StationCaptures, error)

GetCaptureHealth returns per-station capture history: distinct captured_at timestamps (newest first), count, and earliest/latest. Used to spot cadence gaps in collection.

func (*Collector) GetClaimedByAgent

func (c *Collector) GetClaimedByAgent(ctx context.Context, agentID string) ([]ArbitrageOpportunity, error)

GetClaimedByAgent returns opportunities currently claimed by agentID, most-recently claimed first. A hauler calls this on startup to resume a haul it was mid-run on when its process restarted: the in-memory active opportunity does not survive a restart, but the claim row does.

func (*Collector) GetFleetSnapshots

func (c *Collector) GetFleetSnapshots(ctx context.Context, agentID string, limit int) ([]FleetSnapshot, error)

GetFleetSnapshots returns snapshots for agentID (all if empty), newest first, capped at limit (<=0 -> 5000).

func (*Collector) GetFreightResults

func (c *Collector) GetFreightResults(ctx context.Context, agentID string, limit int) ([]FreightResult, error)

GetFreightResults returns the most recent freight results for agentID (all agents if empty), newest finished first, capped at limit (<=0 -> 500).

func (*Collector) GetHaulResults

func (c *Collector) GetHaulResults(ctx context.Context, agentID string, limit int) ([]HaulResult, error)

GetHaulResults returns the most recent haul results for agentID (all agents if empty), newest sold first, capped at limit (<=0 -> 500).

func (*Collector) GetItemPriceHistory

func (c *Collector) GetItemPriceHistory(ctx context.Context, itemID string, limit int) ([]ItemPricePoint, error)

GetItemPriceHistory returns an item's OHLCV buckets across stations, newest first. VWAP is the robust series (close is last-order-in-snapshot and can be noisy for thin items). Empty slice when the item has no history.

func (*Collector) GetItemStationPrices

func (c *Collector) GetItemStationPrices(ctx context.Context, itemID string) ([]ItemStationPrice, error)

GetItemStationPrices returns one item's best ask and best bid per station, each computed from that station's latest capture. BestAsk is the cheapest sell order (where you would buy); BestBid is the highest buy order (where you would sell). AskQty/BidQty total the quantity of orders tying at that best price. Returns an empty slice when the item has no orders.

func (*Collector) GetLatestAnalysis

func (c *Collector) GetLatestAnalysis(ctx context.Context, stationID string) (*MarketAnalysis, error)

GetLatestAnalysis returns the most recent analysis for a station, or (nil, nil).

func (*Collector) GetLatestOrders

func (c *Collector) GetLatestOrders(ctx context.Context, stationID string, limit int) ([]Order, error)

GetLatestOrders returns the most recent orders for a station, newest first.

func (*Collector) GetLatestSnapshot

func (c *Collector) GetLatestSnapshot(ctx context.Context, stationID string) (*MarketSnapshot, error)

GetLatestSnapshot returns the most recent captured market state for a station, reconstructed from the orders sharing the newest captured_at. Returns (nil, nil) when the station has no orders.

func (*Collector) GetMatrix

func (c *Collector) GetMatrix(ctx context.Context, q MatrixQuery) (*Matrix, error)

GetMatrix returns a paginated items×stations matrix. For each matching item and each station, the cell aggregates the station's latest capture of that item: BestSell = cheapest ask, BestBuy = highest bid, VWAP/Volume over sell orders, OrderCount over both sides. Cells are dense-packed: every MatrixItem.Cells has one entry per station in Matrix.Stations order, so item×station pairs with no orders are filled with station-only metadata (HasSell/HasBuy both false), which callers render as "—".

func (*Collector) GetMissionResults

func (c *Collector) GetMissionResults(ctx context.Context, agentID string, limit int) ([]MissionResult, error)

GetMissionResults returns the most recent mission results for agentID (all agents if empty), newest finished first, capped at limit (<=0 -> 500).

func (*Collector) GetOpportunities

func (c *Collector) GetOpportunities(ctx context.Context, status string, limit int) ([]ArbitrageOpportunity, error)

GetOpportunities returns opportunities ordered by gross_profit DESC, optionally filtered to a status ("" = all). Station/system/item names are joined for display. Returns an empty slice when none match.

Rows that are still 'available' but past their expires_at are never served: the scanner's sweep is the only thing that flips available -> expired, so a dead scanner would otherwise freeze the pool and keep handing out gaps that closed hours ago — and because stale rows keep their inflated gross_profit, they would outrank genuinely fresh ones in this very ORDER BY. Other statuses are returned untouched so completed/expired history stays readable for reporting.

func (*Collector) GetReferenceAsk

func (c *Collector) GetReferenceAsk(ctx context.Context, itemID string) (ReferenceAsk, bool, error)

GetReferenceAsk returns an item's live tradeable floor: the cheapest current sentinel-filtered sell across every station's latest capture, plus the total tradeable depth, the number of stations offering, and the quantity available at exactly that best ask. The bool is false when no station currently lists a tradeable ask (so callers fall back rather than reporting a zero price).

This is the honest "what does it cost" signal — the strict minimum ask. Depth and Stations let callers spot a troll floor (one 1cr listing, no other demand) without changing the estimator here.

func (*Collector) GetReferencePrice

func (c *Collector) GetReferencePrice(ctx context.Context, itemID string, lookback time.Duration) (float64, bool, error)

GetReferencePrice returns a robust "cheap" price for an item: the 20th percentile across stations of each station's cheapest sell price seen within lookback (per-station MIN over the window, not just the latest capture). A single gouging station therefore cannot set the reference, and the per-station MIN only ever biases the ceiling stricter (never laxer) — the conservative direction for an anti-gouging gate. Returns (0,false,nil) when no recent sell data exists.

func (*Collector) GetStationFuelPrice

func (c *Collector) GetStationFuelPrice(ctx context.Context, stationID string) (allIn int, capturedAt time.Time, ok bool, err error)

GetStationFuelPrice returns the latest captured all-in fuel price for a station. ok is false (no error) when no price has been captured yet.

func (*Collector) GetStationOrders

func (c *Collector) GetStationOrders(ctx context.Context, stationID, itemID string) ([]Order, error)

GetStationOrders returns the orders from a station's latest capture, optionally filtered to itemID, ordered by side then price. Returns an empty slice when the station has no orders.

func (*Collector) GetStats

func (c *Collector) GetStats(ctx context.Context) (*Stats, error)

GetStats returns database statistics (row counts + most recent capture time).

func (*Collector) HasSnapshotToday

func (c *Collector) HasSnapshotToday(ctx context.Context, stationID string) (bool, error)

HasSnapshotToday reports whether any order for the station was captured today (UTC).

func (*Collector) HaulEfficiencySince

func (c *Collector) HaulEfficiencySince(ctx context.Context, since time.Time) (perAgent []HaulEfficiencyRow, fleet HaulEfficiencyRow, err error)

HaulEfficiencySince returns per-agent aggregates over haul_results rows with sold_at >= since and jumps_traveled > 0, plus the summed fleet row (AgentID ""). A zero `since` (time.Time{}) means all-time. Agents with no qualifying rows are absent from perAgent. Rows with jumps_traveled = 0 are excluded (degenerate and a zero divisor for cr/jump).

func (*Collector) HaulResultTotals

func (c *Collector) HaulResultTotals(ctx context.Context) (map[string]HaulTotals, error)

HaulResultTotals aggregates haul_results per agent — count and summed realized_profit — in a single grouped query. This is the truthful basis for fleet-report's realized-profit + haul-count columns (the actual-fill recorder writes haul_results), replacing the old arbitrage-opportunity gross estimate.

func (*Collector) InvalidateBook

func (c *Collector) InvalidateBook(ctx context.Context, itemID, fromStation, agentID, reason string) error

InvalidateBook clears a collapsed book so no further hauler is drawn in: it expires the book's still-available opportunity rows and the CALLING agent's own claimed row (so its abandon does not republish it), while leaving other agents' claimed rows untouched — they confirm-and-invalidate on their own arrival. Call only when a live recapture confirmed the source is gone.

func (*Collector) LoadCurrentBuyOrders

func (c *Collector) LoadCurrentBuyOrders(ctx context.Context, itemID string) ([]CurrentBuyOrder, error)

LoadCurrentBuyOrders returns the buy orders that are LIVE in each station's most recent capture, across all stations. This is the demand report's data source: unlike the knowledge-DB buy-order ledger (written only on a worker's full docked view_market), market.db is fed continuously by the capture fleet, so "current" here is typically minutes old. Relies on the partial index idx_orders_buy_station_item_cap (side='buy') — without it this query walks the full table.

Liveness gate: a naive MAX(captured_at) per (station, item) resurrects the last time an order was EVER seen, so an order that has since vanished from the book keeps showing up with a multi-hour-stale timestamp (and, being often the highest-value row, dominates the report). We instead keep a (station, item) row only when its latest capture is within one capture cycle (5 min < the ~10-min marketbot cadence, > the few-second intra-capture write stagger) of the STATION's latest capture — i.e. the item was present in the station's most recent snapshot. The station's latest capture is read from the already-joined stations.last_updated_utc (upsertStation stamps it with every snapshot, so it equals MAX(captured_at) for the station) — NOT a MAX(captured_at) GROUP BY station over market_orders, which forces a full scan of the whole buy side (~46M rows, 40+s) because captured_at trails item_id in the only buy index. The PK join to stations is effectively free and keeps `demand --item` at ~2s. Both sides go through datetime() so the "…Z" ISO strings and SQLite's space-form datetime output compare as normalized instants, not raw text (raw text would rank 'T' above ' ' and defeat the gate). Rarely-captured stations (e.g. pirate bases off the marketbot rotation) still surface their latest- known book — that IS their current snapshot — and the report flags it STALE past demandStaleAfter. COALESCE falls back to the row's own capture (gate passes) for any order whose station lacks a stations row.

itemID, when non-empty, scopes the scan to that one item_id (pushed into the per-item latest CTE and the outer filter).

func (*Collector) MedianStationFuelAllIn

func (c *Collector) MedianStationFuelAllIn(ctx context.Context) (median int, ok bool, err error)

MedianStationFuelAllIn returns the median captured all-in fuel price across all stations. ok is false (no error) when no prices have been captured yet.

func (*Collector) PruneOrders

func (c *Collector) PruneOrders(ctx context.Context, olderThan time.Time) (int64, error)

PruneOrders deletes market_orders rows whose capture bucket is older than the given cutoff, returning the number of rows removed.

SQLite has no row TTL, so a retention window is enforced by calling this on a schedule (see cmd/tools/market-prune). Space is reclaimed lazily — freed pages are reused by later inserts, so the file stabilizes at roughly the retention-window peak rather than shrinking. Call Vacuum to shrink the file on disk.

func (*Collector) ReapExpiredBookClaims

func (c *Collector) ReapExpiredBookClaims(ctx context.Context) (int, error)

ReapExpiredBookClaims releases roster rows whose TTL passed while still active (e.g. a hauler killed between claim and settle). The cap count already ignores expired rows; this is cleanup so the roster does not grow unbounded. Returns the number reaped.

func (*Collector) RecomputeContaminatedOHLCV

func (c *Collector) RecomputeContaminatedOHLCV(ctx context.Context, batchSize int) (RecomputeStats, error)

RecomputeContaminatedOHLCV repairs market_ohlcv rows whose aggregates were poisoned by the not-for-sale sentinel (high_price >= NotForSalePrice). For each such bucket it takes the latest surviving raw orders in market_orders and, if any remain, replaces the row with a sentinel-filtered recomputation; if the raw orders have been pruned (retention is short) or were all sentinel, the unrecoverable contaminated row is deleted instead. Clean rows are never touched.

The operation is idempotent: a second run finds no contaminated rows. Work is committed in batches so a large repair does not hold one giant transaction.

func (*Collector) RecordFleetSnapshot

func (c *Collector) RecordFleetSnapshot(ctx context.Context, rows []FleetSnapshot) error

RecordFleetSnapshot writes a batch of per-hauler balance/fuel/cargo snapshots in one transaction (the quarter-hourly fleet_timeseries feed for the credit-balance line).

func (*Collector) RecordFreightResult

func (c *Collector) RecordFreightResult(ctx context.Context, r FreightResult) error

RecordFreightResult writes one settled shipping-contract outcome row, the carrier analogue of RecordMissionResult.

func (*Collector) RecordHaulResult

func (c *Collector) RecordHaulResult(ctx context.Context, r HaulResult) error

RecordHaulResult writes one completed-haul outcome row (real, cargo-capped prices and per-leg timing), the source of the dashboard's true realized-profit and response-time.

func (*Collector) RecordMissionResult

func (c *Collector) RecordMissionResult(ctx context.Context, r MissionResult) error

RecordMissionResult writes one finished-mission outcome row (completed or abandoned), the mission-fleet analogue of RecordHaulResult.

func (*Collector) ReleaseBookClaim

func (c *Collector) ReleaseBookClaim(ctx context.Context, claimID int64, agentID string) error

ReleaseBookClaim returns a claim's cap slot on a pre-buy abandon. Owner-scoped.

func (*Collector) ReleaseOpportunity

func (c *Collector) ReleaseOpportunity(ctx context.Context, id int, agentID string) (bool, error)

ReleaseOpportunity returns a claimed opportunity to the available pool: status back to 'available' and the claim cleared. Only the claiming agent can release its own claim. Returns true if a row was released. Haulers call this when they abandon an opportunity *before buying*, so an abandoned haul does not leak its claim out of the pool (the historical cause of hundreds of stuck 'claimed' rows).

func (*Collector) ScanArbitrage

func (c *Collector) ScanArbitrage(ctx context.Context, opts ScanOptions) (ScanResult, error)

ScanArbitrage detects cross-station buy-low/sell-high spreads from the latest market captures and persists them to arbitrage_opportunities, expiring any previously-available rows first (claimed/completed rows persist). Logistics (fuel/distance/ticks) are deferred to Phase 4b: fuel_cost=0, travel_ticks=0, cargo_required=quantity, notes='logistics:deferred'. Reads happen outside the write transaction so the write lock is held only briefly (important with ~40 capturing agents); a capture landing mid-scan is harmless since opportunities are advisory.

func (*Collector) SettleBookClaim

func (c *Collector) SettleBookClaim(ctx context.Context, claimID int64, agentID string, boughtUnits float64) error

SettleBookClaim records the actual bought quantity on a claim (settle-only: this is the "subtract actual amount used" write). Idempotent no-op if the claim is not in 'claimed' phase or not owned by agentID.

func (*Collector) StoreAnalysis

func (c *Collector) StoreAnalysis(ctx context.Context, a MarketAnalysis) error

StoreAnalysis inserts an LLM market-analysis record.

func (*Collector) UpsertStationFuel

func (c *Collector) UpsertStationFuel(ctx context.Context, s StationFuel) error

UpsertStationFuel writes the latest fuel price for a station, replacing any existing row (one row per station — no time growth).

func (*Collector) Vacuum

func (c *Collector) Vacuum(ctx context.Context) error

Vacuum rebuilds the database file, reclaiming the space freed by deletes. It holds an exclusive lock for the full rewrite, so only run it when no other process is reading or writing the database.

func (*Collector) WriteSnapshot

func (c *Collector) WriteSnapshot(ctx context.Context, snapshot MarketSnapshot) error

WriteSnapshot persists a market snapshot atomically: it upserts the station and items, appends every order to market_orders (raw order rows always accumulate), and upserts the hourly OHLCV bucket for each (station, item, side).

OHLCV is computed only from this snapshot's orders and keyed by the truncated UTC hour. A capture that lands in the SAME hour as a previous one therefore overwrites that hour's OHLCV row instead of extending it — it does not merge volumes or widen the high/low range. Distinct OHLCV data points come from captures in distinct UTC hours, so the collection cadence that builds trend depth is "at most one per hour" (the hourly schedule is the intended driver).

type Config

type Config struct {
	DBPath       string
	WAL          bool
	MaxOpenConns int
	MaxIdleConns int
	BusyTimeout  time.Duration
}

Config holds configuration for the market database.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults.

type CurrentBuyOrder

type CurrentBuyOrder struct {
	StationID  string
	SystemID   string
	ItemID     string
	ItemName   string
	PriceEach  float64
	Quantity   float64
	MyQuantity float64
	Source     string
	CapturedAt time.Time
}

CurrentBuyOrder is one buy order from the most recent capture of its (station, item) pair — the market.db view of live demand. Source is the wire's order source ("station" = Station Manager, "worker" = one of our fleet's own standing orders, "" = another player).

type FleetSnapshot

type FleetSnapshot struct {
	ID            int64   `json:"id"`
	TS            string  `json:"ts"`
	AgentID       string  `json:"agent_id"`
	Role          string  `json:"role"`
	System        string  `json:"system"`
	Docked        bool    `json:"docked"`
	Credits       float64 `json:"credits"`
	Fuel          float64 `json:"fuel"`
	MaxFuel       float64 `json:"max_fuel"`
	CargoUsed     float64 `json:"cargo_used"`
	CargoCapacity float64 `json:"cargo_capacity"`
}

FleetSnapshot is one hauler's balance/fuel/cargo at a point in time (quarter-hourly).

type FreightResult

type FreightResult struct {
	ID            int64   `json:"id"`
	AgentID       string  `json:"agent_id"`
	ContractID    string  `json:"contract_id"`
	PackageID     string  `json:"package_id"`
	FromBaseID    string  `json:"from_base_id"`
	ToBaseID      string  `json:"to_base_id"`
	ServiceLevel  string  `json:"service_level"`
	RouteHops     int     `json:"route_hops"`
	BaseReward    float64 `json:"base_reward"`
	MaxSpeedBonus float64 `json:"max_speed_bonus"`
	FuelCost      float64 `json:"fuel_cost"`
	CarrierPayout float64 `json:"carrier_payout"`
	Outcome       string  `json:"outcome"`
	Reason        string  `json:"reason"`
	AcceptedAt    string  `json:"accepted_at"`
	FinishedAt    string  `json:"finished_at"`
	AcceptedTick  int64   `json:"accepted_tick"`
	FinishedTick  int64   `json:"finished_tick"`
	CreatedAt     string  `json:"created_at"`
}

FreightResult is one settled shipping contract's real outcome, the carrier analogue of MissionResult. Outcome is one of: delivered, returned_infeasible (accept-then-verify rejected it), returned_inflight (deadline buffer collapsed mid-trip), accept_failed, breached, return_failed (the ShippingReturn call itself errored, so the contract was never actually handed back and may still breach — this is the alarm state a would-be-clean return degrades to). A nonzero breached OR return_failed count is the canary's stop signal — the carrier is designed so no path chooses a breach.

type HaulEfficiencyRow

type HaulEfficiencyRow struct {
	AgentID   string
	Hauls     int
	SumProfit float64 // Σ realized_profit
	SumJumps  int64   // Σ jumps_traveled
}

HaulEfficiencyRow is one agent's haul aggregates over a time window.

type HaulResult

type HaulResult struct {
	ID             int64   `json:"id"`
	OppID          int     `json:"opp_id"`
	AgentID        string  `json:"agent_id"`
	ItemID         string  `json:"item_id"`
	Qty            float64 `json:"qty"`
	BuyPricePaid   float64 `json:"buy_price_paid"`
	SellPriceGot   float64 `json:"sell_price_got"`
	RealizedProfit float64 `json:"realized_profit"`
	JumpsTraveled  int     `json:"jumps_traveled"`
	ClaimedAt      string  `json:"claimed_at"`
	ArrivedSrcAt   string  `json:"arrived_src_at"`
	BoughtAt       string  `json:"bought_at"`
	ArrivedDstAt   string  `json:"arrived_dst_at"`
	SoldAt         string  `json:"sold_at"`
	ClaimedTick    int64   `json:"claimed_tick"`
	ArrivedSrcTick int64   `json:"arrived_src_tick"`
	BoughtTick     int64   `json:"bought_tick"`
	ArrivedDstTick int64   `json:"arrived_dst_tick"`
	SoldTick       int64   `json:"sold_tick"`
	CreatedAt      string  `json:"created_at"`
}

HaulResult is the real, cargo-capped outcome of one completed haul, with per-leg timing in wall-time (RFC3339) and game ticks. Drives the dashboard's response-time and credits/jump charts and the true realized-profit column.

type HaulTotals

type HaulTotals struct {
	Hauls          int
	RealizedProfit float64
}

HaulTotals is an agent's recorded-haul roll-up: how many completed hauls and the summed real realized profit across them (losses included).

type Item

type Item struct {
	ItemID         string `json:"item_id"`
	ItemName       string `json:"item_name"`
	Category       string `json:"category"`
	FirstSeenUTC   string `json:"first_seen_utc"`
	LastUpdatedUTC string `json:"last_updated_utc"`
}

Item represents a tradeable item in the market catalog.

type ItemPricePoint

type ItemPricePoint struct {
	StationID   string  `json:"station_id"`
	StationName string  `json:"station_name"`
	Side        string  `json:"side"`
	BucketUTC   string  `json:"bucket_utc"`
	VWAP        float64 `json:"vwap"`
	High        float64 `json:"high"`
	Low         float64 `json:"low"`
	Volume      float64 `json:"volume"`
	TradeCount  int     `json:"trade_count"`
}

ItemPricePoint is one OHLCV bucket for an item at a station.

type ItemSeller

type ItemSeller struct {
	ItemID      string    `json:"item_id"`
	StationID   string    `json:"station_id"`
	StationName string    `json:"station_name"`
	SystemID    string    `json:"system_id"`
	SystemName  string    `json:"system_name"`
	BestPrice   float64   `json:"best_price"`
	TotalQty    float64   `json:"total_quantity"`
	Orders      int       `json:"orders"`
	CapturedAt  time.Time `json:"captured_at"`
}

ItemSeller summarizes one station's sell-side availability of an item, aggregated over that station's latest capture.

type ItemStationPrice

type ItemStationPrice struct {
	StationID   string    `json:"station_id"`
	StationName string    `json:"station_name"`
	SystemID    string    `json:"system_id"`
	SystemName  string    `json:"system_name"`
	BestAsk     float64   `json:"best_ask"`
	AskQty      float64   `json:"ask_qty"`
	BestBid     float64   `json:"best_bid"`
	BidQty      float64   `json:"bid_qty"`
	HasSell     bool      `json:"has_sell"`
	HasBuy      bool      `json:"has_buy"`
	CapturedAt  time.Time `json:"captured_at"`
}

ItemStationPrice is one item's best ask/bid per station, from the latest capture. BestAsk is the cheapest sell order (where you BUY); BestBid is the highest buy order (where you SELL). AskQty/BidQty total the quantity of orders tying at that best price. The arbitrage scanner pairs these across stations.

type MarketAnalysis

type MarketAnalysis struct {
	SystemID        string
	SystemName      string
	StationID       string
	StationName     string
	GameTick        int64
	CapturedAt      time.Time
	AgentID         string
	Mode            string
	SkillLevel      int
	ScanningRange   string
	StationsInRange int
	ItemsScanned    int
	TopInsights     []map[string]any
	TotalItems      int
	TotalPages      int
	Page            int
	Hint            string
	XPGained        map[string]any
	AnalysisData    map[string]any
}

MarketAnalysis is LLM-generated market analysis (analyze_market output).

type MarketSnapshot

type MarketSnapshot struct {
	StationID   string    `json:"station_id"`
	StationName string    `json:"station_name"`
	SystemID    string    `json:"system_id"`
	SystemName  string    `json:"system_name"`
	Orders      []Order   `json:"orders"`
	CapturedAt  time.Time `json:"captured_at"`
}

MarketSnapshot represents a complete market state at one station.

type Matrix

type Matrix struct {
	Stations    []Station    `json:"stations"`
	Items       []MatrixItem `json:"items"`
	TotalItems  int          `json:"total_items"`
	Page        int          `json:"page"`
	Limit       int          `json:"limit"`
	GeneratedAt time.Time    `json:"generated_at"`
}

Matrix is a paginated items×stations snapshot.

type MatrixCell

type MatrixCell struct {
	StationID   string    `json:"station_id"`
	StationName string    `json:"station_name"`
	SystemID    string    `json:"system_id"`
	SystemName  string    `json:"system_name"`
	BestSell    float64   `json:"best_sell"`
	BestBuy     float64   `json:"best_buy"`
	VWAP        float64   `json:"vwap"`   // volume-weighted avg over sell orders
	Volume      float64   `json:"volume"` // sum of sell quantities
	OrderCount  int       `json:"order_count"`
	CapturedAt  time.Time `json:"captured_at"`
	HasSell     bool      `json:"has_sell"`
	HasBuy      bool      `json:"has_buy"`
}

MatrixCell is one item×station cell: aggregates over the station's latest capture.

type MatrixItem

type MatrixItem struct {
	ItemID   string       `json:"item_id"`
	ItemName string       `json:"item_name"`
	Category string       `json:"category"`
	Cells    []MatrixCell `json:"cells"` // aligned to Matrix.Stations order
}

MatrixItem is one matrix row: an item across all stations.

type MatrixQuery

type MatrixQuery struct {
	Category string `json:"category"` // "" = all
	Search   string `json:"search"`   // case-insensitive substring on item_id / item_name
	Page     int    `json:"page"`     // 1-based
	Limit    int    `json:"limit"`    // default 50
}

MatrixQuery parameterizes an items×stations matrix request.

type MissionResult

type MissionResult struct {
	ID             int64   `json:"id"`
	AgentID        string  `json:"agent_id"`
	MissionID      string  `json:"mission_id"`
	TemplateID     string  `json:"template_id"`
	MissionType    string  `json:"mission_type"`
	Title          string  `json:"title"`
	FromBaseID     string  `json:"from_base_id"`
	ToBaseID       string  `json:"to_base_id"`
	ItemID         string  `json:"item_id"`
	Qty            float64 `json:"qty"`
	ExpectedReward float64 `json:"expected_reward"`
	CreditsEarned  float64 `json:"credits_earned"`
	ItemCost       float64 `json:"item_cost"`
	FuelCost       float64 `json:"fuel_cost"`
	Jumps          int     `json:"jumps"`
	Outcome        string  `json:"outcome"` // completed | abandoned
	Reason         string  `json:"reason"`  // cause slug for non-completed outcomes ("" for completed)
	AcceptedAt     string  `json:"accepted_at"`
	FinishedAt     string  `json:"finished_at"`
	AcceptedTick   int64   `json:"accepted_tick"`
	FinishedTick   int64   `json:"finished_tick"`
	CreatedAt      string  `json:"created_at"`
}

MissionResult is one finished (completed or abandoned) mission's real outcome, the mission-fleet analogue of HaulResult. CreditsEarned is the observed wallet delta around complete_mission (0 for abandons); ExpectedReward is what the board advertised, so the dashboard can compare promised vs realized.

type OHLCV

type OHLCV struct {
	StationID  string  `json:"station_id"`
	ItemID     string  `json:"item_id"`
	Side       string  `json:"side"`
	BucketUTC  string  `json:"bucket_utc"`
	OpenPrice  float64 `json:"open_price"`
	HighPrice  float64 `json:"high_price"`
	LowPrice   float64 `json:"low_price"`
	ClosePrice float64 `json:"close_price"`
	Volume     float64 `json:"volume"`
	TradeCount int     `json:"trade_count"`
	VWAP       float64 `json:"vwap"` // Volume-weighted average price
}

OHLCV represents Open, High, Low, Close, Volume for a time bucket.

type Order

type Order struct {
	StationID  string    `json:"station_id"`
	ItemID     string    `json:"item_id"`
	ItemName   string    `json:"item_name"`
	Category   string    `json:"category"`
	Side       string    `json:"side"` // "buy" or "sell"
	PriceEach  float64   `json:"price_each"`
	Quantity   float64   `json:"quantity"`
	MyQuantity float64   `json:"my_quantity"`
	Source     string    `json:"source"`
	CapturedAt time.Time `json:"captured_at"`
	BucketUTC  string    `json:"bucket_utc"` // Truncated to hour
}

Order represents a single buy or sell order from the market.

func OrdersFromListings

func OrdersFromListings(stationID string, gameListings []game.MarketListing, source string, capturedAt time.Time) []Order

OrdersFromListings maps game market listings to market.Order rows. source tags provenance (e.g. "play_as", "agent", "worker").

type RecomputeStats

type RecomputeStats struct {
	Contaminated int // rows found with high_price >= NotForSalePrice
	Recomputed   int // rows rebuilt cleanly from surviving raw orders
	Deleted      int // contaminated rows with no recoverable raw orders, removed
}

RecomputeStats reports the outcome of RecomputeContaminatedOHLCV.

type ReferenceAsk

type ReferenceAsk struct {
	ItemID   string  `json:"item_id"`
	BestAsk  float64 `json:"best_ask"` // cheapest sentinel-filtered current ask
	Depth    float64 `json:"depth"`    // total tradeable sell quantity at latest capture
	Stations int     `json:"stations"` // number of stations currently offering
	AtAsk    float64 `json:"at_ask"`   // quantity available at exactly BestAsk
}

ReferenceAsk is an item's best current tradeable ask across the market: the live floor a buyer would actually pay. It is the honest price signal, distinct from a book-VWAP (which averages the whole resting ladder).

Depth and Stations exist to expose thin-book / troll conditions: a BestAsk set by a lone 1cr listing with Stations==1 and tiny Depth is a red flag that the floor is not real demand, the low-side mirror of the not-for-sale sentinel.

type ScanOptions

type ScanOptions struct {
	MinProfit   float64       `json:"min_profit"`   // gross_profit floor (default 1000)
	MinPrice    float64       `json:"min_price"`    // per-order price floor, filters basement orders (default 10)
	MinQuantity float64       `json:"min_quantity"` // per-order depth floor (default 1)
	ExpiresIn   time.Duration `json:"expires_in"`   // opportunity TTL (default 6h)
	Items       []string      `json:"items"`        // allowlist; empty = all traded items
	Limit       int           `json:"limit"`        // cap rows inserted (default 500)
}

ScanOptions parameterizes an arbitrage scan. Zero-valued fields take the documented defaults when ScanArbitrage runs.

type ScanResult

type ScanResult struct {
	Expired     int       `json:"expired"`
	Inserted    int       `json:"inserted"`
	GeneratedAt time.Time `json:"generated_at"`
}

ScanResult reports what a ScanArbitrage run did.

type Station

type Station struct {
	StationID      string `json:"station_id"`
	StationName    string `json:"station_name"`
	SystemID       string `json:"system_id"`
	SystemName     string `json:"system_name"`
	FirstSeenUTC   string `json:"first_seen_utc"`
	LastUpdatedUTC string `json:"last_updated_utc"`
}

Station represents a station/POI with a market.

type StationCaptures

type StationCaptures struct {
	StationID    string   `json:"station_id"`
	StationName  string   `json:"station_name"`
	SystemID     string   `json:"system_id"`
	SystemName   string   `json:"system_name"`
	CaptureTimes []string `json:"capture_times"` // distinct captured_at, newest first
	Count        int      `json:"count"`
	Latest       string   `json:"latest"`
	Earliest     string   `json:"earliest"`
}

StationCaptures summarizes one station's capture history for health checks.

type StationFuel

type StationFuel struct {
	StationID      string
	FuelPrice      int
	FuelTaxPerUnit int
	FuelPriceAllIn int
	CapturedAt     string
	CapturedBy     string
}

StationFuel is the latest captured fuel price at a station. One row per station (upserted, never grows). FuelPriceAllIn is the per-unit cost a hauler actually pays; Sub-project B consumes it. CapturedAt is RFC3339.

type Stats

type Stats struct {
	StationCount  int    `json:"station_count"`
	ItemCount     int    `json:"item_count"`
	OrderCount    int64  `json:"order_count"`
	OHLCVCount    int64  `json:"ohlcv_count"`
	LatestCapture string `json:"latest_capture"`
}

Stats represents database statistics for quick health checks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL