-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOkx_client.cpp
More file actions
409 lines (343 loc) · 14.8 KB
/
Okx_client.cpp
File metadata and controls
409 lines (343 loc) · 14.8 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#include <ctime>
#include "okx_client.h"
#include <openssl/evp.h>
#include <cstring>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <ctime>
#include <openssl/hmac.h>
#include <openssl/buffer.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <curl/curl.h>
#include <iostream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
// Base64 Encoding Function
std::string base64Encode(const unsigned char* data, size_t length) {
BIO* bmem, * b64;
BUF_MEM* bptr;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // Don't add newline characters
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, data, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
std::string encoded(bptr->data, bptr->length);
BIO_free_all(b64);
return encoded;
}
// Write Callback Function
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t totalSize = size * nmemb;
std::string* str = (std::string*)userp;
str->append((char*)contents, totalSize);
return totalSize;
}
OKXClient::OKXClient(const std::string& apiKey, const std::string& secretKey, const std::string& passphrase)
: apiKey(apiKey), secretKey(secretKey), passphrase(passphrase), baseUrl("https://www.okx.com") {}
// Function to get the current timestamp in ISO8601 format
std::string OKXClient::getISO8601Timestamp() {
using namespace std::chrono;
auto now = system_clock::now();
auto now_seconds = system_clock::to_time_t(now);
std::tm tm = {};
gmtime_r(&now_seconds, &tm);
auto now_ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
std::stringstream ss;
ss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%S")
<< '.' << std::setw(3) << std::setfill('0') << now_ms.count()
<< 'Z';
return ss.str();
}
// Function to create HMAC-SHA256 signature
std::string OKXClient::createSignature(const std::string& timestamp, const std::string& method, const std::string& endpoint, const std::string& body) {
std::string data = timestamp + method + endpoint + body;
// DEBUG: Log all parts of the signature data
std::cout << "Signature Data: " << std::endl;
std::cout << "Timestamp: " << timestamp << std::endl;
std::cout << "Method: " << method << std::endl;
std::cout << "Endpoint: " << endpoint << std::endl;
std::cout << "Body: " << body << std::endl;
std::cout << "Data for HMAC: " << data << std::endl;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_len;
HMAC_CTX* ctx = HMAC_CTX_new();
HMAC_Init_ex(ctx, secretKey.c_str(), secretKey.length(), EVP_sha256(), NULL);
HMAC_Update(ctx, reinterpret_cast<const unsigned char*>(data.c_str()), data.length());
HMAC_Final(ctx, digest, &digest_len);
HMAC_CTX_free(ctx);
std::string signature = base64Encode(digest, digest_len);
std::cout << "Generated Signature: " << signature << std::endl; // DEBUG
return signature;
}
// Function to send a request to the OKX API
std::string OKXClient::sendRequest(const std::string& endpoint, const std::string& method, const std::string& body) {
std::string url = baseUrl + endpoint;
CURL* curl;
CURLcode res;
curl = curl_easy_init();
std::string readBuffer;
if (curl) {
std::string timestamp = getISO8601Timestamp();
std::string signature = createSignature(timestamp, method, endpoint, body);
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, ("OK-ACCESS-KEY: " + apiKey).c_str());
headers = curl_slist_append(headers, ("OK-ACCESS-SIGN: " + signature).c_str());
headers = curl_slist_append(headers, ("OK-ACCESS-TIMESTAMP: " + timestamp).c_str());
headers = curl_slist_append(headers, ("OK-ACCESS-PASSPHRASE: " + passphrase).c_str());
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "x-simulated-trading: 1");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
if (method == "POST") {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
}
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
return readBuffer;
}
// Functions for placing, modifying, canceling orders, etc.
void OKXClient::placeOrder(const std::string& symbol, const std::string& side, const std::string& type, double size, double price) {
// Check and adjust price within the allowed range
double maxBuyPrice = 0.4888;
double minSellPrice = 0.4511;
if (side == "buy" && price > maxBuyPrice) {
std::cout << "Price exceeds maximum buy price. Adjusting to " << maxBuyPrice << std::endl;
price = maxBuyPrice;
}
else if (side == "sell" && price < minSellPrice) {
std::cout << "Price is below minimum sell price. Adjusting to " << minSellPrice << std::endl;
price = minSellPrice;
}
// Ensure size is a multiple of the lot size
double lotSize = 1.0; // Replace this with the actual lot size for the instrument
size = std::floor(size / lotSize) * lotSize;
std::string endpoint = "/api/v5/trade/order";
std::string body = R"({"instId":")" + symbol + R"(","tdMode":"cross","side":")" + side + R"(","ordType":")" + type + R"(","sz":")" + std::to_string(size) + R"(","px":")" + std::to_string(price) + R"("})";
std::string response = sendRequest(endpoint, "POST", body);
std::cout << "Place Order Response: " << response << std::endl;
}
/*
void OKXClient::cancelOrder(const std::string& orderId, const std::string& symbol) {
std::string endpoint = "/api/v5/trade/cancel-order";
// Constructing the JSON body for the request
std::string body = R"({"ordId":")" + orderId + R"(","instId":")" + symbol + R"("})";
// Sending the POST request
std::string response = sendRequest(endpoint, "POST", body);
// Printing the response
std::cout << "Cancel Order Response: " << response << std::endl;
}*/
/*void OKXClient::cancelOrder(const std::string& orderId, const std::string& symbol) {
std::string endpoint = "/api/v5/trade/cancel-order";
std::string body = R"({"ordId":")" + orderId + R"(","instId":")" + symbol + R"("})";
try {
std::string response = sendRequest(endpoint, "POST", body);
std::cout << "Response: " << response << std::endl;
// Optionally, parse the response to check if the cancellation was successful
auto jsonResponse = nlohmann::json::parse(response); // Assuming you have a JSON parsing utility
if (jsonResponse["code"] == "0") {
std::cout << "Order canceled successfully: " << jsonResponse["data"] << std::endl;
}
else {
std::cerr << "Failed to cancel order: " << jsonResponse["msg"] << std::endl;
}
}
catch (const std::exception& e) {
std::cerr << "Error canceling order: " << e.what() << std::endl;
}
}
*/
void OKXClient::cancelOrder(const std::string& instId, const std::string& ordId , const std::string& clOrdId) {
std::string endpoint = "/api/v5/trade/cancel-order";
// Constructing the JSON body for the request
std::string body = R"({"instId":")" + instId + R"(")";
// Add either ordId or clOrdId to the body if provided
if (!ordId.empty()) {
body += R"(,"ordId":")" + ordId + R"(")";
}
else if (!clOrdId.empty()) {
body += R"(,"clOrdId":")" + clOrdId + R"(")";
}
body += "}";
// Sending the POST request
std::string response = sendRequest(endpoint, "POST", body);
std::cout << "Response " << response << std::endl;
try {
// Parse the response using nlohmann::json (assuming you have JSON parsing set up)
auto jsonResponse = nlohmann::json::parse(response);
// Check if the request was successful
if (jsonResponse["code"] == "0") {
std::cout << "Order canceled successfully: " << jsonResponse["data"] << std::endl;
}
else {
std::cerr << "Failed to cancel order: " << jsonResponse["msg"] << std::endl;
}
}
catch (const nlohmann::json::exception& e) {
std::cerr << "JSON parsing error: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error canceling order: " << e.what() << std::endl;
}
}
void OKXClient::getOpenOrders(const std::string& instId, const std::string& instType) {
std::string endpoint = "/api/v5/trade/orders-pending";
// Constructing the query parameters
std::string params = "";
if (!instId.empty()) {
params += "?instId=" + instId;
}
if (!instType.empty()) {
if (!params.empty()) {
params += "&";
}
else {
params += "?";
}
params += "instType=" + instType;
}
// Sending the GET request
std::string response = sendRequest(endpoint + params, "GET");
try {
// Parse the response using nlohmann::json
auto jsonResponse = nlohmann::json::parse(response);
// Check if the request was successful
if (jsonResponse["code"] == "0") {
auto openOrders = jsonResponse["data"];
std::cout << "Open Orders:" << std::endl;
// Iterate through open orders and display the relevant information
for (const auto& order : openOrders) {
std::cout << "Order ID: " << order["ordId"] << ", "
<< "Instrument: " << order["instId"] << ", "
<< "Type: " << order["ordType"] << ", "
<< "State: " << order["state"] << ", "
<< "Size: " << order["sz"] << ", "
<< "Price: " << order["px"] << std::endl;
}
}
else {
std::cerr << "Failed to retrieve open orders: " << jsonResponse["msg"] << std::endl;
}
}
catch (const nlohmann::json::exception& e) {
std::cerr << "JSON parsing error: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error retrieving open orders: " << e.what() << std::endl;
}
}
void OKXClient::getOrderHistory(const std::string& symbol, const std::string& instType) {
std::string endpoint = "/api/v5/trade/orders-history";
// Constructing the query parameters
std::string params = "?instId=" + symbol + "&instType=" + instType;
// Sending the GET request
std::string response = sendRequest(endpoint + params, "GET");
try {
// Parse the response using nlohmann::json
auto jsonResponse = nlohmann::json::parse(response);
// Check if the request was successful
if (jsonResponse["code"] == "0") {
auto orders = jsonResponse["data"];
for (const auto& order : orders) {
std::string ordId = order["ordId"];
std::string state = order["state"];
std::string ordType = order["ordType"];
std::string instId = order["instId"];
std::string fillSz = order["fillSz"];
std::string fillPx = order["fillPx"];
// Display the relevant details in a clean manner
std::cout << "Order ID: " << ordId
<< ", Instrument: " << instId
<< ", Type: " << ordType
<< ", State: " << state
<< ", Filled Size: " << fillSz
<< ", Fill Price: " << fillPx
<< std::endl;
}
}
else {
std::cerr << "Failed to get order history: " << jsonResponse["msg"] << std::endl;
}
}
catch (const nlohmann::json::exception& e) {
std::cerr << "JSON parsing error: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error retrieving order history: " << e.what() << std::endl;
}
}
void OKXClient::getPendingOrders(const std::string& ordType, const std::string& instType) {
// Construct the endpoint with query parameters
std::string endpoint = "/api/v5/trade/orders-pending?ordType=" + ordType + "&instType=" + instType;
// Sending the GET request
std::string response = sendRequest(endpoint, "GET");
// Printing the response
std::cout << "Pending Orders Response: " << response << std::endl;
}
/*void OKXClient::modifyOrder(const std::string& orderId, double newSize, double newPrice) {
std::string endpoint = "/api/v5/trade/amend-order";
std::string body = R"({"ordId":")" + orderId + R"(","newSz":")" + std::to_string(newSize) + R"(","newPx":")" + std::to_string(newPrice) + R"("})";
std::string response = sendRequest(endpoint, "POST", body);
std::cout << "Modify Order Response: " << response << std::endl;
}
*/
void OKXClient::modifyOrder(const std::string& ordId, const std::string& instId, const std::string& newSz, const std::string& newPx) {
std::string endpoint = "/api/v5/trade/amend-order";
// Constructing the JSON body for the request
nlohmann::json bodyJson = {
{"ordId", ordId},
{"instId", instId}
};
// Add optional parameters if provided
if (!newSz.empty()) {
bodyJson["newSz"] = newSz;
}
if (!newPx.empty()) {
bodyJson["newPx"] = newPx;
}
// Convert JSON object to string
std::string body = bodyJson.dump();
// Sending the POST request
std::string response = sendRequest(endpoint, "POST", body);
std::cout << "Response." <<response<< std::endl;
try {
// Parse the response using nlohmann::json
auto jsonResponse = nlohmann::json::parse(response);
// Check if the request was successful
if (jsonResponse["code"] == "0") {
std::cout << "Order modified successfully." << std::endl;
std::cout << "Response: " << jsonResponse.dump(4) << std::endl;
}
else {
std::cerr << "Failed to modify order: " << jsonResponse["msg"] << std::endl;
}
}
catch (const nlohmann::json::exception& e) {
std::cerr << "JSON parsing error: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error modifying order: " << e.what() << std::endl;
}
}
std::string OKXClient::getOrderBook(const std::string& symbol) {
std::string endpoint = "/api/v5/market/books?instId=" + symbol;
std::string response = sendRequest(endpoint, "GET");
return response;
}
std::string OKXClient::getCurrentPositions() {
std::string endpoint = "/api/v5/account/positions";
std::string response = sendRequest(endpoint, "GET");
return response;
}