Skip to content

Writing a strategy

A strategy is a shared library the engine loads once at startup. It subclasses StrategyBase, declares what market data it wants, reacts to callbacks on the strategy-manager worker thread and places orders through helpers that run the risk checks first. The two shipped plugins are described in Strategy reference.

IStrategy and StrategyBase

IStrategy is the interface the host calls: name(), version(), get_subscriptions(), initialize(), start(), stop(), shutdown() and one callback per event. Three callbacks have empty defaults (on_instrument_definition, on_order_book_l3, on_instrument_status). The rest are pure virtual.

Subclass StrategyBase instead. It implements the whole interface and adds:

Provided by StrategyBase Notes
initialize(), start(), stop(), shutdown() Keep a running_ flag and call the protected hooks on_config, on_initialize, on_start, on_stop, on_shutdown
Order tracking A map of this strategy's orders by client order id. get_order(), get_order_by_id(), get_orders(), get_open_orders(), prune_done_orders()
Ownership filtering Acks, fills, rejects and cancels fan out to every strategy. The base drops the ones that are not yours before your hooks run
Position booking Books every owned fill into the PositionTracker under the strategy's name
Order helpers submit_order(), modify_order(), cancel_order(), cancel_all_orders(), close_all_positions()
Parameters get_parameter<T>(key, default) and get_config() over the parameters object
Accessors get_position_tracker(), get_pnl_calculator(), get_risk_manager(), is_running(), get_name()

The hooks you override are on_ack, on_reject, on_cancel, on_fill, on_leg_fill and the lifecycle ones. Market data callbacks (on_trade, on_quote, on_order_book and the optional three) are public virtuals with empty bodies.

Prices and quantities are int64 fixed point at 1e-8. Convert with to_price_t, from_price_t, to_qty_t and from_qty_t. NULL_PRICE means no price, and from_price_t(NULL_PRICE) is NaN.

A minimal plugin:

#include <slick-trader/strategy/strategy_base.hpp>
#include <slick-trader/strategy/strategy_export.hpp>

using namespace slick::trader;

class MyStrategy : public StrategyBase {
public:
    // No logging, no throwing, no side effects. See "The constructor runs three times".
    MyStrategy() : StrategyBase("MyStrategy", "1.0.0") {}

    std::vector<SubscriptionRequest> get_subscriptions() const override {
        return {SubscriptionRequest(broker_id_, SubscriptionType::LEVEL2, {instrument_})};
    }

protected:
    void on_config(const nlohmann::json&) override {
        instrument_ = get_parameter<std::string>("instrument", "BTC-USD");
        broker_id_  = to_broker_id(get_parameter<std::string>("broker", "COINBASE"));
        size_       = get_parameter<double>("size", 0.001);
    }

    void on_quote(const QuoteEvent& q) override {
        // Every strategy is handed every quote, and callbacks arrive while stopped too.
        if (!is_running() || std::string_view(q.instrument) != instrument_) return;
        if (q.bid_price == NULL_PRICE || !get_open_orders().empty()) return;
        submit_order(instrument_, broker_id_, Side::BUY, to_qty_t(size_), OrderType::LIMIT,
                     q.bid_price, TimeInForce::GTC, /*post_only=*/true);
    }

    void on_stop() override { cancel_all_orders(); }

private:
    std::string instrument_{"BTC-USD"};
    BrokerId    broker_id_{BrokerId::COINBASE};
    double      size_{0.001};
};

SLICK_TRADER_EXPORT_STRATEGY(MyStrategy)

Lifecycle

sequenceDiagram
    autonumber
    participant M as Main thread
    participant S as Your strategy
    participant W as StrategyManager worker
    M->>S: dlopen, check API version, inject logger and registry
    M->>S: create_strategy()
    M->>S: initialize(parameters, ...): on_config, then on_initialize
    M->>M: add_strategy, then set risk limits
    M->>S: start(): on_start
    M->>S: get_subscriptions(), read once
    M->>W: spawn worker
    loop every bus event
        W->>S: on_trade, on_quote, on_order_*, ...
    end
    W->>S: on_config (after PUT /api/strategies/:id/config)
    M->>W: join worker (shutdown)
    M->>S: get_subscriptions() again, unsubscribe
    M->>S: stop(): on_stop

The steps, in the order StrategyManager::load_strategies() and start() run them:

  1. Load. Each file with the platform's plugin extension in strategy_plugins_folder is opened, in sorted order. A plugin whose config file says "enabled": false is loaded, then destroyed and skipped.
  2. Initialize. initialize() runs on the main thread. It stores the config and the pointers to the position tracker, PnL calculator, risk manager and order queue, then calls on_config(parameters) and on_initialize(). The strategy's risk limits are set after this returns, so the risk manager still holds defaults while on_initialize runs.
  3. Start. StrategyManager::start() calls start() on each strategy in load order, and right after each one reads its get_subscriptions() and queues the requests. The worker thread starts after the last strategy.
  4. Run. The worker reads the event bus and dispatches. A PUT on the strategy's config arrives as an event and lands in on_config() on the worker.
  5. Stop. The worker is joined first. Then, for each strategy, the manager reads get_subscriptions() again to unsubscribe and calls stop(). Brokers are still running at that point, so the cancels you send from on_stop reach them.

The return value of initialize() is ignored

load_strategies() calls initialize() and never looks at the result. A strategy that returns false from on_initialize() is still added, started and subscribed. OrderStacker's "refusing to start" log line is therefore only a log line: the strategy sits idle but its subscriptions go out. Check your own readiness in the callbacks.

on_shutdown() is never called by the engine

StrategyManager::shutdown() exists but nothing calls it. Release resources in on_stop() or the destructor.

Which thread runs what

Hook Thread
get_subscriptions() Main thread at start and at stop
initialize(), the first on_config(), on_initialize() Main thread, at load
on_trade, on_quote, on_order_book, on_order_book_l3, on_instrument_definition, on_instrument_status Worker
on_order_ack, on_order_fill, on_order_reject, on_order_cancel, and the hooks on_ack, on_fill, on_leg_fill, on_reject, on_cancel Worker
Later on_config() calls Worker
on_start(), on_stop() Whoever calls start() or stop(): the main thread at engine start and stop, the web server thread for POST /api/strategies/:id/control, the worker for a loss-limit stop and for an MD auto-pause or resume
The synthetic reject from submit_order() The thread that called submit_order(), synchronously

State that only callbacks touch needs no locks. on_start and on_stop are the exception: they can run on a thread that is not the worker while the worker is dispatching. The shipped plugins call cancel_all_orders() from on_stop, which walks the order map the worker owns. Called from the REST thread that is a data race. If you stop through the API, keep on_stop to atomics and queue publishes.

Callbacks run with no try or catch around them. An exception that leaves one reaches the worker's run() loop and ends the process through std::terminate. There is no crash isolation either: the plugin shares the engine's address space.

Callbacks arrive while stopped

stop() clears is_running(). It does not stop dispatch. A stopped, paused or halted strategy still receives every quote, trade and order event. Check is_running() before you act on market data, as MarketMaker and OrderStacker do. Fills still book into positions while stopped, and a PUT config still reaches on_config().

Callbacks

Callback Fires when Notes
on_trade(TradeEvent) A subscribed TRADE print Also updates the instrument's mark price before you see it
on_quote(QuoteEvent) A QUOTE update, or the top of a subscribed level 2 or MBO book changes The manager builds quotes from the book, so a LEVEL2 subscription alone yields them. A book side with no quantity has NULL_PRICE
on_order_book(instrument, OrderBookL2&) A subscribed level 2 book changed Every strategy gets every subscribed book: check the name. The reference is valid only inside the call
on_order_book_l3(instrument, OrderBookL3&) An MBO book is whole after an exchange event Neither built-in broker carries MBO. See Queue position
on_instrument_definition(event) A broker publishes tick size, multiplier and quantity limits Position and risk accounting apply the multiplier whether or not you do
on_instrument_status(event) An instrument opened, halted or closed Nothing is pulled on your behalf. Neither built-in broker publishes it
on_ack, on_reject, on_cancel An owned order event The base has already updated the order map
on_fill An owned fill, after the position was booked event.scope is ORDER for a multi-leg order's own fill
on_leg_fill One leg of a multi-leg fill Position already booked. The event's instrument, side, price and quantity are the leg's

The base filters ack, fill, reject and cancel by ownership before your hook runs, so a hook only ever sees its own orders. The raw on_order_ack and friends are public overrides: do not override them without calling the base, or you lose the filtering and the position booking.

Subscriptions

get_subscriptions() returns one SubscriptionRequest(broker, type, instruments, depth) per broker and kind of data. The manager reads it once, in start(), and reads it again at stop to unsubscribe. Changing what it returns in between changes nothing for the broker, and the unsubscribe at stop then names the new list while the old one stays subscribed.

SubscriptionType Delivers
TRADE on_trade
QUOTE on_quote from the broker's own top-of-book feed (Coinbase ticker, Hyperliquid bbo)
LEVEL2, ORDER_BOOK on_order_book, and on_quote from the top of the book
MBO on_order_book_l3, and on_quote unless a level 2 book already gives them

Subscribing both QUOTE and LEVEL2 for one instrument gives you two quote streams. The manager keeps a holder count per broker, type and instrument, so two strategies asking for the same thing cost the broker one request. A broker the engine did not build logs no <broker> broker was built and the request is dropped.

Instrument and broker are fixed at start

MarketMaker lets a PUT change instrument and broker and rebuilds nothing, so it keeps trading the new name on a feed it never subscribed. OrderStacker logs a warning and keeps the old pair. Treat both as start-time parameters.

Placing orders

std::string refusal;
auto id = submit_order(instrument, BrokerId::COINBASE, Side::BUY, to_qty_t(0.01),
                       OrderType::LIMIT, to_price_t(60000.0), TimeInForce::GTC,
                       /*post_only=*/true, &refusal);
if (id.empty()) { /* refused before it left the engine, reason in `refusal` */ }
Helper What it does
submit_order(instrument, broker, side, qty, type, price, tif, post_only, &refusal) Returns the client order id, or an empty string when refused. The defaults are NULL_PRICE, FOK and post_only = true, so pass the time in force and flag you mean
modify_order(client_id, new_price, new_qty, new_stop = NULL_PRICE) Sets the order to PENDING_MODIFY and publishes the modify. It needs the broker's order id, so wait for the ack first
cancel_order(order_id, client_id) Publishes a cancel addressed to the order's broker
cancel_all_orders() Cancels each order that is open or pending a modify and already has a broker id. An order still waiting for its first ack is skipped
close_all_positions() Cancels everything, then sends one aggressive IOC limit per open position, 10% through the mark price. Skips the risk manager

Refusals. submit_order() refuses in two places, in this order. The risk manager (Strategy halted, a position, order-value or rate limit) and the broker status registry (Broker order connector disabled or disconnected). On a refusal it builds an OrderRejectEvent and calls on_order_reject() on you synchronously, from inside submit_order(), then returns an empty string. That reject has no broker order id and the order is not added to the order map. If your reject handler looks the order up by client id it finds nothing: OrderStacker inserts its own record only after submit_order() returns for exactly this reason.

What skips risk. Only submit_order() calls the risk manager. modify_order(), cancel_order() and close_all_positions() do not, so a modify can raise the quantity past a limit. The position check also looks at the filled position, not at working orders.

Post-only. submit_order() clears post_only for CME and ICE orders, which have no such instruction.

Rejected amendments. A reject for a modify or cancel marks the base's copy of the order REJECTED, even though the venue left it resting. REJECTED counts as done, so get_open_orders() and cancel_all_orders() no longer see it and prune_done_orders() removes it. Track your own order state if you amend, as MarketMaker's quote slots do.

Close-out limits. close_all_positions() finds each instrument's broker from the orders this run placed. A position restored from the position store with no order since the restart has no broker on record, logs no broker mapping known and is not closed.

Ownership and client order ids

Every broker event goes to every strategy, so StrategyBase decides which are yours from the client order id. generate_order_id() returns <name>_<timestamp ns>, and owns_client_order_id() accepts an id that starts with <name>_. An order id you already track counts as yours. For a follow-up event that has no client id (Coinbase sends some), the broker order id recorded at ack time decides.

  • If you override generate_order_id(), override owns_client_order_id() to match, or your own fills are ignored and your position never moves. OrderStacker does this to add a counter, because two orders placed in the same clock tick would otherwise share an id.
  • Keep names from being <name>_ prefixes of one another. MM and MM_Fast collide.
  • The order map only holds orders from this run. After a reconnect or restart a broker that restates its working orders gets them adopted when the prefix matches. Nothing cancels them for you.

Queue position and MBO

With an MBO subscription, get_queue_position(book, client_order_id) returns how many orders and how much quantity sit ahead of one of your resting orders. It answers nothing until the order is acked and shows on the feed. Coinbase and Hyperliquid have no MBO feed: both log MBO subscription ignored, so the call never returns a position with the built-in brokers.

Configuration

A strategy's parameters come from the parameters object of its <name>.config.json. The file is matched to the plugin by its name field, not its file name. Format and risk keys are on Configuration.

{
  "name": "MyStrategy",
  "enabled": true,
  "parameters": { "instrument": "BTC-USD", "broker": "COINBASE", "size": 0.001 },
  "risk_limits": { "max_position_size": 0.05, "max_order_value": 10000, "max_orders_per_second": 10 }
}

get_parameter<T>(key, default) returns the default when the key is missing and also when the value has the wrong JSON type, with no warning. A string where a number belongs reads as the default.

Parameters can change two ways:

Way Applies Persists
Edit the file At the next start. Nothing watches the file Yes, it is the file
PUT /api/strategies/:id/config Immediately, through on_config() on the worker Yes, when a *.config.json with a matching name exists. The parameters block is replaced and the file is rewritten. With no file the change lasts until restart

See REST API. A PUT replaces the whole object. config_params_ becomes the new body, so a key you leave out reverts to its default on the next get_parameter call. Send every key. Risk limits changed through PUT /api/strategies/:id/risk are memory only. They are not written back.

A config update reaches on_config() whether or not the strategy runs. If your on_config acts on the change, give a stopped strategy the same treatment your market data handler does, as OrderStacker does when it pulls its ladder before reconciling.

Halts and loss limits live in the risk manager, not in the strategy. A manual halt leaves the strategy running and getting callbacks, and only its new orders fail. A loss-limit breach also closes its positions and stops it. See Positions, PnL and risk.

Exporting the plugin

End the translation unit with SLICK_TRADER_EXPORT_STRATEGY(MyStrategy) (strategy_export.hpp). It defines these extern "C" symbols:

Symbol Purpose
get_strategy_api_version() The STRATEGY_API_VERSION the plugin was built against
create_strategy() new MyStrategy()
destroy_strategy(IStrategy*) delete, so the object is freed by the module that allocated it
get_strategy_name(), get_strategy_version() Read from a function-local static instance, for the load log line
set_logger_instance(Logger*) Points the plugin's logger at the host's
set_broker_status_registry(BrokerStatusRegistry*) Points the plugin's registry at the host's

StrategyLoader::load() requires create_strategy and destroy_strategy and fails with Library missing required functions without them. It then checks the version.

The API version check

STRATEGY_API_VERSION is 2. It covers the layouts the plugin and host share: IStrategy, StrategyBase and BrokerStatus. Anyone changing one of them raises the number. A plugin that reports another version is refused with built against strategy API version N; this host takes version 2. Rebuild it against this slick-trader. A plugin with no get_strategy_api_version reads as version 0 and gets the older "built before plugins named their API version" message. Rebuild plugins with the engine.

The interface also passes std::vector, std::string and nlohmann::json objects across the boundary. Build the plugin with the engine's compiler, standard library and, on Windows, the same CRT setting.

Why the logger and registry are injected

A plugin links slick-trader-core statically, so it owns private copies of the host's singletons. Left alone, its Logger is uninitialised and its BrokerStatusRegistry is all false that nothing writes. The loader calls set_logger_instance and set_broker_status_registry with the host's instances before create_strategy(). The registry matters most: submit_order() asks it whether the broker's order connector is up, so without the injection every order is refused as Broker order connector disconnected while orders from inside the host still work. A plugin that lacks the registry export loads, with a warning that it will place no orders. If you hand-write the exports, write both.

Any other process-wide state in slick-trader-core has the same problem. Do not reach for one.

The constructor runs three times

The macro default-constructs your class for create_strategy() and in two function-local statics, one each in get_strategy_name() and get_strategy_version(). Those two statics live until the process exits. So the constructor must not log, must not throw, must not open files or start threads and must be cheap. A throw there escapes an extern "C" function the loader calls without a try. OrderStacker's constructor carries a comment saying so. Do real setup in on_initialize() or on_start().

name() must be constant. The loader reads it from a different instance than the one that runs, and the risk limits, config and order ids are all keyed by it.

Building the plugin

slick_trader_add_strategy() builds a SHARED library linked against slick-trader-core:

slick_trader_add_strategy(my_strategy
    SOURCES my_strategy.cpp my_helper.cpp   # default: <name>.cpp
    LINK    slick::stacker)                 # optional extra targets

It sets an empty PREFIX and the output directory ${CMAKE_BINARY_DIR}/strategies:

Platform File
Windows my_strategy.dll
Linux my_strategy.so (no lib prefix)
macOS my_strategy.dylib

Multi-config generators (Visual Studio, Xcode) add the configuration name: build/strategies/Debug/. Single-config generators write straight to build/strategies/. Point strategies.strategy_plugins_folder at the one you built. The sample config uses build/strategies/Debug.

slick-trader-core is a static library that is not exported or installed as a CMake package. Out-of-repo plugins therefore have nothing to find_package. Add the plugin to strategies/CMakeLists.txt or add_subdirectory it from the engine's build. A dependency only the plugin needs belongs in that file, not the root CMakeLists.txt, so it stays out of -DSLICK_TRADER_BUILD_STRATEGIES=OFF builds.

The CMake options SLICK_TRADER_ENABLE_LUA_STRATEGY and SLICK_TRADER_ENABLE_PYTHON_STRATEGY define macros that no source file reads. Script strategies do not exist.

Loading and what hot-loadable means

Plugins load once, during TradingEngine::initialize. Nothing rescans the folder or swaps a rebuilt binary into a running engine. The library handle is never released: the loader's deleter destroys the object and leaves the library mapped until the process exits. To run a new build, restart the engine.

What does change live is parameters, through PUT /api/strategies/:id/config, and the running state through POST /api/strategies/:id/control (REST API).

Plugin and config problems appear in the log:

Log line Cause
No config find for strategy <name> No *.config.json has "name": "<name>". The strategy loads with empty parameters and the no-file risk limits
Failed to load plugin: <file> and Error: ... The library did not open, a symbol is missing or the API version differs
Strategy <name> is disabled in config, skipping "enabled": false
Failed to parse strategy config file The JSON is malformed, or a risk key has the wrong type. The whole file is skipped

Two plugins with the same name() share a map slot: the later one replaces the first for REST control and config lookups while both keep receiving events.

Testing a strategy

StrategyManagerFixture builds a manager with every queue it needs and no worker thread, so a test pushes events through manager_.process_event() and reads orders off the order queue. test_market_maker_quote_slots.cpp includes strategies/market_maker.cpp directly, since a plugin has no header, and drives it through the public IStrategy interface. probe_plugin.cpp is a minimal real plugin used to test the loader and the injection. See Testing.