context.
File skeleton
initialize(context)
Required for most strategies. Ziplime calls it once before the first bar.
Use it to:
- Look up assets.
- Store constants and mutable state on
context. - Register scheduled callbacks.
- Configure trading controls.
- Attach pipelines.
- Read algorithm configuration from
context.algorithm.config.
initialize. Order functions are only valid after initialization.
handle_data(context, data)
Required for trading logic. Ziplime calls it on every bar according to the simulation emission_rate.
Use it to:
- Read current or historical values from
data. - Calculate signals.
- Check cash, positions, and open orders.
- Place, target, or cancel orders.
- Record metrics for the result table.
before_trading_start(context, data)
Optional. Ziplime calls it once per session before normal bar processing.
In the current runtime this function is called synchronously, so define it with def, not async def.
Use it to:
- Reset daily state.
- Read pipeline output.
- Prepare a universe for the day.
before_trading_start.
analyze(context, perf)
Optional. Ziplime calls it once after the simulation finishes.
In the current runtime this function is called synchronously, so define it with def, not async def.
perf is the final performance table created by the executor. It includes the recorded variables you created with context.record(...).
Storing state
Use attributes oncontext for anything that must persist across bars:
Algorithm configuration
If your algorithm file defines a subclass ofBaseAlgorithmConfig, Ziplime can load it from the JSON config passed to run_simulation(..., config_file=...).
Common mistakes
| Mistake | Fix |
|---|---|
Defining before_trading_start as async def | Use plain def before_trading_start(...). |
Defining analyze as async def | Use plain def analyze(...). |
Forgetting await on data.current, data.history, or order functions | Add await. |
Placing orders in initialize or before_trading_start | Place orders in handle_data or scheduled callbacks. |
| Calling target order functions repeatedly while old orders are still open | Check context.get_open_orders(asset) or design idempotent rebalance logic. |