Adding a broker¶
A broker is an IBroker that owns a market data connector and an order connector. Each connector has
one worker thread and writes to its own producer buffer on the event bus. The core names no broker, so
adding one touches a single core header (the BrokerId enum). Everything else lives in the broker's own
directory, in tree or out. Read Architecture first, then
Brokers for what the two built-in adapters do. They are the references, and the order
connector rules below come from their mistakes as much as their good habits.
A broker needs a BrokerId, a class, a registration line, two connectors and a CMakeLists.txt. The
examples use a made-up kraken.
1. Add the BrokerId¶
event.hpp
holds the enum, to_string and to_broker_id. A broker is one line in each:
enum class BrokerId : uint8_t {
UNKNOWN = 0, COINBASE, ALPACA, HYPERLIQUID, SIMULATED, CME, ICE,
KRAKEN, // append here, before the count
_BROKER_ID_COUNT_,
};
// to_string: case BrokerId::KRAKEN: return "KRAKEN";
// to_broker_id: else if (broker == "KRAKEN") return BrokerId::KRAKEN;
Append only
The id is written into every event, into the per-broker request queues, into the producer ids
(id * 2 - 1 for market data, id * 2 for orders) and into shared-memory names. Inserting in the middle
renumbers every broker after it and breaks anything reading a queue or state file written before.
The config's name, upper-cased, must equal the string to_broker_id() knows. The engine looks the id up to
find the broker's market data request queue, and stops with names no BrokerId when it finds none. CME and
ICE are already in the enum for brokers kept out of tree. The enum is closed: there is no way to add an id
from outside the repository.
2. Write the IBroker and register it¶
class KrakenBroker : public IBroker {
public:
KrakenBroker(const json& config, slick::stream_buffer_multiplexer& event_mux,
slick::queue<uint8_t>& control_queue, slick::queue<uint8_t>& md_request_queue,
slick::queue<uint8_t>& order_request_queue);
BrokerId get_broker_id() const override { return BrokerId::KRAKEN; }
const char* get_broker_name() const override { return "Kraken"; }
void register_broker() override; // each enabled connector announces itself
bool start() override; // md first, then orders
void stop() override;
void begin_stop() override; // optional: see the order connector
};
SLICK_TRADER_REGISTER_BROKER("kraken", KrakenBroker);
The macro must sit at namespace scope in a .cpp of the broker's OBJECT library. It builds a factory with the
constructor above and adds it to the
BrokerRegistry
at static initialisation. The key is matched to brokers[].name case-insensitively, and a second broker with the
same key is refused.
- Pass each connector its
market_dataororderblock, and passjson::object()when the block is missing. The in-tree brokers pass a default-constructedjson, which is null, and nlohmann'svalue()throws on null. An empty block means the connector is off, as it does in the in-tree connectors. - A constructor may throw. The registry catches it, and the engine logs
Failed to create broker kraken: <what>and stops. Do the work that can fail (reading a key file, building a client) here, not instart(), where nothing catches it. - Every connector reads its own market data request queue (
md_request_queue). The order queue is shared by all brokers.
3. Wire the build¶
slick_trader_add_broker()
makes an OBJECT library named slick_trader_broker_<name>:
find_package(kraken-sdk CONFIG QUIET GLOBAL)
if(NOT kraken-sdk_FOUND)
FetchContent_Declare(kraken-sdk GIT_REPOSITORY ... GIT_TAG ...)
FetchContent_MakeAvailable(kraken-sdk)
endif()
slick_trader_use_slick_net() # only if the SDK uses slick-net: routes its log to the engine
slick_trader_add_broker(kraken
SOURCES kraken_broker.cpp kraken_md_connector.cpp kraken_order_connector.cpp
DEPENDS kraken-sdk
TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_kraken_definitions.cpp)
DEPENDSis linked publicly, so the SDK reaches the engine and the test binary without either naming it.- Resolve dependencies in this file, not the root
CMakeLists.txt, and passGLOBALtofind_package. The engine and the tests link your object library from sibling directories, which cannot see an imported target that was not made global.FetchContenttargets need nothing. - The library must be an OBJECT library. See Brokers for why a static one silently loses the registration.
- A target named
slick_trader_broker_krakendefinesSLICK_TRADER_HAS_KRAKEN=1for anything that links it. Guard test code that needs the broker with it.
For an in-tree broker, add an option and a subdirectory to
src/brokers/CMakeLists.txt,
as Coinbase and Hyperliquid have:
option(SLICK_TRADER_ENABLE_KRAKEN "Build the Kraken broker" ON) # in the root CMakeLists.txt
if(SLICK_TRADER_ENABLE_KRAKEN)
add_subdirectory(kraken)
endif()
4. The market data connector¶
Implement IMarketDataConnector. The helpers in
md_event_writer.hpp
do most of the plumbing.
Construct. Read enabled, add the producer, name the broker, publish its enabled flag:
KrakenMDConnector::KrakenMDConnector(const json& config, slick::stream_buffer_multiplexer& mux,
slick::queue<uint8_t>& control, slick::queue<uint8_t>& requests)
: enabled_(config.empty() ? false : config.value("enabled", true))
, writer_(BrokerId::KRAKEN), control_(control), requests_(requests)
, cursor_(requests.initial_reading_index())
{
auto& registry = BrokerStatusRegistry::instance();
registry.set_name(BrokerId::KRAKEN, "Kraken");
registry.set_md_enabled(BrokerId::KRAKEN, enabled_);
if (enabled_) writer_.open(mux, config); // reads shm_name, queue_size, control_size
}
Register. register_md_connector() calls writer_.register_connector(control_) when enabled. It is the
RegisterEvent the engine uses to attach a shared-memory producer.
Definitions. From start(), publish one InstrumentDefinitionEvent per tradable instrument with
writer_.definition({...}): tick size, contract multiplier, quantity limits, currency. Do it from the
thread that owns the buffer, before another thread starts writing it. The engine applies the multiplier to
position and risk accounting, forwards the event to every strategy and lists the instrument for the
dashboard's ladders. A broker that publishes none leaves ladders listing only what strategies subscribe. Keep
the wire-to-event conversion in a free function, as coinbase_definitions() is, so a test can call it with
no network.
Read requests. The manager sends MDSubscription records for your broker only, on requests_. Read them
with process_md_request(), not your own loop:
const bool read = process_md_request(requests_, cursor_, BrokerId::KRAKEN,
[this](const MDSubscription& r) { subscribe(r); },
[this](const MDSubscription& r) { unsubscribe(r); });
if (!read) std::this_thread::yield();
The helper reports your read position to BrokerStatusRegistry after the handler returns. The manager writes
nothing over what has not been reported read, so a connector that reads the queue another way must report
the same or its requests stall (the manager logs it after md_request_stall_timeout_ms). The handler gets
the request where it lies in the queue. Copy what you keep.
Publish. All market data goes through the writer (trade, levels, orders, status):
- Handle
TRADE,QUOTE,LEVEL2,ORDER_BOOKandMBO. Log and ignore what the venue has no feed for, as Coinbase does forMBO. - A
LEVEL2subscription is enough for quotes: the manager builds them from the book. PublishQUOTEonly where the venue has its own top-of-book feed. - A level with quantity 0 removes the level. A snapshot clears the book, and an empty one is still
published for that reason.
writer_.levels()splits a big snapshot and flags only the first part as the clearing one. - A trade's
sideis the aggressor.is_buyer_makeris true when the aggressor sold. Check which side your venue names before copying it. Coinbase's channel names the maker, and the connector flips it. - Prices are
price_t(1e-8 fixed point) andNULL_PRICEmeans none.PriceScaleconverts an exchange's integer wire price exactly and refuses one it cannot hold, rather than rounding to a price nobody quoted. - For an order-by-order feed, deliver a whole exchange event, then set
is_last. The manager hands the book to strategies only atis_last.LevelBookandOrderBookPublisherturn order changes into levels. - Instrument names are at most 31 characters.
One writer. The producer buffer takes one writer at a time. If the SDK calls back on its own thread,
either have the SDK dispatch to your worker (Hyperliquid's Info::dispatch, Coinbase's processData) or make
sure no other thread writes while it does.
Status. Set md_connected true when the feed is up and false when it drops, with StatusLatch or
BrokerStatusRegistry directly. The manager stops strategies subscribed to a broker whose market data is
enabled but not connected, and restarts them on reconnect. After a reconnect, re-send every subscription. The
manager asked for them once.
5. The order connector¶
Implement IOrderConnector, with the writer from
order_event_writer.hpp.
Construct it like the market data side: OrderEventWriter(BrokerId::KRAKEN), set_order_enabled, and
request_queue.initial_reading_index() for the read cursor. Register with
writer_.register_connector(control_, fees). The fee structure is the fallback for a fill that carries no fee
of its own. Nothing in the engine applies it today, see Brokers.
Read requests, and only your own. Every order connector reads every request on the one shared queue.
dispatch_order_request() does the filtering with is_request_for():
const bool read = dispatch_order_request(requests_, cursor_, BrokerId::KRAKEN,
[this](const NewOrderEvent& r) { handle_new(r); },
[this](const ModifyOrderEvent& r) { handle_modify(r); },
[this](const CancelOrderEvent& r) { handle_cancel(r); });
if (!read) std::this_thread::yield();
Without the filter an order for one broker also goes to every other enabled broker, which rejects it as an unknown product and kills the strategy's order. The queue is a lossy ring: a connector that falls a queue's length behind loses requests. Keep the loop short and do slow venue calls off it.
Answer every request. A strategy waits on each one.
| Request | Publish |
|---|---|
| New order | An ack when the venue accepts it, or a reject with the reason, up to 127 characters. An exception becomes a reject |
| Modify | An ack with the new price and quantity, or a reject carrying the client and broker order ids. A reject for an amendment leaves the original order resting. The strategy must not take it for a dead order |
| Cancel | A cancel event, or a reject. Say so when the venue refuses |
A path that logs and publishes nothing leaves the order in PENDING_* for good. Both in-tree connectors have
a few: Hyperliquid's failed modify and cancel, Coinbase's cancel that throws.
Put both ids on every event. Set client_order_id when you know it and order_id always. A strategy
recognises an event as its own by the client id, or, when the venue omits it on a follow-up, by the order id
recorded at ack time. An event with neither belongs to nobody and is dropped. Set side and the instrument too.
Fills. One OrderFillEvent per execution:
fill_quantityandfill_priceare this fill alone, not cumulative.cumulative_filledandremaining_quantityare the order's. Setremaining_quantitytruthfully:StrategyBasemarks the order filled at 0, and strategies read 0 as a full fill.fee_amountis the fee of this fill in quote currency. Leave it 0 only when the venue does not say, and the position tracker falls back to the fee structure.fill_ididentifies the execution. Setcontract_multiplierif you know it, so a fill replayed before the instrument's definition arrives is still valued correctly.scopeisORDER_AND_POSITIONfor an ordinary fill. For a multi-leg instrument (a futures spread), publish oneORDERfill at the order's own price, which moves the order only, then oneLEGfill per leg with the leg's instrument, side, price and quantity, which moves the position only. Positions and risk live on the legs. See Order lifecycle.
Deduplicate. Venues repeat themselves. CoinbaseOrderStates shows the shape: remember the last state
published per order and drop what changes nothing, mark an order ended once and ignore later acks and
cancels, and bound the memory by forgetting the oldest ended orders. Without it a single Coinbase order came
to strategies as three acks and three cancels. Deduplicate fills too: Hyperliquid's connector reports an
immediate fill twice, once from the order response and once from the fill stream.
Journal fills. FillJournal writes every fill to a memory-mapped ring before it is published. After
a crash between a report arriving and the strategies booking it, the connector replays the journal at start
with writer_.replay(journal, "Kraken"), each fill flagged replayed. Fills carry a journal_seq, and the
manager drops those the position store already has. SlotStore keeps session state and working orders in the
same style. Neither in-tree broker journals, so a fill lost in that window is lost.
Status. Set order_connected true only while orders can be taken, and false otherwise.
submit_order() refuses an order the moment the flags say no, so a connector that stays "connected" while
its session is down gets orders it must reject itself.
Stopping. begin_stop() runs before the strategies stop, and stop() after. The cancels strategies send
as they stop arrive between the two, so the connector must still read requests then. run_kill_switch() is
a helper for pulling every working order before a session closes, waiting for confirmations up to a
timeout (the convention is a cancel_on_stop_ms key). You give it two callbacks: one that reads your
sockets and one that asks each session to cancel what it still has.
Post-only. StrategyBase::submit_order() clears post_only for CME and ICE, a hard-coded list. A venue
without a post-only instruction needs a policy: PostOnlyPolicy and parse_post_only_policy() in
order_entry.hpp implement the usual four (reject_if_crossing, accept, reject, and the venue's own).
REJECT_IF_CROSSING reads the top of book your market data connector shares through SharedTopOfBook.
6. Out of tree¶
A broker that lives in its own repository calls slick_trader_add_broker() from its own CMakeLists.txt and
joins the build by path:
Separate several paths with ; and quote the whole argument. Keep it in a git-ignored
CMakeUserPresets.json so no local path reaches the repository. The directory needs:
- A
CMakeLists.txtthat guards against being configured alone, as slick-trader-cme does:if(NOT COMMAND slick_trader_add_broker) message(FATAL_ERROR ...). - A
project(... VERSION x.y.z)if you want the version shown with the broker when configure lists it. - Its dependencies resolved in that file with
GLOBAL.slick_trader_find_codec()finds a codec library as a package, then a sibling source tree, then a git fetch.slick_trader_require_slick_socket()guaranteesslick-socketat a minimum version and refuses a broker that needs a later one than the engine took. - Its
BrokerId. The enum is in the core header, so unless the broker uses a reserved id (CME,ICE) the one-line change from section 1 goes into this repository.
Configure reports each directory it adds and the brokers it registered, and warns when a directory registers nothing. A config that enables the broker, with the binary built without it, fails startup with the list of adapters it does have. See Building.
7. Tests¶
TESTS files are compiled into slick-trader-tests for as long as the broker is built, so the suite
travels with the broker, in tree or out. Link nothing extra: slick_trader_link_brokers() already links your
object library to the test binary.
- Make connectors testable without a network. A connector built with
{"enabled": false}opens no socket, and a test can call its SDK callback directly, then read the events back off the multiplexer. That is how the Coinbase trade-side test works. - Put pure conversions (definitions, price scaling, state machines) in free functions or small classes,
as
coinbase_definitions()andCoinbaseOrderStatesare, and test them directly. - Test the registration:
BrokerRegistry::instance().find("kraken")is non-null under#ifdef SLICK_TRADER_HAS_KRAKEN. - The helpers have their own tests to copy:
test_order_entry.cpp,test_broker_state_files.cppfor the journal and slot store,test_level_book.cppandtest_order_book_publisher.cpp.
See Testing.
Checklist¶
BrokerIdappended before_BROKER_ID_COUNT_, with itsto_stringandto_broker_idlines.- The config
name, upper-cased, equals theto_broker_id()string. IBrokersubclass with the five-argument constructor, andSLICK_TRADER_REGISTER_BROKERat namespace scope in a.cppof the OBJECT library.slick_trader_add_broker()withSOURCES,DEPENDSandTESTS. SDK found withGLOBAL. Option andadd_subdirectoryfor an in-tree broker, or the path inSLICK_TRADER_EXTERNAL_BROKERS.- Missing config blocks passed as
json::object(). Anything that can fail done in the constructor. - Market data: producer opened, name and
md_enabledset,RegisterEventsent, definitions published, requests read throughprocess_md_request(), every subscription type handled or logged and ignored,md_connectedkept true to the connection, subscriptions re-sent after a reconnect. - Orders:
dispatch_order_request()filters by broker, every request is answered, both ids are on every event,remaining_quantityandfee_amountare real, fills and cancels are deduplicated. - Multi-leg instruments use
ORDERandLEGfills. - Fills journaled and replayed if a lost fill is not acceptable.
order_enabledandorder_connectedmatch what the connector can do, andbegin_stop()andstop()keep the cancels strategies send on the way out.- Tests registered through
TESTS, a registration test underSLICK_TRADER_HAS_<NAME>, and the wire conversions tested with no network.
Related¶
- Brokers: what the two built-in adapters do
- Market data: events, subscriptions and book building
- Order lifecycle: the path of an order and its events
- Building: options and external brokers