Compare commits

...
4 Commits
Author SHA1 Message Date
dodoxandClaude Sonnet 5 e2a5149788 contd.py: fix condition direction, separate costs/rewards/freight legs
PAYMENT/REPUTATION always go to the player; PROVISION_SHIPMENT (a cost) and
PICKUP/DELIVERY_SHIPMENT (a freight leg the player may or may not fly) depend
on the condition's own Party field vs the contract's Party, not a flat
assumption that every material condition is something the player buys. Net
now correctly adds COMEX_PURCHASE_PICKUP rewards instead of only subtracting
provisioning costs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 13:05:51 +02:00
dodoxandClaude Sonnet 5 bf15c709ea Add planet environment-extra materials to capex calcs; buildcost.py tool
Every building needs a planet-hazard material bundle on top of its normal
BuildingCosts (SEA for low pressure, HSE for high pressure, MGC for low
gravity, BL for high gravity, INS for cold, TSH for heat - area-scaled
where applicable), confirmed against live in-game build panels on Nike.
FIO's own BuildRequirements field is an unreliable superset across hazard
types, not a direct per-building list - don't use it directly.

- puga/planet.py::environment_extras(): the real threshold table.
- tools/buildcost.py: full construction material list for one building,
  optionally on a given planet.
- Wired into whatif.py/buy.py (via simulate(planet=...)) and scan.py's
  own bcost(), so their capex numbers stop silently omitting this.
- docs/mechanics.md: the rule, plus a separate forum-sourced note on the
  CX order-cancellation penalty.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-17 19:03:51 +02:00
dodoxandClaude Sonnet 5 6bd5d6cc69 Add CONTD contract evaluator, deadline-aware buy pricing, actpkg JSON generator
- puga/contd.py, tools/contd.py: price open CONTD contract offers against real
  buy-fresh cost, flagging conditions that can't be priced from the API alone.
- tools/buyat.py: cheapest bid price likely to fill by a hard deadline
  (stockout risk), using the empirical first-passage model from history.py.
- puga/actpkg.py, tools/actpkg.py: Refined PrUn XIT ACT buy-list JSON packages.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-17 19:03:42 +02:00
dodoxandClaude Sonnet 5 dbe5cea9ae sell.py: fix off-by-one in queue-ahead depth
A resting order at the same price was posted first and has time
priority, so it should count as ahead too (p <= r["price"], not p <).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-17 19:03:35 +02:00
15 changed files with 464 additions and 13 deletions
+17
View File
@@ -57,7 +57,24 @@ Run as `puga <tool> ...` (e.g. `puga scan --min-n 3`, `puga plan pull <uuid>`);
- `tools/shiptrip.py SHIP FROM TO [--v0 X --v1 Y]` the simple ship-trip tool: give a ship registration + start + stop, it works out jumps/charges/landing fuel itself via `tools/route.py`'s jump graph and reports fuel cost (defaults to max sliders). Direct-jump routes only - an unconnected pair means gateway-only, and it tells you exactly what to read off the live APEX Ship Flight Control screen (the LOCK fee - genuinely not available via FIO/PRUNplanner, confirmed by inspecting both) and what to run instead (`tools/shipcost.py`). Warns if the given ship's live specs (FIO `/ship/ships/{user}`) don't match the calibrated hull/reactor.
- `tools/shipcost.py [--jumps N --charges N] [--v0 X --v1 Y] [--gateways N --lock-fee AMOUNT:CURRENCY] [--to PLANET]` the explicit/manual version: fuel/AIC cost of a ship trip from physics parameters you already know (jump count, slider values, gateway LOCK fees read off the live game) - use `tools/shiptrip.py` instead if you just want "ship X from A to B". Landing fuel is a measured-planet lookup via `--to`, independent of whether the route used jumps or gateways. Both tools scoped to this account's one hull/reactor (blueprint BP-STRT-0000, shared by both ships AVI-07JFB/AVI-07JFC); open caveats (v0 relative to current fuel load, landing fuel confounded with gravity/distance, no second hull to cross-check) are in `puga/shipping.py`'s module docstring - don't trust magnitudes beyond what's there. Raw calibration data (APEX DOM reads, 2026-10-09): `empire/data/shipping_calibration/`. Also wired into `tools/network.py`'s freight cost (direct-jump transfers use the real model; gateway transfers need an explicit `trip_cost` in the chain YAML, else a 9250 AIC fallback). Library: `puga/shipping.py` (`trip_fuel()`, `round_trip_cost()`).
- `tools/parkcash.py [--min-spread X] [--min-trade-days N] [--rate R] [--top N]` where to park idle cash as a buy-low/sell-high position (not a build) while ships are busy or cash has no better use right now - scans every ticker for a big bid/ask spread AND real trading liquidity (trade-days/gap over a calendar window - a huge spread with few trading days is a stale-quote trap, confirmed by hand: AST showed a 130% spread but its resting ask had gone stale after a 60% real price crash). Round-trip wait/value is EMPIRICAL (`puga.history.empirical_touch`, same model as `tools/sell.py --tiers`), not an assumed random walk - a driftless-walk version was tried and backtested wrong (overstated reachability 2-4x vs 3 years of real data, see `docs/decisions.md`). This dropped the whole universe's top pick from ~94%/day to ~1%/day with real waits of 19-194+ days - treat any number from the old model as stale. `--rate` defaults to 0.0 (matches the idle-cash premise; pass your realized growth rate if this cash IS earmarked) and shows up as a separate `discounted_pct` column (margin% x real odds both legs ever happen) alongside the simple non-compounding `daily_pct` used for ranking. Library: `puga/parkcash.py`.
- `tools/contd.py [--cx AI1]` evaluates this account's OPEN CONTD contract offers (the NPC logistics-officer
pool in APEX's CONTD panel, usually 3 at a time, only one acceptable) - payment, each required
material priced at real buy-fresh cost, and net. Deliberately leaves conditions it can't price
(EXPLORATION, REPAIR_SHIP, HEADQUARTERS_UPGRADE, BASE_CONSTRUCTION, CONTRIBUTION, WAIT,
INCREASE_SATISFACTION - real cost depends on context the API can't see, e.g. a ship already flying
that route) as flagged, unpriced conditions, and doesn't account for materials you may already hold
in storage - it's a breakdown for the caller to judge, not a verdict. Library: `puga/contd.py`.
- `tools/lmscan.py PLANET [--direction source|destination] [--min-margin X]` live Local Market hauling-ad scan (FIO, public/no-auth - real player-posted freight jobs, not the CONTD player-contract system), ranked by margin after real fuel cost (`puga.shipping.leg_cost`). One-way cost only - margin assumes the next job is picked up near the destination, not an empty flight home. A small measured gateway-fee table covers ANT<->HRT/BEN; other gateway routes can't be priced (LOCK fee isn't available via any API). Library: `puga/contracts.py`.
- `tools/buildcost.py BUILDING [--planet ID] [--amount N] [--cx AI1]` full construction material
list for one building, priced at real fill cost; `--planet` adds that planet's environment-extra
materials (SEA/HSE/MGC/BL/INS/TSH - threshold table in `docs/mechanics.md`). Also wired into
`whatif.py`/`buy.py`/`scan.py`'s own capex numbers via `simulate(planet=...)` / `scan.py`'s
`bcost()`. Library: `puga/planet.py::environment_extras()`.
- `tools/actpkg.py NAME TICKER:QTY [TICKER:QTY ...] [--cx AI1] [-o file.json]` emits a Refined PrUn
(browser extension, github.com/refined-prun/refined-prun) `XIT ACT` action-package JSON for a buy
list - paste into the extension's Import Action Package to pre-fill the in-game CXPO buy tile per
material (player still clicks the real buy button - semi-auto, not full auto). NAME must be
letters/digits/spaces only; punctuation is stripped automatically. Library: `puga/actpkg.py`.
- `tools/price.py` prices across exchanges with VWAP, volume, fill price for a quantity; `tools/book.py` order-book ladder.
- `tools/prun_scan.py`, `tools/prun_cxarb.py` legacy top-of-book scans; overstate thin markets. Baseline only. `tools/arb.py` replacement is on the roadmap.
- `puga/econ.py` pure formulas ported from PRUNplanner (efficiency stack, workforce, extraction, production I/O, hab optimizer); `tests/test_econ.py` holds the reference values.
+30
View File
@@ -75,6 +75,36 @@ storage fee - this only confirms placing the order doesn't require a prerequisit
that storage itself is free. Also still unconfirmed: FX conversion fee size (a forum thread titled
"remove FX transaction fee entirely" implies one exists, but no amount confirmed).
## Planet environment-extra materials (per community handbook, confirmed live against Nike)
FIO's `/planet/full/{id}` -> `BuildRequirements` lists a superset across hazard types and is NOT
a direct per-building material list - compute it instead from the planet's own Pressure/Gravity/
Temperature/Surface fields against these threshold rules (source: Prosperous Universe Handbook,
building-costs page):
| condition | extra material | quantity |
|---|---|---|
| rocky | MCG | area x 4 |
| gaseous | AEF | area / 3 |
| pressure < 0.25 atm | SEA | area x 1 |
| pressure > 2.0 atm | HSE | 1/building |
| gravity < 0.25g | MGC | 1/building |
| gravity > 2.5g | BL | 1/building |
| temp < -25C | INS | area x 10 |
| temp > 75C | TSH | 1/building |
Applies per building (construction AND repair), area-scaled rows use the building's own `AreaCost`.
Implemented in `puga/planet.py::environment_extras()`, used by `tools/buildcost.py` and wired into
`whatif.py`/`buy.py`/`scan.py`'s own capex numbers.
## CX order cancellation penalty (UNCONFIRMED numbers, forum-sourced)
Deleting too many unfilled/partially-filled CX orders on the same ticker within a day triggers a
fee (added per dev patch notes to deter bot-style requoting); a warning appears around the 4th
attempt. No confirmed threshold or fee formula - forum reports range from 3 to 5-6 cancels/ticker/
day, fee said to scale with order size. Effect: rate-limits requoting, so effective spreads widen
and top-of-book gets sticky/stale - chasing the top spot is still possible within the free
cancel budget (~3-5/ticker/day per forum reports), just be aware each reprice spends one of those
before the fee kicks in.
## HQ in game vs PRUNplanner's "HQ" flag (observed 2026-09-21)
- The HQ screen (level 1, base permits 1 / 2) shows "Efficiency gains: Electronics 20.0%", and 23.3% for the next level (permits 1 / 3). That is exactly the faction bonus formula (Antares electronics 5% x 2 x (3 - 2 x used/total)), so the HQ display is the faction bonus.
- PRUNplanner's plan flag "HQ" (x1.1 on every building) is NOT visible in live efficiencies (smelters 1.3361, HWP 1.0696 both match the model without it). Keep it off. The HQ upgrade adds a base permit and raises the faction bonus.
+3
View File
@@ -4,6 +4,9 @@ Open work only - what's already built/fixed is discoverable from `CLAUDE.md`'s T
`docs/library.md`, `docs/decisions.md`, and module docstrings, not repeated here.
## Todo
- [ ] `tools/network.py`/`puga/network.py`'s `combine()` doesn't pass `planet` into `simulate()`
yet (environment-extra construction materials, `puga/planet.py::environment_extras()`) -
`whatif.py`/`buy.py`/`scan.py` already do.
- [ ] `tools/arb.py`: inter-CX arbitrage at real fill size (replaces `prun_cxarb.py`, which
overstated profit 7-11x on 2/4 top hits).
- [ ] `tools/haul.py`: fuel cost / profit per trip (route.py has the jump graph).
+44
View File
@@ -0,0 +1,44 @@
"""Refined PrUn (github.com/refined-prun/refined-prun) XIT ACT action-package JSON - the semi-auto
buy-list format: importing one pre-fills the in-game CXPO buy tile for each material, the player
still clicks the real buy button themselves. Schema confirmed from the extension's own source
(src/store/user-data.types.d.ts, src/features/XIT/ACT/actions/cx-buy/cx-buy.ts, 2026-10-17).
Gotcha (verified against the real extension, not just reading the source): `global.name` (and group/
action names) get turned directly into an in-game command string by ActionPackageList.vue - spaces
become underscores but other punctuation survives into the command literally, and APEX's command
parser then rejects it with a generic "Illegal command" error on Edit/Execute (NOT on import, so it
looks like the JSON is fine until you actually open it). sanitize_name() strips anything but
letters/digits/spaces to avoid this.
"""
import re
def sanitize_name(name: str) -> str:
return re.sub(r"[^A-Za-z0-9 ]", "", name).strip()
def build_package(name: str, materials: dict[str, float], exchange: str = "AI1") -> dict:
"""materials: {ticker: qty}. Quantities are rounded up to whole units (CXPO buy amounts aren't
fractional)."""
name = sanitize_name(name)
group = sanitize_name(name.lower()) or "group"
import math
mats = {tk.upper(): math.ceil(qty) for tk, qty in materials.items() if qty > 0}
return {
"global": {"name": name},
"groups": [
{"type": "Manual", "name": group, "materials": mats},
],
"actions": [
{
"type": "CX Buy",
"name": f"Buy {name}",
"group": group,
"exchange": exchange,
"priceLimits": {},
"buyPartial": False,
"allowUnfilled": False,
"useCXInv": True,
}
],
}
+88
View File
@@ -0,0 +1,88 @@
"""Player-to-player CONTD contracts (FIO /contract/allcontracts/{user}) - the NPC logistics-officer
offers shown in APEX's CONTD panel, not the public Local Market hauling ads in puga/contracts.py.
Only OPEN contracts are real choices - exactly one of the pool of (usually 3) offers can be accepted;
CANCELLED/REJECTED/FULFILLED/PARTIALLY_FULFILLED are history or already-committed work.
Each condition's own `Party` field ("CUSTOMER" or "PROVIDER") says who performs it, checked
against the contract's own top-level `Party` field (the player's role in that contract - usually
"CUSTOMER"). Condition vocabulary, direction confirmed against real contract JSON (2026-10-17):
PAYMENT/REPUTATION (always granted TO the player by the PROVIDER, regardless of which `Party` the
condition lists), PROVISION_SHIPMENT (the player's `Party` supplies this material - a real COST,
buy-fresh-priced), COMEX_PURCHASE_PICKUP (the partner already bought this via Comex - a REWARD
handed to the player, sell-valued), PICKUP_SHIPMENT/DELIVERY_SHIPMENT (a logistics leg performed
by whichever `Party` it lists - free to the player when that's the PROVIDER's leg, e.g. their
transporter collecting what you provisioned; a real freight cost via `puga.shipping` when it's the
player's own leg, not priced by this module, flagged with weight/volume/address instead), and
open-ended ones this module deliberately does NOT price because their real cost depends on context
this API can't see (a ship already flying that route, a planet you were about to survey anyway, a
ship already damaged): EXPLORATION (Address = planet to survey), REPAIR_SHIP,
HEADQUARTERS_UPGRADE, BASE_CONSTRUCTION, CONTRIBUTION, WAIT, INCREASE_SATISFACTION. Judging
whether one of those is actually cheap right now is the caller's job.
"""
from . import fio, market
def open_contracts():
me = fio.me()
data = fio.own(f"/contract/allcontracts/{me}", ttl=60)
return [c for c in data if c["Status"] == "OPEN"]
def evaluate(contract: dict, cx: str) -> dict:
"""Payment, materials the contract hands TO the player (COMEX_PURCHASE_PICKUP, sell-valued),
materials the player must supply (PROVISION_SHIPMENT on the player's own Party, buy-fresh
cost), freight legs the player must personally fly (PICKUP/DELIVERY_SHIPMENT on the player's
own Party - weight/volume flagged, not priced), and any other unpriced/contextual conditions -
all for the caller to weigh. net = payment + reward_value - cost_value (freight excluded,
flagged separately)."""
my_party = contract.get("Party") # the player's role in THIS contract, e.g. "CUSTOMER"
payment = 0.0
reputation = False
rewards, costs, freight_legs = [], [], []
flags = []
deadline_days = 0.0
for cond in contract["Conditions"]:
t = cond["Type"]
mine = cond.get("Party") == my_party
if t == "PAYMENT" and cond.get("Amount"):
payment += cond["Amount"]
elif t == "REPUTATION":
reputation = True
elif t == "COMEX_PURCHASE_PICKUP" and cond.get("MaterialTicker"):
rewards.append((cond["MaterialTicker"], cond["MaterialAmount"], cond.get("Address")))
elif t == "PROVISION_SHIPMENT" and cond.get("MaterialTicker") and mine:
costs.append((cond["MaterialTicker"], cond["MaterialAmount"], cond.get("Address")))
elif t in ("PICKUP_SHIPMENT", "DELIVERY_SHIPMENT") and mine:
freight_legs.append((t, cond.get("Address"), cond.get("Weight"), cond.get("Volume")))
elif t not in ("PAYMENT", "REPUTATION", "COMEX_PURCHASE_PICKUP", "PROVISION_SHIPMENT",
"PICKUP_SHIPMENT", "DELIVERY_SHIPMENT"):
flags.append((t, cond.get("Address")))
dl = cond.get("DeadlineDurationMs")
if dl:
deadline_days = max(deadline_days, dl / 86400000)
def price_all(items, side):
total, priced = 0.0, []
for tick, qty, addr in items:
r = market.walk(tick, cx, qty, side)
priced.append({"ticker": tick, "qty": qty, "address": addr, "value": r["total"], "short": r["short"]})
total += r["total"]
return total, priced
reward_value, priced_rewards = price_all(rewards, "sell")
cost_value, priced_costs = price_all(costs, "buy")
return {
"id": contract["ContractLocalId"],
"partner": contract.get("PartnerName"),
"payment": payment,
"reputation": reputation,
"deadline_days": deadline_days,
"rewards": priced_rewards,
"reward_value": reward_value,
"costs": priced_costs,
"cost_value": cost_value,
"freight_legs": freight_legs,
"net": payment + reward_value - cost_value,
"flags": flags,
}
+28 -3
View File
@@ -1,8 +1,33 @@
"""Rank planets by extraction factor for a resource, with founding cost (environment extras
from FIO's own BuildRequirements - authoritative, not guessed from temperature/pressure
thresholds, which PRUNplanner's own calculations don't model either)."""
"""Rank planets by extraction factor for a resource. Also holds environment_extras(): FIO's own
BuildRequirements field is an unreliable superset across hazard types (confirmed wrong in-game,
see docs/mechanics.md) - the real per-building material is computed from the planet's own
pressure/gravity/temperature/surface against the Prosperous Universe Handbook's threshold table,
which PRUNplanner's own calculations don't model either."""
from . import fio
# (condition check, ticker, qty per unit area, flat qty) - handbook building-costs table
ENV_RULES = [
(lambda p: (p.get("pressure") or 0) < 0.25, "SEA", 1.0, 0.0),
(lambda p: (p.get("pressure") or 0) > 2.0, "HSE", 0.0, 1.0),
(lambda p: 0 < (p.get("gravity") or 1) < 0.25, "MGC", 0.0, 1.0),
(lambda p: (p.get("gravity") or 0) > 2.5, "BL", 0.0, 1.0),
(lambda p: (p.get("temperature") if p.get("temperature") is not None else 20) < -25, "INS", 10.0, 0.0),
(lambda p: (p.get("temperature") or 0) > 75, "TSH", 0.0, 1.0),
]
def environment_extras(planet: dict, area: float) -> dict[str, float]:
"""Extra construction/repair materials a building needs beyond its normal BuildingCosts and
the universal MCG area cost (already handled elsewhere, e.g. simulate()'s mcg_per_area) - one
row per hazard the planet actually has (pressure/gravity/temperature; rocky-vs-gaseous MCG/AEF
swap not covered here). planet needs lowercase pressure/gravity/temperature keys, e.g. from
prunplanner._g('/data/planet/{id}/') or fio.planets_full() remapped to lowercase."""
out: dict[str, float] = {}
for cond, tk, per_area, flat in ENV_RULES:
if cond(planet):
out[tk] = out.get(tk, 0.0) + per_area * area + flat
return out
def candidates(resource_ticker: str, min_factor: float = 0.0):
"""All planets with this resource, sorted by factor descending. Each: PlanetNaturalId,
+7 -3
View File
@@ -2,6 +2,7 @@
Input is a PRUNplanner plan JSON (as stored by the API, or built by tools/plan_push.build_payload). Pure given the data passed in.
Validated against a screenshot of the real simulator (tests/test_simulate.py)."""
from . import econ
from . import planet as planet_mod
TIERS = econ.TIERS
FARMS = {"FRM", "ORC"}
@@ -10,8 +11,8 @@ DEGRADATION_DAYS = 180 # usePlanCalculation.ts: degradation/day = const
def simulate(plan: dict, recipes: list[dict], buildings: list[dict], resources: list[dict], fertility: float,
price, faction: str | None = None, permits: tuple[float, float] = (1, 2), mcg_per_area: float = 4.0,
built: dict[str, int] | None = None) -> dict:
"""price(ticker, side) -> AIC per unit or None; side is "buy" (net consumed) or "sell" (net produced), like PRUNplanner BUY/SELL exchange preferences; construction uses "buy". resources: planet resources [{material_ticker, resource_type, daily_extraction}]."""
built: dict[str, int] | None = None, planet: dict | None = None) -> dict:
"""price(ticker, side) -> AIC per unit or None; side is "buy" (net consumed) or "sell" (net produced), like PRUNplanner BUY/SELL exchange preferences; construction uses "buy". resources: planet resources [{material_ticker, resource_type, daily_extraction}]. planet: optional, adds environment-extra construction materials via planet.environment_extras() (SEA/HSE/MGC/BL/INS/TSH - needs lowercase pressure/gravity/temperature keys)."""
d = plan["plan_data"]
bl = {b["building_ticker"]: b for b in buildings}
rec = {r["recipe_id"]: r for r in recipes}
@@ -69,7 +70,10 @@ def simulate(plan: dict, recipes: list[dict], buildings: list[dict], resources:
def unit_cost(tk):
info = bl[tk]
return sum(c["material_amount"] * (price(c["material_ticker"], "buy") or 0) for c in info["costs"]) + mcg_per_area * info["area_cost"] * (price("MCG", "buy") or 0)
cost = sum(c["material_amount"] * (price(c["material_ticker"], "buy") or 0) for c in info["costs"]) + mcg_per_area * info["area_cost"] * (price("MCG", "buy") or 0)
if planet is not None:
cost += sum(qty * (price(etk, "buy") or 0) for etk, qty in planet_mod.environment_extras(planet, info["area_cost"]).items())
return cost
# Verified vs simulator screenshots: degradation = production buildings' construction cost / 180 (infrastructure excluded);
# plan cost and area also include one core module (CM), added automatically.
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Emit a Refined PrUn XIT ACT action-package JSON for a buy list - paste into the extension's
"Import Action Package" (XIT ACT -> IMPORT) to pre-fill the CXPO buy tile for each material; you
still click the real buy button yourself. See puga/actpkg.py for the schema/gotcha notes.
puga actpkg "Nike PP1 BDE buildout" BDE:3 BBH:3 BSE:4 MCG:76 PE:750
puga actpkg "Nike PP1 BDE buildout" BDE:3 BBH:3 BSE:4 MCG:76 PE:750 --cx AI1 -o nike_pp1.json
"""
import argparse, json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import config, actpkg
def main():
ap = argparse.ArgumentParser()
ap.add_argument("name", help="package name (letters/digits/spaces only - punctuation is stripped)")
ap.add_argument("materials", nargs="+", help="TICKER:QTY pairs, e.g. BDE:3 MCG:76")
ap.add_argument("--cx", default=config.DEFAULT_CX)
ap.add_argument("-o", "--out", help="write to this file instead of stdout")
a = ap.parse_args()
mats = {}
for m in a.materials:
tk, _, qty = m.partition(":")
if not qty:
sys.exit(f"bad material spec {m!r}, expected TICKER:QTY")
mats[tk] = float(qty)
pkg = actpkg.build_package(a.name, mats, a.cx)
text = json.dumps(pkg, indent=2)
if a.out:
Path(a.out).write_text(text)
print(f"wrote {a.out}")
else:
print(text)
if __name__ == "__main__":
main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Full construction material list for one building, optionally on a specific planet (adds its
environment-extra materials via puga.planet.environment_extras() - SEA/HSE/MGC/BL/INS/TSH).
puga buildcost HB1
puga buildcost EXT --planet ZV-194a
puga buildcost PP1 --planet ZV-194a --amount 1
"""
import argparse, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import config, fio, market, prunplanner as pp, planet as planet_mod
def main():
ap = argparse.ArgumentParser()
ap.add_argument("building", help="building ticker, e.g. HB1, EXT, PP1")
ap.add_argument("--planet", help="planet natural id - adds its environment-extra materials")
ap.add_argument("--amount", type=int, default=1)
ap.add_argument("--cx", default=config.DEFAULT_CX)
a = ap.parse_args()
blds = {b["Ticker"]: b for b in fio.buildings()}
b = blds.get(a.building.upper())
if not b:
sys.exit(f"unknown building {a.building!r}")
need: dict[str, float] = {c["CommodityTicker"]: c["Amount"] for c in b["BuildingCosts"]}
need["MCG"] = need.get("MCG", 0) + 4 * b["AreaCost"]
if a.planet:
planet = pp._g(f"/data/planet/{a.planet}/", 3600)
for tk, qty in planet_mod.environment_extras(planet, b["AreaCost"]).items():
need[tk] = need.get(tk, 0) + qty
print(f"# {b['Ticker']} on {planet['planet_name']} ({a.planet}): pressure {planet['pressure']:.3f}, "
f"gravity {planet['gravity']:.2f}, temp {planet['temperature']:.1f}C")
total = 0.0
for tk, qty in sorted(need.items()):
qty *= a.amount
cost = market.walk(tk, a.cx, qty, "buy")
px = cost["total"] if not cost["short"] else None
total += px or 0
print(f"{tk:4} {qty:8.1f} {px:>10,.0f} AIC" if px is not None else f"{tk:4} {qty:8.1f} (short on {a.cx})")
print(f"total: {total:,.0f} AIC" if total else "")
if __name__ == "__main__":
main()
+9 -4
View File
@@ -20,14 +20,16 @@ from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import config, fio, market, prunplanner as pp
from puga import planet as planet_mod
from puga.simulate import simulate
sys.path.insert(0, str(Path(__file__).resolve().parent))
import plan_push
def construction_items(plan: dict, buildings: list, built: dict) -> dict:
"""Materials needed for the plan's buildings/infra beyond what `built` (ticker -> count) already has."""
def construction_items(plan: dict, buildings: list, built: dict, planet: dict | None = None) -> dict:
"""Materials needed for the plan's buildings/infra beyond what `built` (ticker -> count) already has.
planet: optional, adds environment-extra materials (SEA/HSE/MGC/BL/INS/TSH) via planet.environment_extras()."""
bl = {b["building_ticker"]: b for b in buildings}
d = plan["plan_data"]
need: dict[str, float] = {}
@@ -39,6 +41,9 @@ def construction_items(plan: dict, buildings: list, built: dict) -> dict:
for c in info["costs"]:
need[c["material_ticker"]] = need.get(c["material_ticker"], 0) + c["material_amount"] * gap
need["MCG"] = need.get("MCG", 0) + 4 * info["area_cost"] * gap
if planet is not None:
for etk, qty in planet_mod.environment_extras(planet, info["area_cost"]).items():
need[etk] = need.get(etk, 0) + qty * gap
return need
@@ -101,9 +106,9 @@ def main():
perm = (st.get("permits", {}).get("used", 1), st.get("permits", {}).get("total", 2))
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
price_ask = lambda t, side="buy": (lambda q: q.ask if q else None)(market.snapshot().get((t, a.cx)))
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price_ask, faction, perm)
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price_ask, faction, perm, planet=planet)
con = net_of_on_hand(construction_items(plan, blds, built), on_hand)
con = net_of_on_hand(construction_items(plan, blds, built, planet), on_hand)
stk = net_of_on_hand(stock_items(r["flows"], a.days), on_hand)
con_rows, con_total, con_w, con_v = price(con, a.cx)
stk_rows, stk_total, stk_w, stk_v = price(stk, a.cx)
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Where to post a BUY order (a resting bid) when there's a hard DEADLINE - not "is patience
worth it forever" (that's tools/sell.py's problem, where foregone margin is the only cost of
waiting). Here, a bid that never fills means a production-line STOCKOUT (check tools/runway.py
for your real deadline), so the right question is: what's the cheapest price that's still likely
to fill BY that deadline, with paying the ask as the fallback if it doesn't?
puga buyat PG 150 --deadline 3 # 3 days of runway left on PG
For each candidate price between the current ask and best bid, uses puga.history.empirical_touch
with a fixed `horizon` (the deadline) to get the REAL empirical P(price actually falls to this
level within that many days) - not "ever", which is the wrong question under a deadline. Expected
cost = price * P(fill by deadline) + current_ask * (1 - P(fill by deadline)) - the fallback term
assumes paying the ask at the deadline if the bid never filled; the ask itself could move by then,
so this is an approximation, not a guarantee. Recommends the price minimizing expected cost, but
shows the whole curve - pick a more conservative (higher-P) price than the cost-minimizer if a
stockout would be expensive in ways this doesn't price in (e.g. the whole base's workforce idling).
"""
import argparse, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import config, fio, market
from puga.history import daily_prices, full_series, empirical_touch
import math
def main():
ap = argparse.ArgumentParser()
ap.add_argument("ticker")
ap.add_argument("qty", type=float)
ap.add_argument("--deadline", type=float, required=True, help="days until this input runs out (tools/runway.py) - the hard constraint, not a soft discount rate")
ap.add_argument("--cx", default=config.DEFAULT_CX)
a = ap.parse_args()
t = a.ticker.upper()
ob = fio.order_book(t, a.cx)
bids = sorted(((o["ItemCost"], o["ItemCount"] or 0) for o in ob["BuyingOrders"] if o.get("ItemCost")), reverse=True)
best_bid = bids[0][0] if bids else None
best_ask = ob.get("Ask")
hit = market.walk(t, a.cx, a.qty, "buy")
ask_cost = hit["total"] if not hit["short"] else None
print(f"{t}.{a.cx} best bid {best_bid} ask {best_ask} vwap7 {ob.get('PriceAverage')} deadline {a.deadline:g}d")
if ask_cost is not None:
print(f"instant (pay the asks now): {ask_cost:,.0f} (avg {hit['avg']:.0f}) - the fallback if nothing fills in time")
else:
print("WARNING: book too thin to fill this quantity at any price right now - the 'pay the ask' fallback isn't actually available at this size")
dp = daily_prices(t, a.cx)
s0 = sorted(dp.items())[-1][1][0] if dp else (best_bid or ob.get("Bid") or 0)
series = full_series(t, a.cx)
if len(series) < 10:
print("\nnot enough price history to estimate fill probability - fall back to paying the ask")
return
candidates = sorted({p for p, _ in bids if p <= s0} | {round(s0 * m, 0) for m in (0.99, 0.97, 0.95, 0.9, 0.85, 0.8, 0.7, 0.6)})
candidates = [p for p in candidates if p > 0 and (best_bid is None or p >= best_bid * 0.5)]
print(f"\nlast traded {s0:.0f}, {len(series)}d history - P(fill) is specifically BY the {a.deadline:g}d deadline, not ever:")
print(f" {'price':>10} {'P(fill by deadline)':>20} {'cost if filled':>15} {'expected cost':>14}")
rows = []
for p in candidates:
y = math.log(p / s0) if s0 else 0.0
if y >= 0:
p_fill = 1.0
else:
p_fill = empirical_touch(series, y, 0.0, horizon=a.deadline)["touched_frac"]
cost_if_filled = p * a.qty
fallback = ask_cost if ask_cost is not None else p * a.qty * 1.5 # crude: no real fallback price known
expected = p_fill * cost_if_filled + (1 - p_fill) * fallback
rows.append((p, p_fill, cost_if_filled, expected))
best = min(rows, key=lambda r: r[3]) if rows else None
for p, p_fill, cost_if_filled, expected in rows:
flag = " <- min expected cost" if (p, p_fill, cost_if_filled, expected) == best else ""
print(f" {p:>10.0f} {100*p_fill:>19.0f}% {cost_if_filled:>15,.0f} {expected:>14,.0f}{flag}")
print("\nNOTE: 'expected cost' assumes paying today's ask as the fallback if the bid never fills by the "
"deadline - the real ask could move by then, this is an estimate. Pick a price with HIGHER P(fill) "
"than the cost-minimizer if a stockout costs more than this model sees (idle workforce, missed orders).")
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""List this account's OPEN CONTD contract offers (the NPC logistics-officer pool shown in APEX's
CONTD panel - usually 3 at a time, only one acceptable) with payment, materials received/supplied,
freight legs the player must personally fly, and net (see puga/contd.py's docstring for exactly
which condition types are costs vs rewards vs the player's own job). Judging the actual best deal
is NOT this tool's job for anything it flags as unpriced (EXPLORATION, REPAIR_SHIP, etc.) or for
a freight leg's real fuel cost (flagged with weight/volume, price via puga.shipping yourself) - it
reports the breakdown, the caller reasons about context.
puga contd
puga contd --cx AI1
"""
import argparse, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import config, contd
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cx", default=config.DEFAULT_CX)
a = ap.parse_args()
contracts = contd.open_contracts()
if not contracts:
print("no OPEN contract offers right now")
return
for c in contracts:
r = contd.evaluate(c, a.cx)
print(f"\n{r['id']} partner={r['partner']} deadline {r['deadline_days']:.1f}d"
+ (" +reputation" if r["reputation"] else ""))
print(f" payment: {r['payment']:,.2f} AIC")
for rew in r["rewards"]:
print(f" receives: {rew['ticker']} x{rew['qty']:g} @ {rew['address']} market value {rew['value']:,.0f}")
for cost in r["costs"]:
flag = " SHORT: book can't fill this qty" if cost["short"] else ""
print(f" must supply: {cost['ticker']} x{cost['qty']:g} @ {cost['address']} buy-fresh cost {cost['value']:,.0f}{flag}")
for ltype, addr, wgt, vol in r["freight_legs"]:
print(f" YOUR FREIGHT LEG: {ltype} @ {addr} {wgt:g}t / {vol:g}m3 - price via puga.shipping, not included in net")
for ftype, addr in r["flags"]:
print(f" UNPRICED CONDITION: {ftype}" + (f" @ {addr}" if addr else "") + " - context-dependent, judge separately")
print(f" reward value: {r['reward_value']:,.0f} cost value: {r['cost_value']:,.0f} -> net (payment + reward - cost): {r['net']:,.0f}")
priceable = [c for c in contracts if not contd.evaluate(c, a.cx)["flags"]]
if len(priceable) == len(contracts):
best = max(contracts, key=lambda c: contd.evaluate(c, a.cx)["net"])
print(f"\nby payment+reward net alone, best priced: {best['ContractLocalId']}"
" - unpriced/flagged conditions (freight legs, exploration, etc.) still need judgment")
if __name__ == "__main__":
main()
+9 -1
View File
@@ -13,6 +13,7 @@ from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from puga import ROOT, config, econ, fio, market, prunplanner as pp, saturation as sat
from puga import planet as pl
TIER_CODE = {"pioneer": "P", "settler": "S", "technician": "T", "engineer": "E", "scientist": "Sc"}
TIER_RANK = {"P": 0, "S": 1, "T": 2, "E": 3, "Sc": 4}
@@ -83,7 +84,14 @@ def main():
parts = [(x["Amount"], ask(x["CommodityTicker"])) for x in b["BuildingCosts"]]
if any(p is None for _, p in parts):
return None
return sum(n * p for n, p in parts) + a.mcg * b["AreaCost"] * mcg
cost = sum(n * p for n, p in parts) + a.mcg * b["AreaCost"] * mcg
if planet is not None:
extras = pl.environment_extras(planet, b["AreaCost"])
prices = {etk: ask(etk) for etk in extras}
if any(p is None for p in prices.values()):
return None
cost += sum(qty * prices[etk] for etk, qty in extras.items())
return cost
hab_head, hab_area = {}, {}
for tier, hab in (("pioneer", "HB1"), ("settler", "HB2"), ("technician", "HB3"), ("engineer", "HB4"), ("scientist", "HB5")):
+3 -1
View File
@@ -132,7 +132,9 @@ def main():
cutoff_price = max(recent_prices + [best_ask or 0]) * 1.1 if recent_prices else float("inf")
med_vol = med or 1
for r in rows:
ahead = sum(u for p, u in asks if p < r["price"])
# p <= (not <): a resting order AT the same price was posted first and has time
# priority over yours - it's ahead of you too, not a free pass to the front of the queue.
ahead = sum(u for p, u in asks if p <= r["price"])
# Outside the recent-traded range the queue mechanism doesn't meaningfully apply (no
# real evidence that cumulative ahead-quantity, much of it itself unreachable junk
# asks, clears at the normal rate) - that means "not a binding constraint" (0), NOT
+1 -1
View File
@@ -127,7 +127,7 @@ def marginal_freight(r_b, r_a, planet_id, cx, sf_price, ff_price, mats):
def run(spec, recipes, blds, price, faction, perm, built):
plan = plan_push.build_payload(spec, recipes, {b["building_ticker"] for b in blds})
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
return plan, simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built=built)
return plan, simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built=built, planet=planet)
def main():