Brokers¶
Two broker adapters are built in: Coinbase Advanced Trade and Hyperliquid. Each is a market data
connector and an order connector, with a worker thread apiece, wrapped in one IBroker. The two adapters differ in what they
accept, how they report fills, and what they do when a connection drops. Config keys are on
Configuration. To write another, see Adding a broker.
BrokerId also lists ALPACA, SIMULATED, CME and ICE. They are identifiers only. No Alpaca
or simulated adapter exists in this repository, and CME and ICE are brokers kept out of tree.
Hyperliquid cannot place orders in this build
The order connector's private_key_ is never assigned, so connect() always fails with Private key
not set and the connector never starts. Market data works. Nothing reads the environment variable the
error message names. See Credentials.
How a broker plugs in¶
IBroker
is the whole surface the engine sees: get_broker_id(), get_broker_name(), register_broker(),
start(), stop(), an optional begin_stop() and an optional get_fees(). The two connector interfaces
(IMarketDataConnector, IOrderConnector) are internal to the adapter. The engine never touches them.
A broker joins the build in three steps.
- Register. One line at namespace scope in a
.cppof the adapter:SLICK_TRADER_REGISTER_BROKER("coinbase", CoinbaseBroker);. It adds a factory toBrokerRegistryduring static initialisation. The key is lower-cased and matched case-insensitively against the config'sbrokers[].name. A duplicate key is refused and the first registration stays. The factory takes the broker's JSON block, the event multiplexer, the control queue, the broker's own market data request queue and the shared order request queue. A constructor that throws is caught and reported asFailed to create broker. - Build as an OBJECT library.
slick_trader_add_broker()creates the target asOBJECTon purpose. Nothing in the core names the registration, so from a static library the linker would drop the object file and the broker would vanish from the registry without an error. Object files go to the linker one by one, and the initialiser survives.slick_trader_link_brokers()links every enabled broker into both the engine and the test binary. - Switch on.
SLICK_TRADER_ENABLE_COINBASEandSLICK_TRADER_ENABLE_HYPERLIQUIDareONby default. Out-of-tree brokers are listed inSLICK_TRADER_EXTERNAL_BROKERS. See Building.
An enabled config entry with no adapter in the binary stops startup. The log names what the binary has.
What a broker publishes at startup¶
sequenceDiagram
autonumber
participant E as Main thread
participant B as Broker
participant C as Control queue
participant MD as MD worker thread
participant O as Order worker thread
E->>B: BrokerRegistry::create(config, ...)
Note over B: connectors built, producers added to the event bus,<br/>name and enabled flags written to BrokerStatusRegistry
E->>B: register_broker()
B->>C: RegisterEvent (market data), OrderConnectorRegisterEvent (order)
E->>C: BrokerRegisterEndEvent
E->>B: start()
B->>MD: start, publish InstrumentDefinitionEvents
MD->>MD: read the market data request queue
B->>O: start, connect, publish acks, fills, rejects, cancels
- Status. The market data connector sets the broker's display name and
md_enabled. The order connector setsorder_enabled. Theconnectedflags change as sockets come and go. Strategies read all four throughBrokerStatusRegistry, andsubmit_order()refuses an order when the order flags say no. The manager also usesmd_enabledto decide whether to wait on a connector's request queue. A connector with its block missing or empty, orenabled: false, is disabled. - Producers. Each connector adds its own producer buffer to the event multiplexer. That buffer has a single writer, the connector's worker.
- Registration. An enabled connector writes a register event on the control queue. The event carries the producer id and, for a shared-memory producer, its segment name.
- Definitions. Each market data connector publishes an
InstrumentDefinitionEventper tradable instrument from itsstart(). The engine applies the contract multiplier and gives the list to the dashboard's ladders. A failure to fetch the list is logged and leaves ladders with only what strategies subscribe. - Request cursor. The market data worker reports how far it has read its request queue. The manager writes no further ahead of it than the queue holds.
Side by side¶
| Coinbase | Hyperliquid | |
|---|---|---|
| Venue | Advanced Trade REST and WebSocket | Hyperliquid REST and WebSocket, through its SDK |
| Instruments | Every product in the public product list that is not disabled or view-only. Names like BTC-USD. The contract multiplier is 1 for all of them |
Definitions cover perpetuals only (asset index below 10000), named by bare coin such as BTC. A subscription to a name the SDK's metadata does not know is skipped with an error |
| Instrument tick | price_increment, or quote_increment when that is 0 |
0, since a perp's tick depends on price. The quantity step comes from the coin's size decimals. Currency USDC |
| Market data | market_trades, ticker and level2 channels |
trades, bbo, l2 and l2Book channels |
TRADE |
market_trades. The channel names the maker's side, and the connector flips it so side is the aggressor |
trades. side is the taker's |
QUOTE |
ticker |
bbo |
LEVEL2 |
level2. A snapshot, then updates |
l2, a compressed diff channel the connector expands with its own price index. Published as snapshot then updates |
ORDER_BOOK |
The same level2 channel as LEVEL2 |
l2Book, a full book on every message, each published as a snapshot |
MBO |
Logged and ignored | Logged and ignored |
| Not implemented | candles and status handlers are empty |
|
| Order entry | REST. Order updates over the authenticated user WebSocket channel |
The SDK's Exchange (REST). Fills and cancels over the userFills and orderUpdates streams |
| Credentials | COINBASE_API_KEY and COINBASE_API_SECRET in the environment, read by the SDK |
None can be supplied: see Credentials |
| Fill journal | None | None |
| Kill switch on stop | None. Strategies cancel as they stop | None. Strategies cancel as they stop |
Both brokers pass the strategy's instrument string to the venue unchanged. A Coinbase strategy that says
BTC/USD subscribes to nothing.
Market data requests¶
StrategyManager sends one MDSubscription per broker, type and run of instruments, on that broker's own
queue. Each connector's worker reads them with process_md_request(), which also reports the read position.
Coinbase and Hyperliquid both add the instruments to their own lists and call the SDK's subscribe. The
manager counts holders, so a connector sees one request per broker, type and instrument however many
strategies and ladders want it.
Order types and time in force¶
An order that a connector cannot express becomes an OrderRejectEvent on that connector's producer. The
strategy sees on_reject with the venue's reason text, up to 127 characters.
Coinbase order types¶
The connector converts the order type and TIF, then calls the SDK's create_order(), which builds the
request body. The SDK refuses unsupported combinations locally, before any HTTP request. This table follows
the SDK source at the minimum version the build requires (2.1.1).
| Order type | GTC | IOC | FOK | GTD | DAY |
|---|---|---|---|---|---|
MARKET |
Rejected | Sent | Sent | Rejected | Rejected |
LIMIT |
Sent. post_only honoured |
Sent as a smart-order-routed IOC. post_only ignored |
Sent. post_only ignored |
Rejected | Rejected |
STOP_LIMIT |
Sent. Needs a stop price | Rejected | Rejected | Rejected | Rejected |
STOP |
Rejected, whatever the TIF | ||||
BRACKET |
Sent as a trigger bracket, whatever the TIF. Needs a stop and a take-profit price, the latter taken from price. A spot BUY is rejected |
DAY fails in the connector (Unsupported time in force), the rest in the SDK. A GTD order has no end
time to send, so it fails too. MARKET ignores the price. Orders are sized in base units, never in quote.
Modify takes a price, a quantity and an optional stop. Cancel goes by broker order id.
Hyperliquid order types¶
Order entry is unreachable today (see the warning at the top), so this is what the code does once a key is supplied.
| Order type | Sent as | Notes |
|---|---|---|
MARKET |
market_open with 5% slippage |
TIF and post_only are not looked at, so DAY is accepted |
LIMIT, BRACKET |
A limit order | BRACKET is sent as a plain limit |
STOP |
A trigger order, market on trigger | Trigger is stop_price, or price when there is none. Always a stop-loss trigger |
STOP_LIMIT |
A trigger order, limit on trigger | Limit price is price, or the trigger when there is none |
For LIMIT the TIF maps like this:
| TIF | Sent as |
|---|---|
GTC |
Gtc |
GTD |
Gtc. No expiry is sent |
IOC |
Ioc |
FOK |
Ioc. It is not fill-or-kill |
DAY |
Rejected: Hyperliquid does not support time in force DAY |
any, with post_only |
Alo, which overrides the row above |
Modify re-sends the order as a limit with the new price and size, and ignores the new stop price. Cancel goes by numeric order id.
Order state and duplicates¶
Coinbase order state¶
Coinbase reports most things twice. The REST response and the user channel both acknowledge a new order,
both report a cancel, and the channel repeats updates. CoinbaseOrderStates remembers the last state
published for each order id, so each change goes out once:
- An ack goes out only if its status, price, stop price or quantity differs from the last one. A price, stop or quantity the update leaves out (the channel has no base size for a pending order) keeps the known value.
- A
PENDING_NEWack is dropped once the order is open, since the REST response can arrive after the channel. - Once an order has ended, filled or cancelled, further acks and cancels for it are dropped. The last 1024 ended orders are remembered, oldest evicted first.
- A refused cancel does not mark the order ended, since the order may still be live.
Hyperliquid order state¶
Fills from the userFills stream are deduplicated by trade id in a set that is never pruned. A fill the
order response already reported (an order that fills on entry) is published again by the stream, since the
response carries no trade id to remember.
How fills are derived¶
Coinbase fills¶
Coinbase gives cumulative numbers per order, and the connector turns them into increments. It keeps the previous cumulative quantity, average price and total fees per order:
last_qty = cumulative_qty - prev_cumulative_qty
last_price = (avg * cumulative_qty - prev_avg * prev_cumulative_qty) / last_qty
fee = total_fees - prev_total_fees
The average is filled_value / cumulative_quantity when both are positive. A fill is skipped, with a
warning, when last_qty or last_price is not positive or the price exceeds 1e9. The skip leaves the saved
state alone, so a sentinel price cannot corrupt the next fill. A fill goes out on an OPEN update when
number_of_fills grew, and on FILLED. Its fill_id is the fill count and remaining_quantity is the
order's leaves quantity.
Hyperliquid fills¶
One fill per userFills entry: price, size, trade id as fill_id, time converted from milliseconds, and
the fee as a positive amount. An order that fills at entry also produces a fill from the order response, at
the average price.
Hyperliquid fills always report remaining quantity 0
Every fill event from this connector sets remaining_quantity to 0 and cumulative_filled to that
fill's own size. StrategyBase takes that as the order being complete, so a partial fill marks the
order FILLED. MarketMaker treats remaining <= 0 as a full fill and clears its quote slot.
Reconnect behaviour¶
| Coinbase | Hyperliquid | |
|---|---|---|
| Market data drops | md_connected goes false and the worker re-sends every subscription on its next pass. Auto-pause stops strategies subscribed to this broker until it returns |
Nothing marks it down. The connector sets md_connected once, in connect(), and has no handler for a dropped socket. A connect() that fails is not retried, and subscription requests made while there is no connection are dropped |
| Order connection drops | order_connected goes false, new orders are refused with Broker order connector disconnected, and the connector subscribes the user channel again. The snapshot it gets is processed like any update |
Same as market data: no handler |
| Error on the user channel | Disconnect and reconnect | None |
Orders working at the venue when a connection drops are not cancelled by the engine. The Coinbase user channel's snapshot after a reconnect re-publishes the state of open orders through the same dedupe.
Fees¶
A fill's own fee is used when it is positive. Coinbase sets fee_amount from the order's total_fees
increment and Hyperliquid from the stream's fee field, as an absolute value. Hyperliquid's fee field is
signed and the connector takes its absolute value, so a rebate would book as a cost. Otherwise the position
tracker falls back to its fee structure, which stays at rate 0 because nothing in the engine sets it.
Both brokers implement IBroker::get_fees(): Coinbase fetches the taker rate and caches it, Hyperliquid
returns 0.05%. Nothing calls it. The same rate goes into the OrderConnectorRegisterEvent
at registration, where the engine does not read it. Coinbase makes its REST call for it while registering. The
Hyperliquid register event names BrokerId::COINBASE and carries 0.5%. Neither value reaches PnL.
Credentials¶
The engine reads no credentials. They come from environment variables, never from the config file.
| Broker | Source |
|---|---|
| Coinbase | COINBASE_API_KEY and COINBASE_API_SECRET, read by the Coinbase SDK the first time it signs a JWT, then kept for the process. The secret is a PEM EC key. Literal \n sequences and surrounding quotes in the value are fixed up. Market data channels are public and need none |
| Hyperliquid | None can be supplied. The connector wants a hex private key in private_key_ and names HYPERLIQUID_PRIVATE_KEY in its error, but no code assigns the member or reads that variable, and the SDK's Exchange takes the key only as a constructor argument |
Market data from Hyperliquid and Coinbase's public channels need no secret. Against slick-sim Coinbase still signs a JWT, so the variables need a valid key even though the simulator accepts any well-formed token.
Shared helpers¶
include/slick-trader/brokers/common/
holds the building blocks out-of-tree brokers share. The built-in brokers use only a few: process_md_request()
and publish_definition() from md_event_writer.hpp, and is_request_for() from iorder_connector.hpp.
| Header | Provides |
|---|---|
md_event_writer.hpp |
MdEventWriter (trades, levels, orders, status and definitions into a producer buffer), process_md_request(), publish_definition(), the odd and even producer ids |
order_event_writer.hpp |
OrderEventWriter, dispatch_order_request() and fill-journal replay |
connector_support.hpp |
env_or() for credentials, wall clock helpers, StatusLatch for the connected flags |
order_entry.hpp |
Post-only policy for venues with no post-only order, lot rounding, a request rate limit, the local reject of a new order |
fill_journal.hpp, slot_store.hpp |
A memory-mapped ring of published fills, replayed after a restart, and the file layout it and session state share |
level_book.hpp, order_book_publisher.hpp, shared_top_of_book.hpp |
Turn an order-by-order feed into price levels, and share the top of book with the order worker |
price_scale.hpp |
Exact conversion between a venue's integer prices and price_t |
polled_link.hpp, kill_switch.hpp |
Servicing sockets from the connector's own thread, and a cancel-everything pass when stopping |
instrument_directory.hpp |
Instruments by symbol and by the venue's numeric id |
MdEventWriter and OrderEventWriter both read shm_name for the producer's segment. The in-tree order
connectors read callback_shm_name. A broker built on OrderEventWriter therefore uses the shorter key.
Related¶
- Adding a broker
- Market data: the events connectors publish and how the manager builds books
- Order lifecycle: what happens between
submit_order()and a connector - Configuration: every connector key