Rules and strategy API
The loop
Time moves in ticks. Every tick:
- Harvest. Plantings whose maturity tick has arrived become inventory. What you plant is what you get: exactly plots × yield per plot, no randomness.
- Plant. Your
plant(market, farm)runs. Everyone sees the same market snapshot, taken before anyone plants. Requests beyond your free land or cash are clipped. - Auction rounds. Simulated buyers arrive in waves. After each wave an imbalance message
goes out for every crop (indicative price, paired volume, imbalance), then your
sell(market, farm, auction)runs and may add limit sell orders. - Clear. One uniform price per crop: the buyers' limit price that maximises executed volume (ties: smallest imbalance, then closest to last price). Sell orders at or below it fill and everyone gets that one price. If sellers must be rationed: lower limit first, then earlier round, then pro-rata.
- Expiry. Each harvest can be offered in a fixed number of auctions (its shelf life, counting the harvest tick). Whatever is left of a batch after its last auction is thrown away.
Final score: cash + inventory at the last price with a haircut. Crops still growing are worth nothing.
Sell orders work like the NYSE close
- You can only sell, and only with limit orders: a quantity and a minimum price. There are no market orders. To sell at any price, use a tiny limit such as 0.01; you still receive the clearing price, which is always one of the buyers' limits.
- Orders are firm. Once sent you cannot cancel, shrink or re-price them. You can only add more orders in later rounds, up to your inventory.
- An order placed in an earlier round fills ahead of a later one at the same price.
The buyers
Each crop has a hidden fair price that moves by a random percentage every tick (a random walk, with no pull back to the base price), multiplied by a published seasonal factor. Each buyer bids a random quantity at a limit drawn from a normal distribution around that fair price, never above the crop's price cap. Total buy interest scales with the number of farms and has its own slow random drift.
Crops
Return values
def plant(market, farm):
return {"wheat": 5, "corn": 3} # plots to sow this tick (dict or list of (crop, plots))
def sell(market, farm, auction): # runs once per imbalance round
return [("wheat", 20, 11.0)] # ADD: sell 20 wheat at 11.0 or better
return {"wheat": (20, 11.0)} # same thing as a dict
return [] # add nothing this round (None works too)
Quantities are clipped to the inventory you have not yet offered this tick
(farm.inventory[c] - auction.committed(c)).
market (same object in plant and sell)
market.tick, .ticks, .ticks_left | Current tick (0-based), total, auctions remaining including this one. |
market.players | Number of farms in the game (demand scales with it). |
market.crops[name] | .plant_cost .grow_ticks .yield_mean .shelf_life .base_price .price_cap. shelf_life is None for a crop that never expires. |
market.last_price(c) | Last clearing price (base price if the crop has never traded). |
market.prices(c) | List of all clearing prices, oldest first. |
market.volumes(c) | Executed volume per past auction. |
market.history(c) | Every past auction: tick, price (final), volume, buy_interest, sell_interest, unsold, sellers, feed. feed is every imbalance message of that auction: round, phase, price (what the cross would have been at that moment), paired, imbalance, buy_interest, sell_interest. |
market.demand_history(c) | Realised total buy interest per past auction. |
market.demand_forecast(c) | Public, noisy forecast of total buy interest at the next auction. |
market.seasonal(c, tick) | Published seasonal multiplier on the buyers' fair price at any tick (default: now). market.seasonal_curve(c) gives the whole game. |
market.pipeline(c) | {mature_tick: plots} growing market-wide, including yours. Live. |
market.expected_supply(c, tick) | Units that will be harvested market-wide at tick (exact). |
market.inventory_total(c) | Units held in barns across all farms at the end of the previous tick. One tick stale by design. |
farm
farm.cash, .plots, .free_plots | |
farm.inventory[c] | Total units you hold of a crop. |
farm.batches[c] | The same units by harvest: [{qty, harvested_tick, expires_tick}], oldest first. expires_tick is the last auction the batch can be sold in. Sales always take the oldest batch first. |
farm.expiring(c, tick) | Units whose last auction is tick or earlier. |
farm.plantings | List of {crop, plots, planted_tick, mature_tick}. |
auction (sell hook only)
auction.round, .rounds, .is_final | Round index (0-based); after the final round the book clears. |
auction.imbalance(c) | Latest imbalance message: {price, paired, imbalance, buy_interest, sell_interest}. price is None if nothing crosses. imbalance > 0: excess buyers. |
auction.feed(c) | Every imbalance message so far this tick. |
auction.my_orders | Your firm orders this tick: [{crop, qty, price, round}]. |
auction.committed(c) | Units of a crop you have already offered this tick. |
What is hidden
Other players' code and individual orders, the buyers' fair price and its future path, and future demand.
Everything in market is public and identical for all players.
Practical notes
- Each hook has a time limit (2 seconds). Timeouts and exceptions count as "do nothing" for that hook and are logged on your dashboard.
- Your code runs in its own worker process. A timeout kills that process; the next hook starts a fresh one, so module-level state is lost.
- You can keep state in module-level variables; it survives between hooks until you save new code (or time out).
- Allowed imports:
math, cmath, statistics, random, numpy, collections, itertools, functools, json, operator, heapq, bisect, decimal, fractions, string, re, copy, dataclasses, typing, enum, time, datetime, abc, numbers. Anything else (os,pathlib,socket, ...) raisesImportError;open(),exec()andeval()are not available, andprint()output is discarded. - Use "Test on current state" to see what your code would plant and sell right now without committing.
- Use "Backtest" to play a few whole games of your code against all the bots and see your rank, final value and P&L by crop per game. The games use the live settings (ticks, cash, plots) but seeds derived from the live seed, never the live seed itself, so a backtest cannot reveal the live world's future prices or demand. Each backtest is capped at a few seconds; a game cut short is scored as it stood.
- Offline, the same thing from a terminal, with any number of seeds and several strategy files side by side:
python -m farm_auction.simulate --strategy my.py --seeds 1 2 3 4 5(--strategy my.py:alphanames the player; the default is the file name).
Starter strategy
# Your strategy. Two functions are required: plant() and sell().
# They run automatically every tick, even while you are offline.
# Save often; the next tick picks up your latest code. Errors show in your dashboard.
#
# plant(market, farm) -> {"wheat": 5, "corn": 3} plots to plant this tick
# sell(market, farm, auction) -> [("wheat", 20, 11.0)] ADD a limit sell: 20 units, at 11.0 or better
# [] or None add nothing this round
#
# Orders are firm, like the NYSE close: once sent you cannot cancel or change them. sell() runs once
# per imbalance round, so you can add more orders after each imbalance message. Every order needs a
# price; to sell at any price use a tiny limit like 0.01. You still get the single clearing price.
#
# market: .tick .ticks .ticks_left .players .crops[name] (plant_cost, grow_ticks, yield_mean, shelf_life, price_cap)
# .last_price(c) .prices(c) .history(c) (incl. every imbalance message) .demand_history(c)
# .demand_forecast(c) .seasonal(c, tick) .pipeline(c) .expected_supply(c, tick)
# .inventory_total(c) (market-wide barns, as of the end of the previous tick)
# farm: .cash .plots .free_plots .inventory[c] .batches[c] .expiring(c, tick) .plantings
# auction: .round .rounds .is_final .committed(c) .my_orders
# .imbalance(c) -> {price, paired, imbalance, buy_interest, sell_interest}
# imbalance > 0 means more buyers than sellers at the indicative price.
# Full docs: the "Strategy API" tab.
def plant(market, farm):
orders = {}
free = farm.free_plots
if free == 0:
return orders
# Score each crop by expected profit per plot per tick: last price, adjusted for the published
# season at harvest time, penalised when a lot of it is already in the ground market-wide.
scores = {}
for name, c in market.crops.items():
mature = market.tick + c.grow_ticks
if mature >= market.ticks: # would never reach an auction
continue
price = market.last_price(name) * market.seasonal(name, mature) / market.seasonal(name)
pending = market.expected_supply(name, mature)
recent = market.volumes(name)[-3:]
typical = sum(recent) / len(recent) if recent else c.yield_mean * market.players
crowding = (pending + 1) / (typical + 1)
exp_price = price * crowding ** -0.5
margin = (exp_price * c.yield_mean - c.plant_cost) / c.grow_ticks
if margin > 0:
scores[name] = margin
if not scores:
return orders
# Put 60% of free land in the best crop, the rest in the runner-up.
ranked = sorted(scores, key=scores.get, reverse=True)
orders[ranked[0]] = max(1, round(free * 0.6))
if len(ranked) > 1:
orders[ranked[1]] = free - orders[ranked[0]]
return orders
def sell(market, farm, auction):
orders = []
for name, qty in farm.inventory.items():
free = qty - auction.committed(name) # units not yet offered this tick
if free <= 0:
continue
last = market.last_price(name)
# Units that expire after this auction (or everything, on the final tick) must go now.
urgent = free if market.ticks_left <= 1 else min(free, farm.expiring(name, market.tick))
if urgent > 0 and auction.round == 0:
orders.append((name, urgent, 0.01))
free -= urgent
# The rest can wait: read the imbalance messages, commit in the final round with a floor.
if free > 0 and auction.is_final:
indicative = auction.imbalance(name)["price"] or last
if indicative >= 0.85 * last:
orders.append((name, free, 0.85 * last))
return orders