Strategy reference¶
Three strategies ship with the engine. MANUAL is built in and owns the orders you place from the
dashboard. MarketMaker and OrderStacker are plugins built from
strategies/. Each section lists the
parameters with the defaults the code actually uses. For writing your own, see Writing a strategy.
Config files¶
Each strategy reads <anything>.config.json from strategies.strategy_configs_folder. The file is matched to
the strategy by its name field, which must equal the strategy's name(): MarketMaker, OrderStacker or
MANUAL. Case counts. If two files carry the same name, the one the directory listing returns last wins.
{
"name": "MarketMaker",
"enabled": true,
"parameters": { "instrument": "BTC-USD", "order_size": 0.005 },
"risk_limits": { "max_position_size": 0.05, "max_loss_per_strategy": -200.0 }
}
| Key | Notes |
|---|---|
name |
Required. A file with no name is ignored |
enabled |
Default true. false loads the plugin and then skips it |
parameters |
Handed to the strategy. The tables below list what each one reads. An unknown key is ignored, and a value of the wrong JSON type reads as the default |
risk_limits |
See Risk limits |
strategies/market_maker.json
and strategies/order_stacker.json
are working templates. They do not end in .config.json, so the engine ignores them where they are. Copy each
to <strategy_configs_folder>/<name>.config.json. The config folder defaults to the plugins folder. Full file
format and the engine's other keys are on Configuration.
Risk limits¶
risk_limits is optional. The keys:
| Key | Type | Default | Notes |
|---|---|---|---|
max_position_size |
number | 1000000 |
Absolute position per instrument, base units. An order that grows the position past it is refused. One that shrinks it passes |
max_order_value |
number | 100000 |
Notional per order: absolute price times quantity times the contract multiplier |
max_orders_per_second |
uint | 100 |
Counts orders submitted in a one-second window. Modifies and cancels are not counted |
max_loss_per_strategy |
number | -10000 |
Total PnL below this triggers the loss-limit sequence |
instruments.<name> |
object | none | Per-instrument max_position_size and max_order_value |
A per-instrument entry does not inherit the strategy's limits
An entry under instruments starts from 1000000 and 100000, not from the strategy-level values. If
it names only max_position_size, max_order_value stays at 100000. Give both keys. The same applies
to the REST field, which is called instrument_limits there.
A strategy with a config file that omits risk_limits gets the defaults above. A strategy with no config
file gets 1.0 position, 50000 order value and 10 orders per second, and the log says Using default risk
limits (no config found). A key with the wrong type makes the parser throw, and the whole file is then
skipped with a warning.
Limits can be read and changed live through GET and PUT /api/strategies/:id/risk. A change lasts until
restart. Details and the check order are on Positions, PnL and risk.
Halts, loss limits and auto-pause¶
Three things stop a strategy from trading. All three keep dispatching events to it.
| Trigger | What happens |
|---|---|
Manual halt (POST /api/strategies/:id/halt) |
The risk manager refuses the strategy's new orders with Strategy halted: <reason>. The strategy keeps running. Cancels and modifies still go out |
| Loss limit | Once a second the worker compares each strategy's total PnL with max_loss_per_strategy. On a breach it calls close_all_positions() (cancel everything, then an IOC limit order per open position 10% through the mark, bypassing risk), halts the strategy with Loss limit breached: PnL=... < max_loss=..., and stops it |
| MD auto-pause | Once a second the worker checks every broker the strategy subscribed. If one has market data enabled but not connected, the strategy is stopped (on_stop) and marked paused. When the connection returns it is started again. A manual start or stop clears the pause. The order connector's state is not part of this check |
Resume does not outrun the loss limit
POST /api/strategies/:id/resume clears the halt, and does not start the strategy. The loss check runs
on every strategy, stopped or not, and compares the same PnL against the same limit. Unless the PnL
recovered or you raised max_loss_per_strategy, the next check, up to a second later, closes positions,
halts and stops it again.
Emergency close needs to know the broker
close_all_positions() maps each instrument to a broker from the orders this run has placed. A position
restored from the position store has no mapping until the strategy places an order in it, and the close
logs no broker mapping known and leaves it open.
MANUAL is checked too, with its default limits unless a MANUAL.config.json sets others.
Runtime control¶
| Route | Effect |
|---|---|
GET /api/strategies |
Name, status (running, stopped, paused, halted) and halt reason |
POST /api/strategies/:id/control |
Body {"action": "start"} or {"action": "stop"}. stop runs on_stop, which cancels the working orders in both plugins. It runs on the web server thread |
POST /api/strategies/:id/halt, /resume |
Risk halt. See above |
GET, PUT /api/strategies/:id/config |
Read or replace parameters. A PUT is applied through on_config() on the worker thread and written to the strategy's *.config.json. It replaces the whole object, so omitted keys fall back to the defaults below |
GET, PUT /api/strategies/:id/risk |
Read or merge risk limits. Memory only |
Reference: REST API. Which PUT keys can take effect while running is listed under
each strategy.
MANUAL¶
MANUAL is not a plugin. ManualStrategy
is registered by the manager after the plugins, always, unless strategies.enabled is false. It trades
nothing by itself. Orders you place on the dashboard or through POST /api/orders are booked to it, so its
positions, PnL and risk limits are the manual desk's.
It also decides which instruments the ladders can show.
Listing. Every instrument a broker publishes a definition for is offered to the ladders, unless the filter below rules it out. A listed instrument costs nothing until a ladder opens it.
Ladder-driven subscriptions. Opening a ladder makes MANUAL hold the instrument, which subscribes its
level 2 book and its trades with the broker. Closing the last ladder on it releases both after
web_server_ladder_release_ms (default 5000), so a reloaded page keeps its stream. MANUAL's books stream to
the dashboard only: the manager builds no strategy book for them. A strategy that subscribes the same
instrument keeps it subscribed through a ladder close, and a ladder may hold an instrument the filter
excludes when a strategy already subscribes it.
Filter. The instruments parameter narrows the list:
instruments |
Lists |
|---|---|
| Missing, or not an array | Everything every broker defines |
[] |
Nothing |
["BTC-USD"] |
That exact symbol, as the broker names it, at any broker |
["ETH-*"] |
Every symbol that starts with ETH-. The * is honoured only as the last character |
Matching is case-sensitive, against the broker's own names (Coinbase BTC-USD, Hyperliquid BTC). There is
no per-broker form. Non-string entries are skipped.
A PUT /api/strategies/MANUAL/config replaces the list, like any other parameter update, and re-offers
what brokers already defined. What was listed stays listed: narrowing the filter hides nothing until the
next restart. A PUT without instruments lists everything again. The list holds at most 65536
instruments, and a venue past that gets a single warning.
MarketMaker¶
market_maker.cpp
quotes one bid and one ask, as post-only GTC limit orders of order_size, around a fair value that it
shifts for inventory, trend and book imbalance. It subscribes LEVEL2 and TRADE for instrument on
broker.
How it quotes¶
On each fair value update the strategy recomputes both targets:
half_spread = min_profit_usd / (2 * order_size) + |fair| * taker_fee_rate
inv_ratio = clamp(inventory / max_inventory, -1, 1)
skew = -inv_ratio * inventory_skew_factor * half_spread
trend = clamp((ema_fast - ema_slow) / scale, -1, 1) * trend_sensitivity * half_spread
imbalance = book_imbalance * imbalance_sensitivity * half_spread
adjusted_mid = fair + skew + trend + imbalance
bid = adjusted_mid - half_spread
ask = adjusted_mid + half_spread
- Fair value.
SIMPLE_MIDis(bid + ask) / 2.WEIGHTED_MIDis(bid * ask_qty + ask * bid_qty) / (bid_qty + ask_qty), which leans toward the thinner side.NLEVEL_WMIDdoes the same on the volume-weighted price of the topnlevel_depthlevels per side. Book imbalance is(bid_qty - ask_qty) / total, from the same top of book or levels. Anything else infair_value_modefalls back toWEIGHTED_MID. - Trend. Two EMAs of the fair value, updated once per fair value update (events, not seconds). The signal
is zero until
ema_slow_periodsupdates have been seen.scaleis|fair| / 1000by default, so a 0.1% gap between the EMAs saturates it. In tick mode it ishalf_spread. - Placing. An empty bid slot is filled only if
inventory + order_size < max_inventory, and an empty ask slot only ifinventory - order_size > -max_inventory.max_inventory: 0.010001withorder_size: 0.005is meant to allow exactly two lots, and the extra0.000001keeps a float rounding error from refusing the second. - Repricing. A resting order is modified in place when its target moves more than the threshold:
refresh_threshold_bpsof the posted price, ortick_size * refresh_threshold_tickswhen both are set. A side at or past the inventory limit is cancelled outright. - Fills. A full fill clears the slot and re-quotes at once. A partial fill leaves the slot active.
- Stop.
on_stopcancels every working order. A paused or halted strategy places nothing new.
Each side is a small state machine, which is what keeps it from stacking duplicate orders when a venue rejects an amendment:
stateDiagram-v2
[*] --> EMPTY
EMPTY --> PENDING_NEW: submit_order
PENDING_NEW --> ACTIVE: ack
ACTIVE --> PENDING_MODIFY: target moved
PENDING_MODIFY --> ACTIVE: ack at the requested price
PENDING_MODIFY --> ACTIVE: reject, order still rests
ACTIVE --> PENDING_CANCEL: inventory limit
PENDING_CANCEL --> EMPTY: cancel
PENDING_CANCEL --> ACTIVE: reject
ACTIVE --> EMPTY: full fill
PENDING_NEW --> EMPTY: reject
Only an ack at the price it asked for closes PENDING_MODIFY. Venues keep streaming the pre-edit price while
an edit is in flight, and treating that as the modify ack caused overlapping edits.
Parameters¶
Defaults are the ones in on_config(). Updates through PUT take effect on the next fair value update,
and an update to a running strategy requotes immediately.
| Key | Type | Default | Notes |
|---|---|---|---|
instrument |
string | BTC-USD |
The broker's own name: BTC-USD on Coinbase, BTC on Hyperliquid. Treat as fixed at start: a PUT changes what the quote handlers match but not the subscriptions |
broker |
string | SIMULATED |
COINBASE or HYPERLIQUID in this build, with the same fixed-at-start rule. The default has no connector behind it, so set this. Hyperliquid's order connector cannot connect today, see Brokers |
min_profit_usd |
double | 1.0 |
Target profit per round trip, in quote currency. Sets the half spread together with order_size |
order_size |
double | 0.001 |
Size of each quote |
max_inventory |
double | 0.01 |
Absolute position at which a side stops quoting |
refresh_threshold_bps |
double | 0.5 |
Reprice when the target moves more than this many basis points of the posted price |
tick_size |
double | 0 |
Instrument tick. Used with the next key |
refresh_threshold_ticks |
double | 0 |
Reprice after this many ticks. Takes over from the bps threshold only when this and tick_size are both above 0 |
allow_negative_price |
bool | false |
Treat zero and negative bids and asks as real prices, for calendar spreads. Without a tick threshold the log warns, since a bps threshold near zero collapses and every tick reprices |
inventory_skew_factor |
double | 0.3 |
How hard quotes lean against inventory |
fair_value_mode |
string | WEIGHTED_MID |
SIMPLE_MID, WEIGHTED_MID or NLEVEL_WMID |
nlevel_depth |
int | 5 |
Levels per side for NLEVEL_WMID. Clamped to 1 through 10 |
ema_fast_periods |
int | 10 |
Fast EMA window, in updates |
ema_slow_periods |
int | 50 |
Slow EMA window, and the warm-up before the trend term applies |
trend_sensitivity |
double | 0.5 |
Scales the trend offset |
imbalance_sensitivity |
double | 0.3 |
Scales the imbalance offset |
The header comment in market_maker.cpp gives every one of these defaults the same as the code. Where it
differs from the code:
- It lists
ALPACAas a broker. No Alpaca adapter exists in this repository.HYPERLIQUIDis missing from the list. - It documents
inventory_skew_factor,trend_sensitivityandimbalance_sensitivityas[0,1]. Nothing clamps them. - It says the half spread adds
mid * broker_rate.taker_fee_rateis read once from the position tracker's fee structure, and nothing in the engine sets that, so it is 0 and the term vanishes. - A comment calls the subscriptions dynamic by fair value mode. They are always
LEVEL2andTRADE.
NLEVEL_WMID also reacts to quotes
on_quote has no mode check except SIMPLE_MID. In NLEVEL_WMID every top-of-book quote also sets the
fair value from the weighted top-of-book mid, and updates the EMAs, so the value in use is whichever of
the two events came last.
Example file¶
{
"name": "MarketMaker",
"enabled": true,
"parameters": {
"broker": "COINBASE",
"ema_fast_periods": 3000,
"ema_slow_periods": 18000,
"fair_value_mode": "WEIGHTED_MID",
"imbalance_sensitivity": 0.5,
"instrument": "BTC/USD",
"inventory_skew_factor": 0.3,
"max_inventory": 0.010001,
"min_profit_usd": 0.5,
"nlevel_depth": 20,
"order_size": 0.005,
"refresh_threshold_bps": 1,
"trend_sensitivity": 0.5
},
"risk_limits": {
"max_loss_per_strategy": -200.0,
"max_order_value": 10000.0,
"max_orders_per_second": 10,
"max_position_size": 0.05
}
}
With these numbers the half spread is 0.5 / (2 * 0.005) = 50 quote units each side.
The example's instrument is not a Coinbase product id
Coinbase names products BTC-USD. The example says BTC/USD with broker set to COINBASE, so
market data for it never arrives. Change it to BTC-USD before using the file. nlevel_depth: 20
has no effect: the mode is WEIGHTED_MID, and the value would be clamped to 10 anyway.
OrderStacker¶
order_stacker.cpp
keeps a ladder of resting orders on each side, behind the best bid and offer, using the header-only
slick-stacker library. It is also the reference for driving a
third-party order manager from StrategyBase. It subscribes LEVEL2 and TRADE for instrument on broker,
and the trade feed doubles as a retry heartbeat.
With offset_ticks: 0, levels: 4, level_gap_ticks: 1 and tick_size: 0.01 the ladder looks like this:
ask ladder bid ladder
100.04 100.00 <- best bid, level 0
100.03 99.99
100.02 99.98
100.01 99.97
100.00 <- best ask, level 0 99.96
How it works¶
- On every quote the strategy snaps the touch to the tick grid, rounding away from the market on both
sides, then steps back
offset_tickswhole ticks:bid = floor_tick(best_bid) - offset * tick,ask = ceil_tick(best_ask) + offset * tick. It hands the stacker one price and size per side, and the stacker placeslevelsmore rungs behind it,level_gap_ticksapart, each ofstack_qty. - The stacker never sends anything from its own handlers. The strategy calls
reconcile()at the end of every handler (quote, trade, ack, fill, cancel, reject), behind a guard that stops re-entry, so a refused request is retried on the next event. ack_requiredis always true. A modify or cancel needs the broker order id, which exists only after the ack, so nothing asks for one earlier. A cancel that a rebase orders for an unacked order is held and sent on the ack.- With no usable book (a missing side, a locked or crossed market, a non-positive price) or when the strategy is not running, the ladder is pulled. A pulled ladder cancels its orders.
- Order ids are
<name>_<session stamp>_<counter>, a counter instead of a timestamp, since a whole ladder is placed in one tight loop. A timestamp collision would drop the second order's map entry while the broker still received it. - Orders are
LIMIT,GTC, withpost_onlyfrom the config.
Position guard. The filled position is checked on every quote. The buy side is pulled when the position
reaches max_position, and resumes when it falls to max_position - position_resume_qty. The sell side mirrors
that for a short position. The band stops it flapping. The guard sees only filled quantity, so exposure can
overshoot max_position by up to one ladder, (levels + 1) * stack_qty, before the pull lands. Set
max_position and the risk limit max_position_size with that in mind.
Parameters¶
| Key | Type | Default | Notes |
|---|---|---|---|
instrument |
string | BTC-USD |
Coinbase product id, or a Hyperliquid bare symbol. Fixed at start. A PUT that changes it logs a warning and is ignored |
broker |
string | COINBASE |
COINBASE or HYPERLIQUID. Fixed at start, same rule. Any name that is not a BrokerId leaves the strategy unconfigured |
tick_size |
double | 0.01 |
The stack tick. Must be a multiple of the venue's tick, and equal to it for offset_ticks: 0 to sit on the touch. Changing it at runtime rebuilds the grid and cancels every working order |
offset_ticks |
int | 0 |
Ticks behind the touch for level 0. Negative values are clamped to 0 |
levels |
int | 4 |
Rungs behind level 0, which is not counted: 4 gives five prices per side. Clamped to 0 through 64 |
level_gap_ticks |
int | 1 |
Ticks between rungs. Minimum 1 |
stack_qty |
double | 0.001 |
Size of each rung. Negative is clamped to 0 |
top_qty |
double | 0 |
Size of level 0. 0 means stack_qty |
max_position |
double | 0.01 |
Absolute filled position at which a side is pulled |
position_resume_qty |
double | 0 |
Hysteresis band. 0 means stack_qty |
post_only |
bool | true |
Sent with every order |
prefer_modify |
bool | true |
Reprice a rung in place instead of cancelling and replacing |
refill_on_fill |
bool | false |
Place a replacement rung after a fill |
slack_levels |
int | 0 |
Rungs past the bottom that are kept instead of cancelled |
min_order_qty |
double | 0 |
Dust guard for what is left of a partly filled order |
The header comment matches these defaults. Its broker list also names ALPACA, which has no adapter here.
A bad first config leaves the strategy idle but subscribed
The strategy applies its parameters in on_config(). An unknown broker, or a set the stacker's own
validation refuses, leaves it unconfigured and logs the reason. on_initialize() returns false and logs
refusing to start. The manager ignores that return value, so the strategy is still started and its
subscriptions to the default BTC-USD on Coinbase go out. Every quote handler returns early. A bad
update after a good start keeps the previous working configuration instead.
The ladder's span is offset_ticks + levels * level_gap_ticks ticks. The library's price window holds 2048
levels, and a jump larger than the window forces a full rebase, which cancels everything and
re-places it. The strategy logs a warning when the span is large against the window.
Example file¶
strategies/order_stacker.json:
{
"name": "OrderStacker",
"enabled": true,
"parameters": {
"broker": "COINBASE",
"instrument": "BTC-USD",
"tick_size": 0.01,
"offset_ticks": 0,
"levels": 4,
"level_gap_ticks": 1,
"stack_qty": 0.001,
"top_qty": 0.001,
"max_position": 0.01,
"position_resume_qty": 0.001,
"post_only": true,
"prefer_modify": true,
"refill_on_fill": false,
"slack_levels": 1,
"min_order_qty": 0.0001
},
"risk_limits": {
"max_loss_per_strategy": -200.0,
"max_order_value": 10000.0,
"max_orders_per_second": 200,
"max_position_size": 0.05
}
}
max_orders_per_second is 200 here on purpose. A ladder of five prices per side places ten orders in one
reconcile, which would hit a limit of 10 at once.
Related¶
- Writing a strategy
- Positions, PnL and risk: the checks behind
risk_limitsand halts - REST API: the control, config and risk routes
- Configuration