Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
json_parser.cpp
Go to the documentation of this file.
1#include "json_parser.hpp"
2#include <slick/logger.hpp>
3#include <algorithm>
4
6
7JsonParser::JsonParser() : exec_id_counter_(1) {}
8
9bool JsonParser::can_handle(const uint8_t* data, size_t length) const {
10 if (length == 0) return false;
11
12 // Look for JSON indicators in first few bytes
13 std::string str(reinterpret_cast<const char*>(data), std::min(length, size_t(20)));
14
15 // Skip whitespace
16 auto first_non_space = str.find_first_not_of(" \t\n\r");
17 if (first_non_space == std::string::npos) return false;
18
19 return str[first_non_space] == '{' || str[first_non_space] == '[';
20}
21
22ParseResult JsonParser::parse_message(const uint8_t* data, size_t length, int client_id) {
23 ParseResult result;
24
25 try {
26 // Accumulate data in buffer
27 message_buffer_.append(reinterpret_cast<const char*>(data), length);
28
29 // Check for complete JSON messages
30 if (!is_complete_json_message(message_buffer_)) {
31 result.is_complete_message = false;
32 return result;
33 }
34
35 // Parse JSON
36 nlohmann::json json_msg = nlohmann::json::parse(message_buffer_);
37 message_buffer_.clear();
38
39 // Determine message type
40 if (json_msg.contains("method") || json_msg.contains("type")) {
41 std::string msg_type;
42 if (json_msg.contains("method")) {
43 msg_type = json_msg["method"];
44 } else if (json_msg.contains("type")) {
45 msg_type = json_msg["type"];
46 }
47
48 // Handle different message types
49 if (msg_type == "newOrder" || msg_type == "ORDER" || msg_type == "order.place") {
50 result.order = parse_new_order_json(json_msg, client_id);
51 result.is_complete_message = true;
52
53 LOG_DEBUG("JSON: Parsed order for client {}: {}",
54 client_id, result.order->client_order_id.view());
55 } else {
56 result.error_message = "Unknown JSON message type: " + msg_type;
57 }
58 } else {
59 // Try to parse as direct order object (some exchanges use this format)
60 if (json_msg.contains(field_mapping_.client_order_id) &&
61 json_msg.contains(field_mapping_.symbol)) {
62 result.order = parse_new_order_json(json_msg, client_id);
63 result.is_complete_message = true;
64
65 LOG_DEBUG("JSON: Parsed direct order for client {}: {}",
66 client_id, result.order->client_order_id.view());
67 } else {
68 result.error_message = "Invalid JSON order format - missing required fields";
69 }
70 }
71
72 } catch (const nlohmann::json::parse_error& e) {
73 result.error_message = "JSON parsing error: " + std::string(e.what());
74 LOG_ERROR("JSON parsing error: {}", e.what());
75 message_buffer_.clear(); // Reset buffer on parse error
76 } catch (const std::exception& e) {
77 result.error_message = "JSON processing error: " + std::string(e.what());
78 LOG_ERROR("JSON processing error: {}", e.what());
79 }
80
81 return result;
82}
83
84Order JsonParser::parse_new_order_json(const nlohmann::json& json_order, int client_id) {
85 Order order;
86 order.client_id = client_id;
87
88 // Extract order data - handle nested structures for different exchanges
89 nlohmann::json order_data = json_order;
90 if (json_order.contains("params")) {
91 order_data = json_order["params"];
92 } else if (json_order.contains("data")) {
93 order_data = json_order["data"];
94 }
95
96 // Required fields
97 order.client_order_id = order_data[field_mapping_.client_order_id].get<std::string>();
98 order.symbol = order_data[field_mapping_.symbol].get<std::string>();
99
100 // Side - handle different formats
101 std::string side_str = order_data[field_mapping_.side].get<std::string>();
102 order.side = parse_side(side_str);
103
104 // Order type
105 std::string type_str = order_data[field_mapping_.type].get<std::string>();
106 order.type = parse_order_type(type_str);
107
108 // Quantity - handle both string and numeric formats
109 if (order_data[field_mapping_.quantity].is_string()) {
110 order.quantity = std::stoull(order_data[field_mapping_.quantity].get<std::string>());
111 } else {
112 order.quantity = order_data[field_mapping_.quantity].get<uint64_t>();
113 }
114 order.leaves_quantity = order.quantity;
115
116 // Price (if present)
117 if (order_data.contains(field_mapping_.price) && !order_data[field_mapping_.price].is_null()) {
118 if (order_data[field_mapping_.price].is_string()) {
119 order.price = to_price_t(std::stod(order_data[field_mapping_.price].get<std::string>()));
120 } else {
121 order.price = to_price_t(order_data[field_mapping_.price].get<double>());
122 }
123 }
124
125 // Time in Force (optional)
126 if (order_data.contains(field_mapping_.time_in_force)) {
127 std::string tif_str = order_data[field_mapping_.time_in_force].get<std::string>();
128 order.time_in_force = parse_time_in_force(tif_str);
129 }
130
131 return order;
132}
133
134std::vector<uint8_t> JsonParser::serialize_response(const OrderResponse& response) {
135 try {
136 nlohmann::json json_response = create_execution_report_json(response);
137 std::string json_str = json_response.dump();
138
139 return std::vector<uint8_t>(json_str.begin(), json_str.end());
140 } catch (const std::exception& e) {
141 LOG_ERROR("JSON serialization error: {}", e.what());
142 return {};
143 }
144}
145
146nlohmann::json JsonParser::create_execution_report_json(const OrderResponse& response) {
147 nlohmann::json json_response;
148
149 // Common crypto exchange execution report format
150 json_response["type"] = "executionReport";
151 json_response["clientOrderId"] = response.client_order_id;
152 json_response["exchId"] = response.order_id;
153 json_response["orderStatus"] = order_status_to_string(response.order_status);
154 json_response["price"] = std::to_string(response.price);
155 json_response["quantity"] = std::to_string(response.qty);
156 json_response["cumQty"] = std::to_string(response.cum_qty);
157 json_response["leavesQty"] = std::to_string(response.leaves_qty);
158 json_response["timestamp"] = response.timestamp;
159
160 if (response.reject_reason != OrdRejectReason::NONE) {
161 json_response["rejectReason"] = response.reject_reason;
162 }
163
164 return json_response;
165}
166
167bool JsonParser::is_complete_json_message(const std::string& buffer) const {
168 if (buffer.empty()) return false;
169
170 int brace_count = 0;
171 int bracket_count = 0;
172 bool in_string = false;
173 bool escape_next = false;
174
175 for (char c : buffer) {
176 if (escape_next) {
177 escape_next = false;
178 continue;
179 }
180
181 if (c == '\\' && in_string) {
182 escape_next = true;
183 continue;
184 }
185
186 if (c == '"') {
187 in_string = !in_string;
188 continue;
189 }
190
191 if (!in_string) {
192 switch (c) {
193 case '{': brace_count++; break;
194 case '}': brace_count--; break;
195 case '[': bracket_count++; break;
196 case ']': bracket_count--; break;
197 }
198 }
199 }
200
201 return brace_count == 0 && bracket_count == 0;
202}
203
205 message_buffer_.clear();
206}
207
208} // namespace slick::sim::order_gateway
ParseResult parse_message(const uint8_t *data, size_t length, int client_id) override
std::vector< uint8_t > serialize_response(const OrderResponse &response) override
bool can_handle(const uint8_t *data, size_t length) const override
static TimeInForce parse_time_in_force(const std::string &tif_str)
static std::string order_status_to_string(OrderStatus status)
static Side parse_side(const std::string &side_str)
static OrderType parse_order_type(const std::string &type_str)
constexpr price_t to_price_t(double price)
Scales a decimal into the fixed-point representation, rounding to the nearest tick rather than trunca...
Definition types.hpp:42
utils::fixed_string< 32 > symbol
Definition order.hpp:289
utils::fixed_string< 37 > client_order_id
Definition order.hpp:291
OrdRejectReason reject_reason
Definition messages.hpp:312
OrderType type
Definition order.hpp:306
TimeInForce time_in_force
Definition order.hpp:308
qty_t leaves_quantity
Definition order.hpp:316