-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinance_options.cpp
More file actions
494 lines (443 loc) · 17.9 KB
/
Copy pathbinance_options.cpp
File metadata and controls
494 lines (443 loc) · 17.9 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#include "binance_options.hpp"
#include "black_scholes.hpp"
#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <chrono>
#include <ctime>
#include <thread>
#include <stdexcept>
#include <windows.h>
using json = nlohmann::json;
// -- Timestamps ----------------------------------------------------------------
static long long now_ms_opt() {
FILETIME ft; GetSystemTimeAsFileTime(&ft);
ULARGE_INTEGER u; u.LowPart = ft.dwLowDateTime; u.HighPart = ft.dwHighDateTime;
return static_cast<long long>((u.QuadPart - 116444736000000000ULL) / 10000ULL);
}
// -- libcurl write callback ----------------------------------------------------
static size_t curl_write(void* ptr, size_t size, size_t nmemb, std::string* out) {
out->append(static_cast<char*>(ptr), size * nmemb);
return size * nmemb;
}
BinanceOptionsClient::BinanceOptionsClient(const std::string& underlying)
: underlying_(underlying) {}
// -- HTTP GET ------------------------------------------------------------------
std::string BinanceOptionsClient::http_get(const std::string& url) const {
CURL* curl = curl_easy_init();
std::string buf;
if (!curl) return buf;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT,
"Nimbus/1.0 (github.com/chrislernunes/Nimbus)");
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "[HTTP] curl error: " << curl_easy_strerror(res) << "\n";
buf.clear();
} else {
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if (code != 200) {
std::cerr << "[HTTP] " << url << " -> " << code
<< " body: " << buf << "\n";
buf.clear();
}
}
curl_easy_cleanup(curl);
return buf;
}
// -- Parse symbol "BTC-250530-65000-C" ----------------------------------------
bool BinanceOptionsClient::parse_symbol(const std::string& sym,
std::string& und,
std::string& exp_str,
double& strike,
OptionType& type) const {
std::vector<std::string> parts;
std::string token;
for (char c : sym) {
if (c == '-') { parts.push_back(token); token.clear(); }
else token += c;
}
parts.push_back(token);
if (parts.size() < 4) return false;
und = parts[0];
exp_str = parts[1];
try { strike = std::stod(parts[2]); }
catch (...) { return false; }
type = (parts[3] == "C") ? OptionType::CALL : OptionType::PUT;
return true;
}
// -- "YYMMDD" -> fractional years from now ------------------------------------
double BinanceOptionsClient::expiry_to_years(const std::string& exp_str,
long long now) const {
if (exp_str.size() != 6) return 0.0;
int yy = std::stoi(exp_str.substr(0, 2));
int mm = std::stoi(exp_str.substr(2, 2));
int dd = std::stoi(exp_str.substr(4, 2));
std::tm tm_exp{};
tm_exp.tm_year = 100 + yy;
tm_exp.tm_mon = mm - 1;
tm_exp.tm_mday = dd;
tm_exp.tm_hour = 8; // Binance options expire 08:00 UTC
time_t t_exp = _mkgmtime(&tm_exp);
long long exp_ms = static_cast<long long>(t_exp) * 1000LL;
double diff_ms = static_cast<double>(exp_ms - now);
return std::max(diff_ms / (1000.0 * 3600.0 * 24.0 * 365.0), 1.0 / 365.0);
}
// -- Fetch spot index ----------------------------------------------------------
double BinanceOptionsClient::fetch_spot() const {
std::string url = std::string(BASE_URL)
+ "/eapi/v1/index?underlying=" + underlying_ + "USDT";
std::string resp = http_get(url);
if (resp.empty()) {
// Fallback: Binance spot REST API
url = "https://api.binance.com/api/v3/ticker/price?symbol="
+ underlying_ + "USDT";
resp = http_get(url);
if (resp.empty()) return 0.0;
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded()) return 0.0;
return std::stod(j.value("price", "0"));
}
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded()) return 0.0;
return std::stod(j.value("indexPrice", "0"));
}
// -- Fetch available expiries --------------------------------------------------
std::vector<std::string> BinanceOptionsClient::fetch_expiry_dates() const {
std::string url = std::string(BASE_URL) + "/eapi/v1/exchangeInfo";
std::string resp = http_get(url);
if (resp.empty()) return {};
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded() || !j.contains("optionSymbols")) return {};
std::vector<std::string> dates;
for (const auto& sym : j["optionSymbols"]) {
std::string name = sym.value("symbol", "");
std::string und, exp_str;
double strike;
OptionType type;
if (parse_symbol(name, und, exp_str, strike, type) &&
und == underlying_ &&
std::find(dates.begin(), dates.end(), exp_str) == dates.end())
{
dates.push_back(exp_str);
}
}
std::sort(dates.begin(), dates.end());
return dates;
}
// -- Fetch mark prices for one expiry -----------------------------------------
std::vector<BinanceOptionTicker> BinanceOptionsClient::fetch_expiry(
const std::string& expiry_date) const
{
long long ts = now_ms_opt();
std::string url = std::string(BASE_URL) + "/eapi/v1/mark?underlying="
+ underlying_ + "USDT&expiration=" + expiry_date;
std::string resp = http_get(url);
if (resp.empty()) return {};
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded() || !j.is_array()) return {};
std::vector<BinanceOptionTicker> tickers;
for (const auto& item : j) {
std::string sym = item.value("symbol", "");
std::string und, exp_str;
double strike;
OptionType type;
if (!parse_symbol(sym, und, exp_str, strike, type)) continue;
BinanceOptionTicker t;
t.symbol = sym;
t.underlying = und + "USDT";
t.type = type;
t.strike = strike;
t.expiry_years = expiry_to_years(exp_str, ts);
t.mark_price = std::stod(item.value("markPrice", "0"));
t.mark_iv = std::stod(item.value("markIV", "0"));
t.delta = std::stod(item.value("delta", "0"));
t.gamma = std::stod(item.value("gamma", "0"));
t.vega = std::stod(item.value("vega", "0"));
t.theta = std::stod(item.value("theta", "0"));
t.bid = 0.0;
t.ask = 0.0;
t.open_interest = 0.0;
t.timestamp_ms = ts;
tickers.push_back(t);
}
return tickers;
}
// -- Fetch full chain ----------------------------------------------------------
//
// Endpoints used per poll cycle:
// GET /eapi/v1/index — spot price
// GET /eapi/v1/mark — mark prices + greeks for all contracts
// GET /eapi/v1/ticker — bid/ask for all contracts
//
// NOTE: /eapi/v1/openInterest returns HTTP 400 {"code":-6010,"msg":"open
// interest error data."} for every expiry. OI is therefore not available
// from Binance EAPI at this time. The open_interest field on all tickers
// is set to 0.0, and FilterConfig::min_open_interest must be set to 0.0
// (which is done in demo_live / demo_record_and_replay in main.cpp).
//
OptionsChain BinanceOptionsClient::fetch_chain() const {
long long ts = now_ms_opt();
OptionsChain chain;
chain.underlying = underlying_;
chain.timestamp_ms = ts;
// 1. Spot
chain.spot = fetch_spot();
if (chain.spot <= 0.0) {
std::cerr << "[Chain] Failed to fetch spot for " << underlying_ << "\n";
return chain;
}
// 2. All mark prices + greeks (single request, all expiries)
std::string url = std::string(BASE_URL) + "/eapi/v1/mark?underlying="
+ underlying_ + "USDT";
std::string resp = http_get(url);
if (resp.empty()) {
std::cerr << "[Chain] Empty response from mark endpoint\n";
return chain;
}
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded() || !j.is_array()) {
std::cerr << "[Chain] JSON parse failed\n";
return chain;
}
for (const auto& item : j) {
std::string sym = item.value("symbol", "");
std::string und, exp_str;
double strike;
OptionType type;
if (!parse_symbol(sym, und, exp_str, strike, type)) continue;
if (und != underlying_) continue;
double exp_years = expiry_to_years(exp_str, ts);
if (exp_years <= 0.0) continue;
BinanceOptionTicker t;
t.symbol = sym;
t.underlying = und + "USDT";
t.type = type;
t.strike = strike;
t.expiry_years = exp_years;
t.expiry_ts_ms = ts + static_cast<long long>(exp_years * 365.0 * 86400000.0);
t.mark_price = std::stod(item.value("markPrice", "0"));
t.mark_iv = std::stod(item.value("markIV", "0"));
t.delta = std::stod(item.value("delta", "0"));
t.gamma = std::stod(item.value("gamma", "0"));
t.vega = std::stod(item.value("vega", "0"));
t.theta = std::stod(item.value("theta", "0"));
t.bid = 0.0;
t.ask = 0.0;
t.open_interest = 0.0; // see note above
t.volume_24h = std::stod(item.value("amount", "0"));
t.timestamp_ms = ts;
chain.tickers.push_back(t);
}
// 3. Enrich with bid/ask from /eapi/v1/ticker
std::string tick_url = std::string(BASE_URL) + "/eapi/v1/ticker?underlying="
+ underlying_ + "USDT";
std::string tick_resp = http_get(tick_url);
if (!tick_resp.empty()) {
auto tj = json::parse(tick_resp, nullptr, false);
if (!tj.is_discarded() && tj.is_array()) {
std::map<std::string, std::pair<double,double>> bids_asks;
for (const auto& ti : tj) {
std::string sym = ti.value("symbol", "");
double bid = std::stod(ti.value("bidPrice", "0"));
double ask = std::stod(ti.value("askPrice", "0"));
bids_asks[sym] = {bid, ask};
}
for (auto& t : chain.tickers) {
auto it = bids_asks.find(t.symbol);
if (it != bids_asks.end()) {
t.bid = it->second.first;
t.ask = it->second.second;
}
}
}
}
// 4. Diagnostic summary
{
int with_iv = 0, with_bid = 0;
for (const auto& t : chain.tickers) {
if (t.mark_iv > 0.0) with_iv++;
if (t.bid > 0.0) with_bid++;
}
std::cout << "[Chain] Fetched " << chain.tickers.size()
<< " contracts spot=" << std::fixed << std::setprecision(2)
<< chain.spot
<< " with_iv=" << with_iv
<< " with_bid=" << with_bid
<< " ts=" << ts << "\n";
}
return chain;
}
// -- Convert chain to SurfacePoints -------------------------------------------
std::vector<SurfacePoint> OptionsChain::to_surface_points(
double min_oi, double min_bid, double /*max_spread_iv*/) const
{
std::vector<SurfacePoint> pts;
for (const auto& t : tickers) {
if (t.open_interest < min_oi) continue;
if (t.mark_iv <= 0.0) continue;
if (t.mark_price <= 0.0) continue;
if (t.bid > 0 && t.bid < min_bid) continue;
SurfacePoint p;
p.strike = t.strike;
p.expiry = t.expiry_years;
p.mid_iv = t.mark_iv;
p.bid_iv = t.mark_iv * 0.99;
p.ask_iv = t.mark_iv * 1.01;
pts.push_back(p);
}
return pts;
}
// -- Live polling --------------------------------------------------------------
void BinanceOptionsClient::start_live(ChainCallback cb, int interval_ms) {
running_ = true;
poll_thread_ = std::thread([this, cb, interval_ms]() {
while (running_) {
auto t0 = std::chrono::steady_clock::now();
try {
OptionsChain chain = fetch_chain();
if (!chain.tickers.empty()) cb(chain);
} catch (const std::exception& e) {
std::cerr << "[Live] Exception: " << e.what() << "\n";
}
auto elapsed = std::chrono::steady_clock::now() - t0;
auto sleep_ms = std::chrono::milliseconds(interval_ms) - elapsed;
if (sleep_ms.count() > 0)
std::this_thread::sleep_for(sleep_ms);
}
});
}
void BinanceOptionsClient::stop() {
running_ = false;
if (poll_thread_.joinable()) poll_thread_.join();
}
// -- Record snapshot to CSV ---------------------------------------------------
// CSV schema:
// timestamp_ms, spot, symbol, type, strike, expiry_years,
// mark_iv, bid, ask, delta, gamma, vega, theta, open_interest, volume_24h
void BinanceOptionsClient::record_snapshot(const OptionsChain& chain,
const std::string& filepath) const {
bool write_header = false;
{
std::ifstream f(filepath);
write_header = !f.good();
}
std::ofstream f(filepath, std::ios::app);
if (!f.is_open()) {
std::cerr << "[Record] Cannot open " << filepath << "\n";
return;
}
if (write_header)
f << "timestamp_ms,spot,symbol,type,strike,expiry_years,"
"mark_iv,bid,ask,delta,gamma,vega,theta,open_interest,volume_24h\n";
for (const auto& t : chain.tickers) {
f << chain.timestamp_ms << ","
<< std::fixed << std::setprecision(4) << chain.spot << ","
<< t.symbol << ","
<< (t.type == OptionType::CALL ? "C" : "P") << ","
<< t.strike << ","
<< t.expiry_years << ","
<< t.mark_iv << ","
<< t.bid << ","
<< t.ask << ","
<< t.delta << ","
<< t.gamma << ","
<< t.vega << ","
<< t.theta << ","
<< t.open_interest << ","
<< t.volume_24h << "\n";
}
}
// -- Load snapshots from CSV --------------------------------------------------
std::vector<HistoricalSnapshot> BinanceOptionsClient::load_snapshots(
const std::string& filepath) const
{
std::ifstream f(filepath);
if (!f.is_open()) {
std::cerr << "[Load] Cannot open " << filepath << "\n";
return {};
}
std::map<long long, HistoricalSnapshot> by_ts;
std::string line;
std::getline(f, line); // skip header
while (std::getline(f, line)) {
if (line.empty()) continue;
std::istringstream ss(line);
std::vector<std::string> fields;
std::string field;
while (std::getline(ss, field, ',')) fields.push_back(field);
if (fields.size() < 15) continue;
long long ts = std::stoll(fields[0]);
double spot = std::stod(fields[1]);
OptionType type = (fields[3] == "C") ? OptionType::CALL : OptionType::PUT;
double strike = std::stod(fields[4]);
double exp_yrs = std::stod(fields[5]);
double mark_iv = std::stod(fields[6]);
double bid = std::stod(fields[7]);
double ask_val = std::stod(fields[8]);
double delta = std::stod(fields[9]);
double gamma = std::stod(fields[10]);
double vega_v = std::stod(fields[11]);
double theta = std::stod(fields[12]);
double oi = std::stod(fields[13]);
double vol24 = std::stod(fields[14]);
auto& snap = by_ts[ts];
snap.timestamp_ms = ts;
snap.spot = spot;
snap.chain.spot = spot;
snap.chain.timestamp_ms = ts;
BinanceOptionTicker t;
t.symbol = fields[2];
t.type = type;
t.strike = strike;
t.expiry_years = exp_yrs;
t.mark_iv = mark_iv;
t.bid = bid;
t.ask = ask_val;
t.delta = delta;
t.gamma = gamma;
t.vega = vega_v;
t.theta = theta;
t.open_interest = oi;
t.volume_24h = vol24;
t.timestamp_ms = ts;
snap.chain.tickers.push_back(t);
}
std::vector<HistoricalSnapshot> result;
result.reserve(by_ts.size());
for (auto& [ts, snap] : by_ts) {
snap.surface_pts = snap.chain.to_surface_points(0.0); // OI filter off
result.push_back(std::move(snap));
}
std::cout << "[Load] Loaded " << result.size()
<< " snapshots from " << filepath << "\n";
return result;
}
// -- Replay historical snapshots ----------------------------------------------
void BinanceOptionsClient::replay(const std::vector<HistoricalSnapshot>& snaps,
ChainCallback cb,
double speed_factor) const {
if (snaps.empty()) return;
std::cout << "[Replay] " << snaps.size() << " snapshots"
<< " speed=" << speed_factor << "x\n";
for (size_t i = 0; i < snaps.size(); i++) {
cb(snaps[i].chain);
if (i + 1 < snaps.size() && speed_factor > 0.0) {
long long gap_ms = snaps[i+1].timestamp_ms - snaps[i].timestamp_ms;
long long sleep_ms = static_cast<long long>(
static_cast<double>(gap_ms) / speed_factor);
if (sleep_ms > 0 && sleep_ms < 300000)
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
}
}
std::cout << "[Replay] Complete\n";
}