Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_exchange.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <slick/stream_buffer_multiplexer.hpp>
5#include <coinbase/websocket.hpp>
6#include <queue>
7#include <array>
8#include <unordered_map>
10
11namespace slick::sim::exch {
12
13enum class EventType : uint8_t { LEVEL_UPDATE, TRADE };
14
15using WebSocketClient = coinbase::WebSocketClient;
16
17class CoinbaseExchange : public Exchange, public coinbase::UserThreadWebsocketCallbacks {
18public:
19 CoinbaseExchange(const nlohmann::json &config);
20
21 ~CoinbaseExchange() override = default;
22
23 [[nodiscard]] std::vector<FeedInfo> enabledFeeds() const override;
24
25 void onMarketDataConnected(WebSocketClient* client) override;
26 void onMarketDataDisconnected(WebSocketClient* client) override;
27 void onUserDataConnected(WebSocketClient* client) override;
28 void onUserDataDisconnected(WebSocketClient* client) override;
29 void onLevel2Snapshot(WebSocketClient* client, uint64_t seq_num, const coinbase::Level2UpdateBatch& snapshot) override;
30 void onLevel2Updates(WebSocketClient* client, uint64_t seq_num, const coinbase::Level2UpdateBatch& updates) override;
31 void onMarketTradesSnapshot(WebSocketClient* client, uint64_t seq_num, const std::vector<coinbase::MarketTrade>& snapshots) override;
32 void onMarketTrades(WebSocketClient* client, uint64_t seq_num, const std::vector<coinbase::MarketTrade>& trades) override;
33 void onTickerSnapshot(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Ticker>& /* tickers */) override {}
34 void onTickers(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Ticker>& /* tickers */) override {}
35 void onCandlesSnapshot(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Candle>& /* candles */) override {}
36 void onCandles(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Candle>& /* candles */) override {}
37 void onStatusSnapshot(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Status>& /* status */) override {}
38 void onStatus(WebSocketClient* /* client */, uint64_t /* seq_num */, uint64_t /* timestamp */, const std::vector<coinbase::Status>& /* status */) override {}
39 void onMarketDataGap(WebSocketClient* client) override;
40 void onUserDataGap(WebSocketClient* client) override;
41 void onUserDataSnapshot(WebSocketClient* /* client */, uint64_t /* seq_num */, const std::vector<coinbase::Order>& /* orders */, const std::vector<coinbase::PerpetualFuturePosition>& /* perpetual_future_positions */, const std::vector<coinbase::ExpiringFuturePosition>& /* expiring_future_positions */) override {}
42 void onOrderUpdates(WebSocketClient* /* client */, uint64_t /* seq_num */, const std::vector<coinbase::Order>& /* orders */) override {}
43 void onMarketDataError(WebSocketClient* client, std::string &&err) override;
44 void onUserDataError(WebSocketClient* client, std::string &&err) override;
45
46protected:
47 void handleMdSubscription(const Request &request) override;
48 void handleMdUnsubscription(const Request &request) override;
49 void poll() override;
50 void processSequencedEvents(bool force = false);
51
52private:
53 Symbol* addSymbol(std::string_view product_id);
54
55 struct Event {
56 EventType type;
57 uint64_t received_time; // When we received it (system time)
58 uint64_t event_time; // Coinbase's exchange timestamp
59 uint64_t sequence_id; // Internal counter for tiebreaking
60 uint64_t seq_num;
61 price_t price;
62 qty_t qty;
63 Side side;
64 // Defaulted because onMarketTrades used to leave it alone: `Event evt;`
65 // default-initialises, so dispatchEvent's TRADE branch read an indeterminate
66 // value to decide is_last_in_batch for a resting remainder.
68 };
69
70 // std::priority_queue pops the *greatest* element, so every comparison here is
71 // inverted: `a < b` must mean "a is processed after b".
72 struct EventCompare {
73 bool operator()(const Event& a, const Event& b) const {
74 if (a.event_time != b.event_time) {
75 // Earliest event time first.
76 return a.event_time > b.event_time;
77 }
78 if (a.type != b.type) {
79 // A trade and the level update reflecting it share a timestamp but
80 // arrive on independent channels, so sequence_id (arrival order)
81 // is arbitrary between them. Always apply the trade first: the
82 // level update is then measured against a book that has already
83 // absorbed it, instead of reducing the same quantity twice.
84 return a.type != EventType::TRADE;
85 }
86 // For equal timestamps and types, pop the highest sequence_id first.
87 // The enqueue loops use opposite directions to restore chronological order:
88 // onLevel2Updates walks oldest-first data in reverse; onMarketTrades walks
89 // newest-first data forwards. Inverting this tie-break would replay both
90 // batches backwards, leaving stale levels and assigning trade ids in reverse.
91 return a.sequence_id < b.sequence_id;
92 }
93 };
94
95 // Per-symbol event sequencing state
96 struct SymbolEventState {
97 std::priority_queue<Event, std::vector<Event>, EventCompare> pending_events;
98 uint64_t last_event_time = 0;
99 uint64_t last_sequence_id = 0;
100 uint64_t last_seq_num = 0;
101 uint64_t next_sequence_id = 0;
102 uint64_t last_published_level_seq_num = 0;
106 std::vector<MDLevel> level_update_buffer_;
107 // Stamped onto every book mutation in place of the venue's seq_num. The
108 // book silently discards a mutation whose sequence regresses, and both
109 // venue-side counters regress here by construction: this queue reorders
110 // arrival into event_time order, so a trade that arrived late carrying an
111 // earlier event_time dispatches ahead of the l2 batch it overtook - and
112 // takes the higher seq_num with it, sinking that whole batch. Only a
113 // counter handed out at dispatch is monotonic in dispatch order.
114 uint64_t next_book_seq_num = 0;
115 };
116
121 uint64_t nextBookSeqNum(Symbol* symbol, SymbolEventState& state);
122
123 void dispatchEvent(Symbol* symbol, const Event& event, SymbolEventState& state, uint64_t book_seq_num);
124 void populateMDTradesResponse(Symbol* symbol);
125
126private:
127 slick::stream_buffer_multiplexer ws_mux_;
128 std::unordered_map<md_feed::MDFeed*, std::unordered_set<std::string>> feed_symbols_;
129 std::unordered_map<std::string, std::shared_ptr<md_feed::MDFeed>> map_symbol_feed_;
130 std::array<std::unordered_set<Symbol*>, static_cast<size_t>(coinbase::WebSocketChannel::_CHANNEL_COUNT_)> pending_md_subscription_;
131
132 bool use_live_feed_ = false;
133
134 std::unordered_map<Symbol*, SymbolEventState> symbol_event_state_;
135};
136
137} // end namespace slick::sim::exch
void onStatusSnapshot(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Status > &) override
void onUserDataSnapshot(WebSocketClient *, uint64_t, const std::vector< coinbase::Order > &, const std::vector< coinbase::PerpetualFuturePosition > &, const std::vector< coinbase::ExpiringFuturePosition > &) override
void onLevel2Snapshot(WebSocketClient *client, uint64_t seq_num, const coinbase::Level2UpdateBatch &snapshot) override
void onUserDataError(WebSocketClient *client, std::string &&err) override
void onLevel2Updates(WebSocketClient *client, uint64_t seq_num, const coinbase::Level2UpdateBatch &updates) override
void onTickerSnapshot(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Ticker > &) override
void onMarketDataError(WebSocketClient *client, std::string &&err) override
void onUserDataConnected(WebSocketClient *client) override
void onTickers(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Ticker > &) override
void poll() override
One iteration of the exchange thread's loop, called continuously between start() and stop().
void onMarketDataDisconnected(WebSocketClient *client) override
void onCandles(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Candle > &) override
void onOrderUpdates(WebSocketClient *, uint64_t, const std::vector< coinbase::Order > &) override
~CoinbaseExchange() override=default
void handleMdUnsubscription(const Request &request) override
void onMarketDataConnected(WebSocketClient *client) override
void onUserDataDisconnected(WebSocketClient *client) override
void onUserDataGap(WebSocketClient *client) override
void processSequencedEvents(bool force=false)
CoinbaseExchange(const nlohmann::json &config)
void onCandlesSnapshot(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Candle > &) override
std::vector< FeedInfo > enabledFeeds() const override
The market-data feeds the config enables: those in md_feed_ and md_feeds_.
void handleMdSubscription(const Request &request) override
void onStatus(WebSocketClient *, uint64_t, uint64_t, const std::vector< coinbase::Status > &) override
void onMarketDataGap(WebSocketClient *client) override
void onMarketTradesSnapshot(WebSocketClient *client, uint64_t seq_num, const std::vector< coinbase::MarketTrade > &snapshots) override
void onMarketTrades(WebSocketClient *client, uint64_t seq_num, const std::vector< coinbase::MarketTrade > &trades) override
Exchange(Venue venue, const nlohmann::json &config)
Definition exchange.cpp:21
Helpers for a venue whose one config entry describes several independent exchange instances,...
Definition exchange.hpp:30
coinbase::WebSocketClient WebSocketClient
@ TRADE
Reserved.
int_fast64_t qty_t
Definition types.hpp:22
int_fast64_t price_t
Definition types.hpp:21