Strategies in Python
Geometer Markets lets you write a trading strategy once in Python (or Go, or any language that reads and writes JSON lines) and run the exact same code in backtest, paper, and run (live) modes on one deterministic Go engine.
Target positions, not raw orders
Section titled “Target positions, not raw orders”In Geometer Markets, your strategy inspects a market View and outputs desired target positions (self.target({...})) or self.hold(). The Go engine reconciles your desired target against current positions and open orders, constructs the resulting orders, and sends them through the risk gate:
- In
backtestmode, orders pass through the exact same risk gate andlimits.jsonas live mode against the local simulator (modeling T+1 equity delivery settlement, intraday square-off cut-offs, circuit price bands, tick sizes, and dated India charges). - In
paperandrun(live) modes, the engine sends every order over loopback HTTP (/v1/orders) to your running Order Guard with a scoped local key. The engine has no back door around the guard.
A minimal Python strategy
Section titled “A minimal Python strategy”Every bundled example is white-box source code on generic index instruments or synthetic data — a code example illustrating the API shape, not trade guidance.
from geometer_markets import Hold, Strategy, Target, View, run
class CrossOver(Strategy): """Moving-average crossover code example on the NSE:NIFTYBEES index ETF."""
universe = ["NSE:NIFTYBEES"] every = "5m" warmup_bars = 50 product = "delivery"
fast_period = 20 slow_period = 50 target_qty = 100
def decide(self, view: View) -> Target | Hold: symbol = self.universe[0] fast = view.sma(symbol, self.fast_period) slow = view.sma(symbol, self.slow_period) if fast is None or slow is None: return self.hold(reason="waiting for moving-average warmup bars")
qty = self.target_qty if fast > slow else 0 return self.target( {symbol: qty}, reason=f"sma{self.fast_period} {fast:.2f} vs sma{self.slow_period} {slow:.2f}", )
if __name__ == "__main__": raise SystemExit(run(CrossOver))Run the same file across all three modes without editing a single line of strategy logic:
# Deterministic offline backtest on your historical or synthetic barsgeometer-markets backtest --strategy "python3 crossover.py" --limits ./limits.json --data ./bars.jsonl
# Paper trading through the local Order Guardgeometer-markets paper --strategy "python3 crossover.py" --guard http://127.0.0.1:7878
# Live trading through the local Order Guard (requires active daily broker login and live key)geometer-markets run --strategy "python3 crossover.py" --guard http://127.0.0.1:7878The View and Strategy API
Section titled “The View and Strategy API”All prices, quantities, account balances, and indicator outputs in geometer_markets.strategy use Python’s exact Decimal type — never IEEE-754 floating-point numbers — so backtests stay reproducible down to the last paisa.
View properties and methods
Section titled “View properties and methods”| Member | Type | Description |
|---|---|---|
view.now |
str |
Deterministic engine timestamp in UTC RFC 3339 (nanosecond precision). |
view.now_utc / view.now_ist |
datetime |
Engine clock as UTC or fixed IST (UTC+05:30, no OS tzdata dependency). |
view.equity, view.cash, view.allocation |
Decimal |
Current strategy equity, available cash, and allocated budget. |
view.open_orders |
int |
Count of currently working orders for this strategy. |
view.position(symbol) / view.positions |
Decimal / dict |
Current signed position for one symbol or all universe symbols. |
view.bars(symbol, n=None) |
tuple[Bar, ...] |
Recent OHLCV bars (open, high, low, close, volume as Decimal). |
view.last(symbol) |
Decimal | None |
Latest mark price for symbol. |
view.sma(symbol, n) / view.ema(symbol, n) |
Decimal | None |
Simple or exponential moving average over n bars (None during warmup). |
view.highest(symbol, n) / view.lowest(symbol, n) |
Decimal | None |
Highest high or lowest low over n bars. |
view.pct_change(symbol, n=1) |
Decimal | None |
Percentage price change over n bars. |
view.atr(symbol, n) |
Decimal | None |
Average True Range over n bars. |
Strategy lifecycle hooks
Section titled “Strategy lifecycle hooks”universe: list of canonical instrument IDs (e.g.["NSE:NIFTYBEES"]). Emitting a target for an instrument outsideuniverseis treated as a protocol fault.every: decision cadence ("1m","5m","15m","1d", or"event"for customis_due(ts, view)logic).product: default order product ("delivery","intraday", or"carry").decide(view): required method that outputsself.target({symbol: qty}, reason=...)orself.hold(reason=...).- Optional hooks:
on_hello(...),on_bar(bar),on_tick(tick),is_due(ts, view).
The gm-strategy/1 local protocol
Section titled “The gm-strategy/1 local protocol”Under the hood, the Go engine spawns your strategy process and exchanges UTF-8 JSON lines over stdin and stdout (max 4 MiB per line; stderr is captured as diagnostic logs). All numeric fields travel on the wire as canonical base-10 decimal strings.
Message lifecycle:
hello->hello_ack: engine sends mode,account_id,strategy_id, andclock_tz(Asia/Kolkata); strategy replies with itsname,universe,cadence, andwarmup_bars.market: engine streamsbarortickevents with monotonic sequence numbers.due->due_ack: used whencadenceis"event".decide->targets(orerror): engine sends the deterministicviewsnapshot; strategy replies with signed target quantities or"hold": true.shutdown: clean termination notice at backtest completion or market close.
Fault handling in live mode: live decide requests enforce a reply deadline (default 2 seconds; no timeout in backtest). A late, malformed, out-of-universe, or error reply holds positions unchanged and increments the strategy’s fault counter. Three consecutive faults automatically trip that strategy’s stop switch to no_new_risk.
Determinism and India reference data
Section titled “Determinism and India reference data”Running the same backtest twice produces the exact same SHA-256 digest across both Go and Python strategies because:
- The simulation kernel uses exact decimals, a double-entry ledger, and explicit event timestamps (never wall-clock time or unseeded randomness).
- NSE and BSE reference tables (2026–2027 trading calendars, holidays, lot sizes, tick rules, expiry series, and dated fee schedules) are versioned data files with cited exchange sources.
- Bring your own historical data: Geometer Markets does not sell or redistribute real exchange market data. Supply historical bars exported from your own broker account or local JSONL files.
Bundled white-box examples
Section titled “Bundled white-box examples”Four open Apache-2.0 examples ship in both Python and Go, operating exclusively on generic index instruments (NSE:NIFTYBEES, NFO:NIFTY...) and mathematically generated synthetic JSONL datasets:
- Moving-average crossover (
01_ma_crossover.py): minimalgm-strategy/1strategy onNSE:NIFTYBEES. - Opening-range breakout (
02_opening_range_breakout.py): deterministic IST clock (09:15–09:30range) and pre-cut-off intraday flattening. - Short strangle with stop (
03_short_strangle_with_stop.py): index options example demonstratingoption_worst_caserefusal on unhedged legs vs. hedged wings with a combined-premium stop. - Guarded AI agent (
04_mcp_agent_guarded.py): AI-agent boundary through the local Order Guard (/v1/*).
Calling the Order Guard directly from Python
Section titled “Calling the Order Guard directly from Python”If you want to build your own loop instead of subclassing Strategy, use geometer_markets.guard.GuardClient:
from geometer_markets.guard import GuardClient, RefusedError
client = GuardClient( base_url="http://127.0.0.1:7878", api_key="gm_paper_a1b2c3d4_your_local_key",)
try: preview = client.preview_order( account_id="default", strategy_id="example-bot", instrument="NSE:NIFTYBEES", side="buy", order_type="limit", product="delivery", quantity="10", price="250.00", ) print(preview)except RefusedError as err: print(err.code, err.limit, err.message, err.decision_id)GuardClient uses only the Python standard library, enforces loopback URLs by default, and translates every guard refusal into a typed RefusedError.