Repository navigation
Expand file tree
/
Copy pathTwelveWSClient.cpp
More file actions
296 lines (276 loc) · 10.7 KB
/
Copy pathTwelveWSClient.cpp
File metadata and controls
296 lines (276 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#include "TwelveWSClient.hpp"
#include "Logger.hpp"
#include <json/json.h>
#include <chrono>
#include <format>
#if defined(__APPLE__)
#include <mach/mach_time.h>
#include <mach/mach.h>
#include <mach/thread_policy.h>
#include <pthread.h>
#endif
#include <memory>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace {
std::string stringifyJson(const Json::Value& value) {
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
return Json::writeString(builder, value);
}
}
TwelveWSClient::TwelveWSClient(const std::string& apiKey)
: mApiKey(apiKey) {
mJsonReaderBuilder["collectComments"] = false;
mJsonReaderBuilder["allowDroppedNullPlaceholders"] = false;
mJsonReader = std::unique_ptr<Json::CharReader>(mJsonReaderBuilder.newCharReader());
}
TwelveWSClient::~TwelveWSClient() {
stop();
}
void TwelveWSClient::addSymbol(std::string_view symbol) {
std::scoped_lock lock(mMtx);
mSymbolQueue.emplace(symbol);
}
void TwelveWSClient::start() {
if (mRunning.exchange(true)) {
Logger::instance().info("[CLIENT] WebSocket client already running");
return;
}
Logger::instance().info("[CLIENT] Starting WebSocket client");
mConnect();
mHeartbeatThread = std::jthread([this](std::stop_token stopToken) {
mHeartbeatLoop(stopToken);
});
}
void TwelveWSClient::stop() {
if (!mRunning.exchange(false)) {
return;
}
Logger::instance().info("[CLIENT] Stopping WebSocket client");
// Unsubscribe from all active symbols before closing
std::vector<std::string> toUnsub;
{
std::scoped_lock lock(mMtx);
for (const auto& sym : mActiveSymbols) {
toUnsub.push_back(sym);
}
mActiveSymbols.clear();
}
if (!toUnsub.empty()) {
std::string symbolList;
for (size_t i = 0; i < toUnsub.size(); ++i) {
symbolList += toUnsub[i];
if (i + 1 < toUnsub.size()) symbolList += ",";
}
Json::Value unsub;
unsub["action"] = "unsubscribe";
unsub["params"]["symbols"] = symbolList;
std::string payload = stringifyJson(unsub);
Logger::instance().info(std::format("[UNSUB] Sending payload: {}", payload));
mWs.send(payload);
}
if (mHeartbeatThread.joinable()) {
mHeartbeatThread.request_stop();
mHeartbeatThread.join();
}
mWs.close();
}
void TwelveWSClient::mConnect() {
const std::string baseUrl = "wss://ws.twelvedata.com/v1/quotes/price";
std::string url;
url.reserve(baseUrl.size() + 9 + mApiKey.size());
url.append(baseUrl);
url.append("?apikey=");
url.append(mApiKey);
Logger::instance().info("[CLIENT] Connecting to " + baseUrl + "?apikey=***");
mWs.setUrl(url);
// Configure message handler
mWs.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) {
if (msg->type == ix::WebSocketMessageType::Open) {
Logger::instance().info("[WS] Connected");
mSubscribeNext();
}
else if (msg->type == ix::WebSocketMessageType::Message) {
mHandleMessage(msg->str);
}
else if (msg->type == ix::WebSocketMessageType::Close) {
Logger::instance().info(std::format("[WS] Closed code={} reason={} remote={}",
msg->closeInfo.code,
msg->closeInfo.reason,
msg->closeInfo.remote));
}
else if (msg->type == ix::WebSocketMessageType::Error) {
Logger::instance().error(std::format(
"[WS] Error message: {} http_status={} retries={} wait_time={} decompressionError={}",
msg->errorInfo.reason,
msg->errorInfo.http_status,
msg->errorInfo.retries,
msg->errorInfo.wait_time,
msg->errorInfo.decompressionError));
}
else if (msg->type == ix::WebSocketMessageType::Ping) {
Logger::instance().info("[WS] Ping received");
}
else if (msg->type == ix::WebSocketMessageType::Pong) {
Logger::instance().info("[WS] Pong received");
}
else {
using Enum = ix::WebSocketMessageType;
const auto typeValue = static_cast<std::underlying_type_t<Enum>>(msg->type);
Logger::instance().info(std::format("[WS] Other message type: {}", typeValue));
}
});
Logger::instance().info("[CLIENT] Starting ix::WebSocket event loop");
mWs.start();
}
void TwelveWSClient::mSubscribeNext() {
struct PendingSubscription {
std::string symbol;
std::string payload;
};
std::vector<std::string> batch;
{
std::unique_lock lock(mMtx);
while (mActiveSymbols.size() < mMaxConcurrent && !mSymbolQueue.empty()) {
std::string sym = std::move(mSymbolQueue.front());
mSymbolQueue.pop();
mActiveSymbols.insert(sym);
batch.push_back(sym);
}
}
if (!batch.empty()) {
std::string symbolList;
for (size_t i = 0; i < batch.size(); ++i) {
symbolList += batch[i];
if (i + 1 < batch.size()) symbolList += ",";
}
Json::Value sub;
sub["action"] = "subscribe";
sub["params"]["symbols"] = symbolList;
std::string payload = stringifyJson(sub);
Logger::instance().info(std::format("[SUB] Sending payload: {}", payload));
mWs.send(payload);
Logger::instance().info(std::format("[SUB] {}", symbolList));
}
}
void TwelveWSClient::mHandleMessage(const std::string& msg) {
// Only log raw message for non-price events (for debugging)
Json::Value data;
std::string errs;
{
std::scoped_lock readerLock(mJsonReaderMutex);
if (!mJsonReader) {
mJsonReader = std::unique_ptr<Json::CharReader>(mJsonReaderBuilder.newCharReader());
}
if (!mJsonReader->parse(msg.data(), msg.data() + msg.size(), &data, &errs)) {
Logger::instance().error("[ERROR] JSON parse failed: " + errs + " | msg=" + msg);
return;
}
}
// Remove all '[WS] Raw message:' logs for price events and legacy code
// Update last message time
mLastMessageTime = std::chrono::steady_clock::now();
// ...existing code...
// Update last message time
mLastMessageTime = std::chrono::steady_clock::now();
try {
Json::Value data;
std::string errs;
{
std::scoped_lock readerLock(mJsonReaderMutex);
if (!mJsonReader) {
mJsonReader = std::unique_ptr<Json::CharReader>(mJsonReaderBuilder.newCharReader());
}
if (!mJsonReader->parse(msg.data(), msg.data() + msg.size(), &data, &errs)) {
Logger::instance().error("[ERROR] JSON parse failed: " + errs + " | msg=" + msg);
return;
}
}
if (data.isMember("event")) {
const std::string event = data["event"].asString();
if (event == "connected") {
Logger::instance().info("[WS] Server acknowledged connection");
}
else if (event == "subscribe-status") {
const Json::Value& success = data["success"];
if (!success.isNull()) {
Logger::instance().info(std::format("[SUB] Success payload: {}", stringifyJson(success)));
}
const Json::Value& fails = data["fails"];
if (const bool hasFails = !fails.isNull() && fails.isArray() && !fails.empty(); hasFails) {
Logger::instance().error(std::format("[SUB] Subscription failures: {}", stringifyJson(fails)));
{
std::scoped_lock lock(mMtx);
for (const auto& entry : fails) {
if (entry.isMember("symbol")) {
mActiveSymbols.erase(entry["symbol"].asString());
}
}
}
// Attempt to fill the subscription window with remaining queued symbols after releasing the lock.
mSubscribeNext();
}
}
else if (event == "error") {
Logger::instance().error("[WS] Error event payload: " + msg);
}
}
// Handle real-time price updates
if (data.isMember("symbol")) {
std::string symbol = data["symbol"].asString();
double price = 0.0;
const Json::Value& priceVal = data["price"];
if (priceVal.isDouble() || priceVal.isIntegral()) {
price = priceVal.asDouble();
}
else if (priceVal.isString()) {
price = std::stod(priceVal.asString());
}
else {
Logger::instance().error("[ERROR] Unexpected price format | msg=" + msg);
return;
}
std::string currency;
if (data.isMember("currency")) {
currency = data["currency"].asString();
} else if (data.isMember("currency_quote")) {
currency = data["currency_quote"].asString();
}
std::ostringstream priceStream;
priceStream << std::fixed << std::setprecision(4) << price;
std::string priceStr = priceStream.str();
if (!currency.empty()) {
Logger::instance().update(std::format("{}: {} {}", symbol, priceStr, currency));
} else {
Logger::instance().update(std::format("{}: {}", symbol, priceStr));
}
// Stay subscribed: do not remove symbol, do not unsubscribe, do not call mSubscribeNext().
// (No action here)
}
}
catch (const std::exception& e) {
Logger::instance().error(std::string{"[ERROR] "} + e.what() + " | msg=" + msg);
}
}
void TwelveWSClient::mHeartbeatLoop(std::stop_token stopToken) {
using clock = std::chrono::steady_clock;
auto nextTick = clock::now() + mHeartbeatInterval;
while (!stopToken.stop_requested() && mRunning.load()) {
std::this_thread::sleep_until(nextTick);
if (stopToken.stop_requested() || !mRunning.load()) {
break;
}
// Only send heartbeat if no message received in last 10 seconds
auto now = clock::now();
auto lastMsg = mLastMessageTime.load();
auto sinceLastMsg = std::chrono::duration_cast<std::chrono::seconds>(now - lastMsg);
if (mWs.getReadyState() == ix::ReadyState::Open && sinceLastMsg >= std::chrono::seconds(10)) {
Logger::instance().info("[HB] Sending heartbeat");
mWs.send(mHeartbeatPayload);
}
nextTick += mHeartbeatInterval;
}
}