Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_ws_order_gateway.hpp
Go to the documentation of this file.
3#include <nlohmann/json.hpp>
4// #define JWT_DISABLE_PICOJSON
5#include <jwt-cpp/jwt.h>
6#include <jwt-cpp/traits/nlohmann-json/traits.h>
7#include <unordered_map>
8#include <string>
9#include <atomic>
10#include <format>
11#include <chrono>
12#include <iomanip>
13#include <sstream>
14
15struct us_listen_socket_t;
16using json = nlohmann::json;
17
19
20// Per-socket data structure for uWebSockets
22 std::string sub; // JWT sub claim
23 std::string user_id;
24 uint64_t seq_num;
25 std::chrono::steady_clock::time_point last_pong; // Track last pong received
26 bool authenticated = false;
28 static uint_fast64_t heartbeat_count;
29};
30
32 // std::thread ws_thread_;
33 // us_listen_socket_t* listen_socket_ = nullptr;
34 // uWS::Loop* loop_ = nullptr;
35 us_timer_t* heartbeat_timer_ = nullptr;
36 // uint32_t port_ = 3000;
37 std::atomic_bool running_{false};
38
39 // Response queue read index
40 uint64_t response_read_index_ = 0;
41
42 using wsT = uWS::WebSocket<false, true, PerSocketData>;
43
44 // Client connection mapping: user_id -> WebSocket connection
45 // No mutex needed - all access is from the single event loop thread
46 std::unordered_map<std::string, wsT*> clients_;
47
48 // Heartbeat configuration
49 int ping_interval_ms_{15000}; // Send ping every 30 seconds (in milliseconds)
50 std::chrono::seconds pong_timeout_{60}; // Disconnect if no pong for 60 seconds
51
52 std::string products_;
53 std::unordered_map<std::string, std::string> product_by_id_;
57 OrderStore orders_;
58 double fee_rate_ = 0.0012; // 1.2%
59
60public:
61 CoinbaseWebsocketOrderGateway(const json& config, slick::queue<Request> &request_queue, slick::queue<OrderResponse> &response_queue);
62
63 ~CoinbaseWebsocketOrderGateway() override = default;
64
65 std::string_view type() const noexcept override { return "WS"; }
66
67 void start() override {
68 running_.store(true, std::memory_order_release);
70 }
71
72 // void start() override {
73 // running_.store(true, std::memory_order_release);
74
75 // // Start WebSocket server thread (handles everything in event loop)
76 // ws_thread_ = std::thread([this]() {
77 // auto app = uWS::App();
78
79 // app.ws<PerSocketData>("/*", {
80 // /* WebSocket settings */
81 // .compression = uWS::SHARED_COMPRESSOR,
82 // .maxPayloadLength = 16 * 1024,
83 // .idleTimeout = 120,
84 // .maxBackpressure = 1 * 1024 * 1024,
85
86 // /* WebSocket handlers */
87 // .upgrade = nullptr,
88
89 // .open = [this](auto *ws) {
90 // // Initialize connection timestamp
91 // ws->getUserData()->last_pong = std::chrono::steady_clock::now();
92 // ws->getUserData()->authenticated = false;
93 // LOG_INFO("WebSocket client connected");
94 // },
95
96 // .message = [this](auto *ws, std::string_view message, uWS::OpCode /* opCode */) {
97 // handleMessage(ws, message);
98 // },
99
100 // .drain = [](auto */* ws */) {
101 // // Check backpressure
102 // },
103
104 // .ping = [](auto *ws, std::string_view /* message */) {
105 // // Automatically respond to client ping with pong
106 // // uWebSockets handles this automatically, but we log it
107 // LOG_TRACE("Received ping from client {:p}", (void*)ws);
108 // },
109
110 // .pong = [this](auto *ws, std::string_view /* message */) {
111 // // Client responded to our ping
112 // ws->getUserData()->last_pong = std::chrono::steady_clock::now();
113 // LOG_TRACE("Received pong from client {:p}", (void*)ws);
114 // },
115
116 // .close = [this](auto *ws, int code, std::string_view message) {
117 // handleClose(ws, code, message);
118 // }
119 // })
120 // .listen(port_, [this, &app](auto *listen_socket) {
121 // listen_socket_ = listen_socket;
122 // if (listen_socket) {
123 // LOG_INFO("Coinbase WebSocket OrderGateway started on port {}", port_);
124
125 // // Get the event loop
126 // loop_ = uWS::Loop::get();
127
128 // // Create heartbeat timer in the event loop
129 // // Use defer() to create timer with proper lambda capture
130 // loop_->defer([this]() {
131 // heartbeat_timer_ = us_create_timer((struct us_loop_t*)loop_, 0, 0);
132
133 // // Store 'this' pointer in timer extension data
134 // *((CoinbaseWebsocketOrderGateway**)us_timer_ext(heartbeat_timer_)) = this;
135
136 // // Set timer callback that retrieves 'this' from extension data
137 // us_timer_set(heartbeat_timer_, [](struct us_timer_t *timer) {
138 // // Dereference the pointer stored in extension data
139 // auto* self = *((CoinbaseWebsocketOrderGateway**)us_timer_ext(timer));
140 // self->checkHeartbeats();
141 // }, ping_interval_ms_, ping_interval_ms_);
142 // });
143
144 // LOG_INFO("Event loop configured (heartbeat: {}ms)", ping_interval_ms_);
145
146 // // Start continuous response processing
147 // scheduleResponseProcessing();
148
149 // } else {
150 // LOG_ERROR("Failed to listen on port {}", port_);
151 // }
152 // })
153 // .run();
154 // });
155 // }
156
157 void stop() override {
158 running_.store(false, std::memory_order_release);
159
160 // Close heartbeat timer
161 if (heartbeat_timer_) {
162 us_timer_close(heartbeat_timer_);
163 heartbeat_timer_ = nullptr;
164 }
165
167
168 // Clear client connections (no lock needed - thread already joined)
169 clients_.clear();
170 }
171
172private:
173 void setup_routes(uWS::App &app) override;
174
175 void on_listen_socket(us_listen_socket_t *listen_socket) override;
176
177 // Handle incoming WebSocket messages
178 void handle_message(wsT *ws, std::string_view message);
179
180 // Handle WebSocket close event
181 void handle_close(wsT *ws, int code, std::string_view message);
182
183 // Send error message to client
184 void send_error(wsT *ws, const std::string& error_msg);
185
186 // Schedule response processing to run in the event loop
187 void schedule_response_processing() {
188 if (!running_.load(std::memory_order_acquire) || !loop_) {
189 return;
190 }
191
192 loop_->defer([this]() {
193 process_all_responses();
194 });
195 }
196
197 // Process all available responses from the queue
198 // Called continuously via defer() or after WebSocket events
199 void process_all_responses();
200
201 void handle_order_response(const OrderResponse &response, wsT *ws);
202
203 // Heartbeat check - called by timer in event loop
204 void check_heartbeats();
205};
206
207}
CoinbaseWebsocketOrderGateway(const json &config, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue)
Tracks the orders reported to one gateway.
RestWsOrderGateway(Venue venue, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue, uint32_t port)
nlohmann::json json
Definition order.hpp:16
std::chrono::steady_clock::time_point last_pong