From 344d180557e48a44b91eca849a769bb9ff9ecbd7 Mon Sep 17 00:00:00 2001 From: Adeel Khan Date: Thu, 6 Mar 2025 05:37:47 +0000 Subject: [PATCH] Diag: Pushing changes prior to 6th March Crash --- .devcontainer/devcontainer.json | 10 +- src/lib/md/GeneralMarketDataListener.cpp | 410 ++++++++--- src/lib/md/protos/co2.proto | 17 + src/server/sparkd/md/MarketDataGateway.cpp | 34 +- src/server/sparkd/md/MarketDataGateway.h | 1 + src/server/sparkd/md/recording/DbWriters.h | 306 +++++++- src/server/sparkd/md/recording/MDRecorder.cpp | 109 ++- src/server/sparkd/md/recording/MDRecorder.h | 1 + .../sparkd/md/taifex/TaifexDataGateway.cpp | 112 ++- .../sparkd/md/taifex/TaifexDataProcessors.h | 67 +- src/server/sparkd/md/taifex/TaifexMessages.h | 310 +++++--- src/server/sparkd/md/taifex/TaifexUtils.h | 89 +++ src/server/sparkd/md/twse/TwseDataGateway.cpp | 666 ++++++++++++++++++ src/server/sparkd/md/twse/TwseDataGateway.h | 27 + .../sparkd/md/twse/TwseDataProcessors.h | 37 + src/server/sparkd/md/twse/TwseMessages.h | 430 +++++++++++ .../md/twse/TwseSecurityDetailsMapper.h | 13 + src/server/sparkd/md/twse/TwseUtils.h | 124 ++++ 18 files changed, 2501 insertions(+), 262 deletions(-) create mode 100644 src/server/sparkd/md/twse/TwseDataGateway.cpp create mode 100644 src/server/sparkd/md/twse/TwseDataGateway.h create mode 100644 src/server/sparkd/md/twse/TwseDataProcessors.h create mode 100644 src/server/sparkd/md/twse/TwseMessages.h create mode 100644 src/server/sparkd/md/twse/TwseSecurityDetailsMapper.h create mode 100644 src/server/sparkd/md/twse/TwseUtils.h diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 1a9d66335..4389f8c87 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -19,15 +19,15 @@ "--shm-size", "2gb", "-p", - "8000:8000", + "9000:8000", "-p", - "8001:8001", + "9001:8001", "-p", - "8002:8002", + "9002:8002", "-p", - "8003:8003", + "9003:8003", "-p", - "12345:12345" + "13345:12345" ], "mounts": [ "source=${localEnv:HOME}/.bts/devcontainer-mounts/${devcontainerId},target=/home/bts,type=bind" diff --git a/src/lib/md/GeneralMarketDataListener.cpp b/src/lib/md/GeneralMarketDataListener.cpp index e9aaea151..0d91a8ecb 100644 --- a/src/lib/md/GeneralMarketDataListener.cpp +++ b/src/lib/md/GeneralMarketDataListener.cpp @@ -46,7 +46,7 @@ #include #include #include - +#include "lib/io/JsonDumper.h" #include #include #include @@ -80,74 +80,99 @@ struct CCSecSearchResult { struct IncrementalBookData { std::map book_map; -bool update_incremental(const IMarketDataListener::BookOp &op) { - //DONT NEED THIS? - // Validate inputs first - if (op.price <= 0.0 || op.quantity < 0) { - LOG(md, Error, "Invalid input - Price: {}, Quantity: {}", op.price, op.quantity); - return false; - } + bool update_incremental(const IMarketDataListener::BookOp &op) { + //DONT NEED THIS? + // Validate inputs first + if (op.price <= 0.0 || op.quantity < 0) { + LOG(md, Error, "Invalid input - Price: {}, Quantity: {}", op.price, + op.quantity); + return false; + } - // Logging setup - //DO WE NEED TO PUT THESE IN A STRING - std::string side_str = (op.side == domain::Side::Buy) ? "Buy" : "Sell"; - std::string op_type_str; - switch (op.op_type) { - case IMarketDataListener::BookOpType::Add: op_type_str = "Add"; break; - case IMarketDataListener::BookOpType::MODIFY: op_type_str = "Modify"; break; - case IMarketDataListener::BookOpType::REMOVE: op_type_str = "Delete"; break; - default: op_type_str = "Unknown"; break; - } - //CAN WE DO THIS WITHOUT ASSIGNING TO STRINGS - std::stringstream op_details; - op_details << "Operation: Price: " << op.price << ", Quantity: " << op.quantity - << ", Side: " << side_str << ", Type: " << op_type_str << "\n"; + // Logging setup + //DO WE NEED TO PUT THESE IN A STRING + std::string side_str = (op.side == domain::Side::Buy) ? "Buy" : "Sell"; + std::string op_type_str; + switch (op.op_type) { + case IMarketDataListener::BookOpType::Add: + op_type_str = "Add"; + break; + case IMarketDataListener::BookOpType::MODIFY: + op_type_str = "Modify"; + break; + case IMarketDataListener::BookOpType::REMOVE: + op_type_str = "Delete"; + break; + default: + op_type_str = "Unknown"; + break; + } + //CAN WE DO THIS WITHOUT ASSIGNING TO STRINGS + std::stringstream op_details; + op_details << "Operation: Price: " << op.price + << ", Quantity: " << op.quantity << ", Side: " << side_str + << ", Type: " << op_type_str << "\n"; - LOG(md, Info, "Book Increment: {}", op_details.str()); + LOG(md, Info, "Book Increment: {}", op_details.str()); - // Get book and validate - auto book = get_book(op.id); - if (book == nullptr) { - LOG(md, Error, "Book not found for id: {}", op.id); - return false; - } + // Get book and validate + auto book = get_book(op.id); + if (book == nullptr) { + LOG(md, Error, "Book not found for id: {}", op.id); + return false; + } - // Get correct side of the book - auto& book_side = (op.side == domain::Side::Buy) ? book->bids() : book->asks(); + // Get correct side of the book + auto &book_side = + (op.side == domain::Side::Buy) ? book->bids() : book->asks(); - // Log initial state - std::stringstream book_before; - book_before << "Book before update (" << side_str << " side):\n"; - for (const auto& level : book_side) { - book_before << "Price: " << level.price << ", Quantity: " << level.total_quantity << "\n"; - } + // Log initial state + std::stringstream book_before; + book_before << "Book before update (" << side_str << " side):\n"; + for (const auto &level : book_side) { + book_before << "Price: " << level.price + << ", Quantity: " << level.total_quantity << "\n"; + } - /*-----------*/ - if(op.side == domain::Side::Buy){ - switch(op.op_type){ - case IMarketDataListener::BookOpType::Add: - { + /*-----------*/ + if (op.side == domain::Side::Buy) { + switch (op.op_type) { + case IMarketDataListener::BookOpType::Add: { int insert_position = 0; - for (size_t i = 0; i < book_side.size(); i++){//not sure how to access book - if(book_side[i].price != 0 && book_side[i].price > op.price ){ + for (size_t i = 0; i < book_side.size(); + i++) { //not sure how to access book + if(book_side[i].price == op.price){ + IMarketDataListener::BookOp new_op; + new_op.id = op.id; + new_op.op_type = IMarketDataListener::BookOpType::MODIFY; + new_op.price = op.price; + new_op.quantity = op.quantity; + new_op.side = op.side; + + return update_incremental(new_op); + + } + if (book_side[i].price != 0 && book_side[i].price > op.price) { //book_side is the book we have ? //op.price is what we received ? insert_position++; continue; - }else {//need j to be last level - for (size_t j =fmin(book_side.size()-1,5-1); j > i; j--){ - book_side[j] = book_side[j-1]; + } else { //need j to be last level + for (size_t j = fmin(book_side.size() - 1, 5 - 1); j > i; + j--) { + book_side[j] = book_side[j - 1]; } break; } } book_side[insert_position].price = op.price; - book_side[insert_position].total_quantity = op.quantity;//dont know how to add quantity + book_side[insert_position].total_quantity = + op.quantity; //dont know how to add quantity break; } - case IMarketDataListener::BookOpType::MODIFY:{ - for(size_t i = 0; i < fmin(book_side.size(),5); i++){ - if(book_side[i].price != 0 && book_side[i].price == op.price){ + case IMarketDataListener::BookOpType::MODIFY: { + for (size_t i = 0; i < fmin(book_side.size(), 5); i++) { + if (book_side[i].price != 0 && book_side[i].price == op.price) { //want to update quantity if price is a match book_side[i].total_quantity = op.quantity; break; @@ -155,103 +180,124 @@ bool update_incremental(const IMarketDataListener::BookOp &op) { } break; } - case IMarketDataListener::BookOpType::REMOVE:{ + case IMarketDataListener::BookOpType::REMOVE: { int found_position = -1; - for (size_t i = 0; i < fmin(book_side.size(),5); i++){ - if(book_side[i].price == op.price){//trying to find based on price only + for (size_t i = 0; i < fmin(book_side.size(), 5); i++) { + if (book_side[i].price == + op.price) { //trying to find based on price only found_position = i; break; } } size_t level = found_position; - //would've had 4 here; want to be at last level - for(size_t i = found_position; i insert_position; i--) { - book_side[i].price = book_side[i - 1].price; - book_side[i].total_quantity = book_side[i - 1].total_quantity; + for (int i = 0; i < fmin(book_side.size(), 5); i++) { + if(book_side[i].price == op.price){ + IMarketDataListener::BookOp new_op; + new_op.id = op.id; + new_op.op_type = IMarketDataListener::BookOpType::MODIFY; + new_op.price = op.price; + new_op.quantity = op.quantity; + new_op.side = op.side; + + return update_incremental(new_op); + + } + if (book_side[i].price != 0 && book_side[i].price < op.price) { + insert_position++; + continue; + } + } //need i to be at the last level + for (int i = fmin(book_side.size() - 1, 5 - 1); i > insert_position; + i--) { + book_side[i].price = book_side[i - 1].price; + book_side[i].total_quantity = book_side[i - 1].total_quantity; } book_side[insert_position].price = op.price; - book_side[insert_position].total_quantity = op.quantity; + book_side[insert_position].total_quantity = op.quantity; break; } - case IMarketDataListener::BookOpType::MODIFY:{ - for (int i = 0; i < fmin(book_side.size(),5); i++) { - if (book_side[i].price != 0 && book_side[i].price == op.price) { - // For modify, we might want to update or keep the same value - book_side[i].price = op.price; - book_side[i].total_quantity = op.quantity; - break; - } - }break; + case IMarketDataListener::BookOpType::MODIFY: { + for (int i = 0; i < fmin(book_side.size(), 5); i++) { + if (book_side[i].price != 0 && book_side[i].price == op.price) { + // For modify, we might want to update or keep the same value + book_side[i].price = op.price; + book_side[i].total_quantity = op.quantity; + break; + } + } + break; } case IMarketDataListener::BookOpType::REMOVE: { int found_position = -1; - for (size_t i = 0; i < fmin(book_side.size(),5); i++){ - if(book_side[i].price == op.price){ + for (size_t i = 0; i < fmin(book_side.size(), 5); i++) { + if (book_side[i].price == op.price) { found_position = i; break; } } - size_t level =found_position; - for (int i = found_position; i < fmin(book_side.size(),5); i++){ - book_side[i].price = book_side[i+1].price; - book_side[i].total_quantity = book_side[i+1].total_quantity; + size_t level = found_position; + for (int i = found_position; i < fmin(book_side.size(), 5); i++) { + book_side[i].price = book_side[i + 1].price; + book_side[i].total_quantity = book_side[i + 1].total_quantity; level++; } - if(found_position != -1){ - book_side[fmin(book_side.size()-1,level)].total_quantity = domain::Quantity(0); + if (found_position != -1) { + book_side[fmin(book_side.size() - 1, level)].total_quantity = + domain::Quantity(0); } break; } default: - LOG(md, Error, "In the Default Case for IMarketDataListener::BookOp {}"); + LOG(md, Error, + "In the Default Case for IMarketDataListener::BookOp {}"); break; + } } + /*---------------------*/ + int counter = 0; + for (auto &level : book_side) { + if (counter > 4) { + level.total_quantity = domain::Quantity(0); + } + counter++; } - /*---------------------*/ - int counter =0; - for(auto &level:book_side){ - if(counter >4){ - level.total_quantity =domain::Quantity(0); + + // Log final state + std::stringstream book_after; + book_after << "Book after update (" << side_str << " side):\n"; + for (const auto &level : book_side) { + book_after << "Price: " << level.price + << ", Quantity: " << level.total_quantity << "\n"; } - counter++; + + std::string book_before_after_op = + book_before.str() + "\n" + book_after.str() + "\n" + op_details.str(); + LOG(md, Diag, "Book Increment desc: {}", book_before_after_op); + bts_assert_msgf( + book->is_sorted(), "book not sorted {}", book_before_after_op); + + return true; } - - // Log final state - std::stringstream book_after; - book_after << "Book after update (" << side_str << " side):\n"; - for (const auto& level : book_side) { - book_after << "Price: " << level.price << ", Quantity: " << level.total_quantity << "\n"; - } - - std::string book_before_after_op = book_before.str() + "\n" + book_after.str() + "\n" + op_details.str(); - LOG(md, Diag, "Book Increment desc: {}", book_before_after_op); - bts_assert_msgf(book->is_sorted(), "book not sorted {}", book_before_after_op); - - return true; -} domain::Book const *get_const_book(domain::SecurityID id) const { auto it = book_map.find(id); if (it == book_map.end()) { @@ -301,8 +347,7 @@ struct GeneralMarketDataListener::PImpl { GeneralSecurityIndex &index, MDProducer &md_producer, std::shared_ptr sim_ex_gwy) - : venue(venue), index(index), - md_producer(md_producer), + : venue(venue), index(index), md_producer(md_producer), sim_ex_gwy(std::move(sim_ex_gwy)) { if (this->sim_ex_gwy != nullptr) { this->sim_ex_gwy->set_producers(&this->index); @@ -464,28 +509,159 @@ void GeneralMarketDataListener::on_book( void GeneralMarketDataListener::on_book_increment( const IMarketDataListener::BookOp &book_op) { - if(!me->inc_book_data.update_incremental(book_op)){ + if (!me->inc_book_data.update_incremental(book_op)) { return; } domain::Book const *book_ptr = me->inc_book_data.get_const_book(book_op.id); bts_assert(book_ptr != nullptr); _on_book(*book_ptr); } +co2::AggressorSide try_fill_agg_side( + const domain::Price &trade_price, + const co2::AggressorSide ¤t_side, + const domain::Book *book, + const domain::SecurityID &id) { + if (current_side != co2::AGGRESSOR_SIDE_NONE) + return current_side; + if (!book) { + LOG(md, Info, + "No book found for sec_id: {}. Processing trade with aggressor " + "side set to NONE.", + id); + return current_side; + } + // Access ask-side and bid-side levels + auto book_ask_side = book->asks(); + auto book_bid_side = book->bids(); + if (book_ask_side.is_populated() && + trade_price >= + book_ask_side[0] + .price) //this means the trade happened on the ask side + { + LOG(md, Info, "Trade Price: {}, Book_Ask[0] Price: {}", trade_price, + book_ask_side[0].price); + return co2::AGGRESSOR_SIDE_BUY; + } + if (book_bid_side.is_populated() && + trade_price <= + book_bid_side[0] + .price) //this means the trade happened on the bid side + { + LOG(md, Info, "Trade Price: {}, Book_Ask[0] Price: {}", trade_price, + book_bid_side[0].price); + return co2::AGGRESSOR_SIDE_SELL; + } + std::string book_str = "Bids: " + bts::io::JsonDumper::dump(book_bid_side, 2) + "\nAsks: " + bts::io::JsonDumper::dump(book_ask_side, 2); + LOG(md, Info, "Could not determine Aggressor, Trade Price: {}, Current Book: {}", trade_price, book_str); + + return co2::AGGRESSOR_SIDE_NONE; +} void GeneralMarketDataListener::on_trades( const std::vector &trades) { for (auto tp : trades) { - auto handle = _find_handle(tp->sec_id); + + std::ostringstream log_stream; + + // Log the important fields from the TradeRecord pointer + log_stream << "TradePointer - sec_id: " << tp->sec_id + << ", agg_side: " << tp->agg_side + << ", trade_price: " << tp->trade_price + << ", trade_quantity: " << tp->trade_quantity.value() + << ", time_stamp: " << tp->time_stamp.millis(); + + // Log the trade data + LOG(md, Info, "logging tp {}", log_stream.str()); + + auto handle = + _find_handle(tp->sec_id); // might be the reason behind missing trades + auto aggressor_side = convert_agg_side(tp->agg_side); + + // Log the initial aggressor_side + LOG(md, Info, "Initial aggressor side for sec_id: {} is: {}", tp->sec_id, + static_cast(aggressor_side)); + + if (handle == nullptr) { + LOG(md, Info, "No handle found for sec_id: {}", tp->sec_id); + continue; + } + aggressor_side = try_fill_agg_side( + tp->trade_price, aggressor_side, + me->inc_book_data.get_const_book(tp->sec_id), tp->sec_id); + auto trade_ts = datetime::ll_from_unix_epoch_ms(tp->time_stamp.millis()); + // Process the trade even if aggressor_side is NONE if (handle != nullptr) { handle->handle.add_trade( utils::TimeStamp::now(), PriceSize( convert_price(tp->trade_price), tp->trade_quantity.value()), - trade_ts, convert_agg_side(tp->agg_side), 0, false); + trade_ts, aggressor_side, 0, false); + LOG(md, Info, "Trade processed for sec_id: {}", tp->sec_id); } } } +// void GeneralMarketDataListener::on_trades( +// const std::vector &trades) { +// for (auto tp : trades) { + +// for (auto tp : trades) { +// std::ostringstream log_stream; + +// // Log the important fields from the TradeRecord pointer +// log_stream << "TradePointer - sec_id: " << tp->sec_id +// << ", agg_side: " << tp->agg_side +// << ", trade_price: " << tp->trade_price +// << ", trade_quantity: " << tp->trade_quantity.value() +// << ", time_stamp: " << tp->time_stamp.millis(); + +// // Log the trade data +// LOG(md, Info, "logging tp {}",log_stream.str());} + +// auto handle = +// _find_handle(tp->sec_id); //might be the reason behind missing trades +// auto aggressor_side = convert_agg_side(tp->agg_side); +// if (aggressor_side == co2::AggressorSide::AGGRESSOR_SIDE_NONE) { +// auto book = me->inc_book_data.get_const_book(tp->sec_id); +// // Check if the book is empty +// if (!book) { +// LOG(md, Info, "book pointer log"); +// LOG(md, Info, "Processing trade with sec_id: {}", tp->sec_id); +// aggressor_side = +// co2::AggressorSide::AGGRESSOR_SIDE_NONE; // Reset aggressor side +// continue; // Skip processing this trade +// }else { +// LOG(md, Info, "Book found for sec_id: {} with size: {}", tp->sec_id, book->size()); +// } + +// // Access ask-side and bid-side levels +// auto book_ask_side = book->asks(); +// auto book_bid_side = book->bids(); +// if (!book_ask_side.is_populated() || !book_bid_side.is_populated()) { +// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_NONE; // Reset +// continue; // Skip processing this trade +// } +// // Determine aggressor side based on trade price +// if (tp->trade_price <= book_ask_side[0].price) { +// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_BUY; +// } else if (tp->trade_price >= book_bid_side[0].price) { +// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_SELL; +// } +// } + +// // // Check if ask and bid sides are populated + +// // } +// auto trade_ts = datetime::ll_from_unix_epoch_ms(tp->time_stamp.millis()); +// if (handle != nullptr) { +// handle->handle.add_trade( +// utils::TimeStamp::now(), +// PriceSize( +// convert_price(tp->trade_price), tp->trade_quantity.value()), +// trade_ts, aggressor_side, 0, false); +// } +// } +// } void GeneralMarketDataListener::on_rfqs( const std::vector &) {} diff --git a/src/lib/md/protos/co2.proto b/src/lib/md/protos/co2.proto index 8aada7d6e..daecf516b 100644 --- a/src/lib/md/protos/co2.proto +++ b/src/lib/md/protos/co2.proto @@ -142,6 +142,21 @@ message TradeMessage { AggressorSide aggressor_side = 9; bool from_spread = 10; } + +enum BboTradeEventType { + BBO_TRADE_UNKNOWN = 0; + //BOOK_UPDATE = 1; + TRADE = 2; +} + +message BboTradeRecord { + BboTradeEventType event_type = 1; + // Book at time of trade + TotalBook book = 2; + // Include trade details only for TRADE events. + TradeMessage trade = 3; +} + message QuoteRequestMessage { enum Side { UNDEFINED = 0; @@ -182,6 +197,7 @@ message TotalBook{ // Message written to the file, for replay message RecordedMDMessage{ uint32 sec_key = 10; + string subset = 11; int64 timestamp = 20; oneof MDRecord { bts.api.Security security = 100; @@ -189,6 +205,7 @@ message RecordedMDMessage{ TradeMessage trade = 300; QuoteRequestMessage rfq = 400; MiscMessage misc = 500; + BboTradeRecord bbo_trade = 600; } } diff --git a/src/server/sparkd/md/MarketDataGateway.cpp b/src/server/sparkd/md/MarketDataGateway.cpp index 2303c7ba8..757083404 100644 --- a/src/server/sparkd/md/MarketDataGateway.cpp +++ b/src/server/sparkd/md/MarketDataGateway.cpp @@ -36,6 +36,7 @@ #include "server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h" #include "server/sparkd/md/recording/MDReplayer.h" #include "server/sparkd/md/taifex/TaifexDataGateway.h" +#include "server/sparkd/md/twse/TwseDataGateway.h" #include #include @@ -139,8 +140,9 @@ void MarketDataGateway::run() { bts_assert(me_->md_config.emumba_deribit().size() == 1); _start_emumba_deribit(me_->md_config.emumba_deribit().at(0)); } - start_glbx(me_->md_config); + start_glbx(me_->md_config); start_taifex(me_->md_config); + start_twse(me_->md_config); start_cboe(me_->md_config); _start_replays(me_->md_config); while (true) { @@ -377,6 +379,36 @@ void MarketDataGateway::_start_replays( os::get_thread_id(), os::get_thread_name()); } +void MarketDataGateway::start_twse(const bts::api::md::MarketDataConfig &cfg) { + // twse +// int counter = 0; +// LOG(md, Info, "In start, mdgtway.cpp"); + +// for (const auto &twse : cfg.twse()) { +// counter++; +// auto p = me_->venue_listeners.emplace_back( +// std::make_shared(bts::api::VENUE_TWSE)); +// std::string tid_name = "twse" + std::to_string(counter); +// bts::threading::make_thread(tid_name, [&]() { +// bts::md::twse::TwseDataGateway::run( +// twse, p->listener, me_->sec_id_store); +// }).detach(); +// } + for (const auto &twse : cfg.twse()) { + auto p = me_->venue_listeners.emplace_back( + std::make_shared(bts::api::VENUE_TWSE)); + // Capture `p->listener` and `me_->sec_id_store` by value + auto listener = p->listener; + auto sec_id_store = me_->sec_id_store; + std::string tid_name = "twse"; + bts::threading::make_thread(tid_name, [listener, sec_id_store, twse]() { + bts::md::twse::TwseDataGateway::run( + twse, listener, sec_id_store); + }).detach(); + + } +} + void MarketDataGateway::start_taifex(const bts::api::md::MarketDataConfig &cfg) { // taifex for (const auto &taifex : cfg.taifex()) { diff --git a/src/server/sparkd/md/MarketDataGateway.h b/src/server/sparkd/md/MarketDataGateway.h index 22a88d1c6..473b063c5 100644 --- a/src/server/sparkd/md/MarketDataGateway.h +++ b/src/server/sparkd/md/MarketDataGateway.h @@ -39,6 +39,7 @@ class MarketDataGateway { void start_glbx(const bts::api::md::MarketDataConfig &cfg); void start_cboe(const bts::api::md::MarketDataConfig &cfg); void start_taifex(const bts::api::md::MarketDataConfig &cfg); + void start_twse(const bts::api::md::MarketDataConfig &cfg); }; } // namespace bts::md diff --git a/src/server/sparkd/md/recording/DbWriters.h b/src/server/sparkd/md/recording/DbWriters.h index 79196aa9d..de28e1325 100644 --- a/src/server/sparkd/md/recording/DbWriters.h +++ b/src/server/sparkd/md/recording/DbWriters.h @@ -26,6 +26,12 @@ class DbWriters { LOG(md, Info, "{}", bts::utils::pb::to_string(rec_msg)); } } + // to check subset values for each record + static void dumpSubsets(const std::vector& data) { + for (const auto &r : data) { + LOG(md, Info, "Record subset: '{}'", r.subset()); + } + } // Writes data to an SQL database static std::unique_ptr open_db( @@ -69,6 +75,12 @@ class DbWriters { db->exec("CREATE TABLE IF NOT EXISTS trades (" "ts TEXT NOT NULL, key INTEGER NOT NULL, price float NOT NULL, " "quantity float NOT NULL, total_volume );"); + db->exec("CREATE TABLE IF NOT EXISTS tbbo (" + "ts TEXT, key INTEGER, price float, " + "quantity float, total_volume float, book_ts TEXT, " + "book_key INTEGER, " + "bid_price_1 float, bid_qty_1 float, ask_price_1 float, " + "ask_qty_1 float);"); return db; } @@ -84,47 +96,242 @@ class DbWriters { } return oss.str(); } + + static void writeToSQL(const std::vector &data) { + LOG(md, Info, "Writting {} entries to sql", data.size()); + + dumpSubsets(data); + + // Open the database. + std::unique_ptr db = open_db(); + + try { + // Group records by the subset field. + std::map> subsets; + for (const auto &r : data) { + std::string subset = r.subset(); // subset field from the proto + if (!subsets.count(subset)) { + subsets[subset] = std::vector(); + } + subsets[subset].push_back(r); + } + + // Begin a transaction for bulk insert. + SQLite::Transaction transaction(*db); + + // Process each group. + for (const auto &pair : subsets) { + const std::string &tableName = pair.first; // dynamic table name from subset + const auto &records = pair.second; + + // First, determine the table schema based on record type and create the table if needed. + std::string createTableQuery; + if (!records.empty() && records.front().has_total_book()) { + createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + "ts TEXT NOT NULL, key INTEGER NOT NULL, " + "bid_price_1 float, bid_qty_1 float, ask_price_1 float, ask_qty_1 float, " + "bid_price_2 float, bid_qty_2 float, ask_price_2 float, ask_qty_2 float, " + "bid_price_3 float, bid_qty_3 float, ask_price_3 float, ask_qty_3 float, " + "bid_price_4 float, bid_qty_4 float, ask_price_4 float, ask_qty_4 float, " + "bid_price_5 float, bid_qty_5 float, ask_price_5 float, ask_qty_5 float, " + "bid_price_6 float, bid_qty_6 float, ask_price_6 float, ask_qty_6 float, " + "bid_price_7 float, bid_qty_7 float, ask_price_7 float, ask_qty_7 float, " + "bid_price_8 float, bid_qty_8 float, ask_price_8 float, ask_qty_8 float, " + "bid_price_9 float, bid_qty_9 float, ask_price_9 float, ask_qty_9 float, " + "bid_price_10 float, bid_qty_10 float, ask_price_10 float, ask_qty_10 float)"; + } else if (!records.empty() && records.front().has_trade()) { + createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + "ts TEXT , key INTEGER , price float , " + "quantity float , total_volume float)"; + } else if (!records.empty() && records.front().has_bbo_trade()) { + createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + "ts TEXT, key INTEGER, price float , " + "quantity float, total_volume float, book_ts TEXT, " + "book_key INTEGER, " + "bid_price_1 float, bid_qty_1 float, ask_price_1 float, ask_qty_1 float)"; + } else { + continue; + } + + // Execute the CREATE TABLE query. + { + SQLite::Statement createStmt(*db, createTableQuery); + createStmt.exec(); + } + + // Now build the INSERT query. + std::string insertQuery; + if (!records.empty() && records.front().has_total_book()) { + insertQuery = "INSERT OR REPLACE INTO " + tableName + + " (ts, key, bid_price_1, bid_qty_1, ask_price_1, ask_qty_1, " + "bid_price_2, bid_qty_2, ask_price_2, ask_qty_2, " + "bid_price_3, bid_qty_3, ask_price_3, ask_qty_3, " + "bid_price_4, bid_qty_4, ask_price_4, ask_qty_4, " + "bid_price_5, bid_qty_5, ask_price_5, ask_qty_5, " + "bid_price_6, bid_qty_6, ask_price_6, ask_qty_6, " + "bid_price_7, bid_qty_7, ask_price_7, ask_qty_7, " + "bid_price_8, bid_qty_8, ask_price_8, ask_qty_8, " + "bid_price_9, bid_qty_9, ask_price_9, ask_qty_9, " + "bid_price_10, bid_qty_10, ask_price_10, ask_qty_10)"; + } else if (!records.empty() && records.front().has_trade()) { + insertQuery = "INSERT OR REPLACE INTO " + tableName + + " (ts, key, price, quantity, total_volume)"; + } else if (!records.empty() && records.front().has_bbo_trade()) { + insertQuery = "INSERT OR REPLACE INTO " + tableName + + " (ts, key, price, quantity, total_volume, book_ts, book_key, " + "bid_price_1, bid_qty_1, ask_price_1, ask_qty_1)"; + } + + // Build value tuples. + std::vector valueStrings; + for (const auto &entry : records) { + std::string tuple; + if (entry.has_total_book()) { + auto book = entry.total_book(); + tuple = "(" + std::to_string(entry.timestamp()) + ", " + + std::to_string(entry.sec_key()); + const auto &asks = book.direct_book().asks(); + const auto &bids = book.direct_book().bids(); + for (int i = 0; i < 10; ++i) { + // Process asks. + if (i < asks.size()) { + IntPrice p(asks.at(i).mantissa(), asks.at(i).exponent()); + tuple += ", " + std::to_string(p.price()) + ", " + + std::to_string(asks.at(i).size()); + } else { + tuple += ", NULL, NULL"; + } + // Process bids. + if (i < bids.size()) { + IntPrice p(bids.at(i).mantissa(), bids.at(i).exponent()); + tuple += ", " + std::to_string(p.price()) + ", " + + std::to_string(bids.at(i).size()); + } else { + tuple += ", NULL, NULL"; + } + } + tuple += ")"; + } else if (entry.has_trade()) { + const auto &trade = entry.trade(); + IntPrice p(trade.mantissa(), trade.exponent()); + tuple = "(" + std::to_string(entry.timestamp()) + ", " + + std::to_string(entry.sec_key()) + ", " + + std::to_string(p.price()) + ", " + + std::to_string(trade.size()) + ", " + + std::to_string(trade.total_volume()) + ")"; + } else if (entry.has_bbo_trade()) { + const auto &bbo_trade = entry.bbo_trade(); + const auto &trade = bbo_trade.trade(); + IntPrice p(trade.mantissa(), trade.exponent()); + + tuple = "(" + + std::to_string(trade.time()) + ", " + + std::to_string(trade.key()) + ", " + + std::to_string(p.price()) + ", " + + std::to_string(trade.size()) + ", " + + std::to_string(trade.total_volume()) + ", " + + std::to_string(entry.timestamp()) + ", " + + std::to_string(entry.sec_key()); + + const auto &asks = bbo_trade.book().direct_book().asks(); + const auto &bids = bbo_trade.book().direct_book().bids(); + + // Process top ask (level 1) + if (!asks.empty()) { + IntPrice askPrice(asks[0].mantissa(), asks[0].exponent()); + tuple += ", " + std::to_string(askPrice.price()) + ", " + + std::to_string(asks[0].size()); + } else { + tuple += ", NULL, NULL"; + } + + // Process top bid (level 1) + if (!bids.empty()) { + IntPrice bidPrice(bids[0].mantissa(), bids[0].exponent()); + tuple += ", " + std::to_string(bidPrice.price()) + ", " + + std::to_string(bids[0].size()); + } else { + tuple += ", NULL, NULL"; + } + + tuple += ")"; + } + + valueStrings.push_back(tuple); + } + std::string fullQuery = insertQuery + " VALUES " + join(valueStrings, ", ") + ";"; + + // Replace any occurrence of "nan" with "NULL". + auto replaceNanWithNull = [](std::string &input) { + const std::string target = "nan"; + const std::string replacement = "NULL"; + size_t pos = 0; + while ((pos = input.find(target, pos)) != std::string::npos) { + input.replace(pos, target.length(), replacement); + pos += replacement.length(); + } + }; + replaceNanWithNull(fullQuery); + LOG(md, Diag, "EXECUTING QUERY '{}'", fullQuery); + SQLite::Statement q(*db, fullQuery); + q.exec(); + } + transaction.commit(); + } catch (const SQLite::Exception &e) { + LOG(md, Warn, "Error writing to books db (retry pending): {}", + std::string(e.what())); + } + } + + + /*old writeToSQL static void writeToSQL(const std::vector &data) { LOG(md, Info, "Writting {} entries to sql", data.size()); std::unique_ptr db = open_db(); try { auto db = open_db(); - std::string insert_book = "INSERT OR REPLACE INTO books (ts, key, " - "bid_price_1, bid_qty_1, ask_price_1, ask_qty_1, " - "bid_price_2, bid_qty_2, ask_price_2, ask_qty_2, " - "bid_price_3, bid_qty_3, ask_price_3, ask_qty_3, " - "bid_price_4, bid_qty_4, ask_price_4, ask_qty_4, " - "bid_price_5, bid_qty_5, ask_price_5, ask_qty_5, " - "bid_price_6, bid_qty_6, ask_price_6, ask_qty_6, " - "bid_price_7, bid_qty_7, ask_price_7, ask_qty_7, " - "bid_price_8, bid_qty_8, ask_price_8, ask_qty_8, " - "bid_price_9, bid_qty_9, ask_price_9, ask_qty_9, " - "bid_price_10, bid_qty_10, ask_price_10, ask_qty_10)"; - std::string insert_trade= "INSERT OR REPLACE INTO trades (ts, key, price, quantity, total_volume)"; + std::string insert_book = + "INSERT OR REPLACE INTO books (ts, key, " + "bid_price_1, bid_qty_1, ask_price_1, ask_qty_1, " + "bid_price_2, bid_qty_2, ask_price_2, ask_qty_2, " + "bid_price_3, bid_qty_3, ask_price_3, ask_qty_3, " + "bid_price_4, bid_qty_4, ask_price_4, ask_qty_4, " + "bid_price_5, bid_qty_5, ask_price_5, ask_qty_5, " + "bid_price_6, bid_qty_6, ask_price_6, ask_qty_6, " + "bid_price_7, bid_qty_7, ask_price_7, ask_qty_7, " + "bid_price_8, bid_qty_8, ask_price_8, ask_qty_8, " + "bid_price_9, bid_qty_9, ask_price_9, ask_qty_9, " + "bid_price_10, bid_qty_10, ask_price_10, ask_qty_10)"; + std::string insert_trade = "INSERT OR REPLACE INTO trades (ts, key, " + "price, quantity, total_volume)"; + std::string insert_tbbo = "INSERT OR REPLACE INTO tbbo (ts, key, " + "price, quantity, total_volume, " + "book_ts, book_key, bid_price_1, bid_qty_1, " + "ask_price_1, ask_qty_1)"; SQLite::Transaction transaction(*db); - auto replaceNanWithNull = [](std::string& input) { - const std::string target = "nan"; - const std::string replacement = "NULL"; - size_t pos = 0; + auto replaceNanWithNull = [](std::string &input) { + const std::string target = "nan"; + const std::string replacement = "NULL"; + size_t pos = 0; - while ((pos = input.find(target, pos)) != std::string::npos) { - input.replace(pos, target.length(), replacement); - pos += replacement.length(); // Move past the replacement - } - }; + while ((pos = input.find(target, pos)) != std::string::npos) { + input.replace(pos, target.length(), replacement); + pos += replacement.length(); // Move past the replacement + } + }; // Collect data for bulk insert std::vector book_values; std::vector trade_values; + std::vector tbbo_values; for (const auto &entry : data) { if (entry.has_total_book()) { auto book = entry.total_book(); std::string &book_value = book_values.emplace_back(); - book_value = "(" + - std::to_string(entry.timestamp()) + - ", " + std::to_string(entry.sec_key()); + book_value = "(" + std::to_string(entry.timestamp()) + ", " + + std::to_string(entry.sec_key()); const auto &asks = book.direct_book().asks(); const auto &bids = book.direct_book().bids(); @@ -146,7 +353,7 @@ class DbWriters { book_value += ", NULL, NULL"; } } - book_value +=")"; + book_value += ")"; } if (entry.has_trade()) { const auto &trade = entry.trade(); @@ -158,11 +365,44 @@ class DbWriters { std::to_string(trade.size()) + ", " + std::to_string(trade.total_volume()) + ")"); } + if (entry.has_bbo_trade()) { + const auto &bbo_trade = entry.bbo_trade(); + IntPrice p(bbo_trade.trade().mantissa(), bbo_trade.trade().exponent()); + std::string tbbo_value = + "(" + std::to_string(entry.timestamp()) + ", " + + std::to_string(entry.sec_key()) + ", " + + std::to_string(p.price()) +", " + + std::to_string(bbo_trade.trade().size()) + ", " + + std::to_string(bbo_trade.trade().total_volume()); + + const auto &asks = bbo_trade.book().direct_book().asks(); + const auto &bids = bbo_trade.book().direct_book().bids(); + + if (!asks.empty()) { + IntPrice askPrice(asks.begin()->mantissa(), asks.begin()->exponent()); + tbbo_value += ", " + std::to_string(askPrice.price()) + ", " + + std::to_string(asks.size()); + } else { + tbbo_value += ", NULL, NULL"; + } + + if (!bids.empty()) { + IntPrice bidPrice( + bids.begin()->mantissa(), bids.begin()->exponent()); + tbbo_value += ", " + std::to_string(bidPrice.price()) + ", " + + std::to_string(bids.size()); + } else { + tbbo_value += ", NULL, NULL"; + } + + tbbo_value += ")"; + tbbo_values.push_back(tbbo_value); + } } // Construct the full bulk insert query for books if (!book_values.empty()) { std::string book_query = - insert_book + " VALUES "+ join(book_values, ", ")+";"; + insert_book + " VALUES " + join(book_values, ", ") + ";"; replaceNanWithNull(book_query); LOG(md, Diag, "EXECUTING QUERY '{}'", book_query); SQLite::Statement q(*db, book_query); @@ -172,7 +412,7 @@ class DbWriters { // Construct the full bulk insert query for trades if (!trade_values.empty()) { std::string trade_query = - insert_trade + " VALUES "+ join(trade_values, ", ")+";"; + insert_trade + " VALUES " + join(trade_values, ", ") + ";"; replaceNanWithNull(trade_query); LOG(md, Diag, "EXECUTING QUERY '{}'", trade_query); SQLite::Statement q(*db, trade_query); @@ -180,13 +420,23 @@ class DbWriters { ; } + if (!tbbo_values.empty()) { + std::string tbbo_query = + insert_tbbo + " VALUES " + join(tbbo_values, ", ") + ";"; + replaceNanWithNull(tbbo_query); + LOG(md, Diag, "EXECUTING QUERY '{}'", tbbo_query); + SQLite::Statement q(*db, tbbo_query); + q.exec(); + ; + } + transaction.commit(); } catch (const SQLite::Exception &e) { LOG(md, Warn, "Error writing to books db (retry pending): {}", std::string(e.what())); } } - +*/ // Writes data to a file static void writeProtoToFile( const std::vector &data, diff --git a/src/server/sparkd/md/recording/MDRecorder.cpp b/src/server/sparkd/md/recording/MDRecorder.cpp index 46afc97c7..1dbb6a5ba 100644 --- a/src/server/sparkd/md/recording/MDRecorder.cpp +++ b/src/server/sparkd/md/recording/MDRecorder.cpp @@ -30,6 +30,7 @@ #include #include #include +#include namespace bts::md::recording { @@ -98,11 +99,13 @@ void copy_misc(IntPrice settlement, MiscData &misc, co2::MiscMessage *pmisc) { // each security is represented here struct MDRecordingSecEntry { SecurityKey key; + std::string subset_string; // New: computed base subset (e.g. "taifex_future_tx") MDConsumerHandle handle; TimeStamp direct_book_ts = {}; TimeStamp implied_book_ts = {}; TimeStamp trade_ts = {}; TimeStamp misc_ts = {}; + co2::TotalBook last_total_book; MDRecordingSecEntry(SecurityKey key, MDConsumerHandle handle) : key(key), handle(handle) {} }; @@ -198,6 +201,7 @@ void MDRecorder::_poll_md() { MDRecordingSecEntry &md_entry = kv.second; if (me->settings.n_book_levels > 0) _poll_books(md_entry); + _poll_bbotrade(md_entry); // Added this to poll tbbo _poll_trades(md_entry); _poll_misc(md_entry); } @@ -221,6 +225,37 @@ void MDRecorder::_poll_md() { bts::api::Venue_Name(me->venue)); } +std::string computeBaseSubsetString(const bts::api::Security &sec) { + std::string exchange_str = bts::api::Venue_Name(sec.exchange()); + + std::string instrument_type; + if (sec.has_future()) { + instrument_type = "future"; + } else if (sec.has_option()) { + instrument_type = "option"; + } else if (sec.has_spot()) { + instrument_type = "spot"; + } else if (sec.has_spread()) { + instrument_type = "spread"; + } else if (sec.has_synthetic()) { + instrument_type = "synthetic"; + } else { + instrument_type = "unset"; + } + //might need to add toLowerCase for exact match to sheet requirement + std::string symbol = sec.symbol(); + + + // Convert instrument_type and symbol to lowercase + std::transform(exchange_str.begin(), exchange_str.end(), exchange_str.begin(), ::tolower); + std::transform(instrument_type.begin(), instrument_type.end(), instrument_type.begin(), ::tolower); + std::transform(symbol.begin(), symbol.end(), symbol.begin(), ::tolower); + + + // This base string does not include the event prefix (like "book", "tradebbo", etc.) + return exchange_str + "_" + instrument_type + "_" + symbol; +} + void MDRecorder::_scan_securities() { auto secs = me->md_client.current_consumer().get_securities(); uint32_t n_secs_added = 0; @@ -233,14 +268,26 @@ void MDRecorder::_scan_securities() { LOG(md, Info, "MDRecorder::_scan_securities adding sec: {}, n_secs: {}", key, me->handles.size()); - me->handles.emplace( + + // Compute the base subset string from the security details. + std::string baseSubset = computeBaseSubsetString(*s); + // Create a new MDRecordingSecEntry and assign the computed subset_string. + MDRecordingSecEntry entry(key, me->md_client.current_consumer().get_handle(key.value())); + entry.subset_string = baseSubset; + // Insert the entry with the computed subset_string. + me->handles.emplace(key, std::move(entry)); + + /*me->handles.emplace( key, MDRecordingSecEntry( key, me->md_client.current_consumer().get_handle( - key.value()))); + key.value())));*/ bts::co2::RecordedMDMessage rec_msg; rec_msg.set_sec_key(key.value()); rec_msg.set_timestamp(bts::core::TimeStamp::now_ns()); rec_msg.mutable_security()->CopyFrom(*s); + + rec_msg.set_subset(baseSubset); + _write_pb_to_file(rec_msg); n_secs_added++; } @@ -288,6 +335,10 @@ void MDRecorder::_poll_books(MDRecordingSecEntry &md_entry) { if (md_change) { co2::RecordedMDMessage rec_msg; rec_msg.set_sec_key(md_entry.key.value()); + //for tbbo consistency + std::string eventSubset = "book_" + md_entry.subset_string; + rec_msg.set_subset(eventSubset); + //-------- rec_msg.set_timestamp(bts::core::TimeStamp::now_ns()); rec_msg.mutable_total_book()->CopyFrom(book); _write_pb_to_file(rec_msg); @@ -315,13 +366,65 @@ void MDRecorder::_poll_trades(MDRecordingSecEntry &md_entry) { // aggressor? co2::RecordedMDMessage rec_msg; rec_msg.set_sec_key(md_entry.key.value()); + //for tbbo consistency + std::string eventSubset = "trade_" + md_entry.subset_string; + rec_msg.set_subset(eventSubset); + //----- rec_msg.set_timestamp(bts::core::TimeStamp::now_ns()); rec_msg.mutable_trade()->CopyFrom(tm); _write_pb_to_file(rec_msg); _write_pb_to_db(rec_msg); } } +void MDRecorder::_poll_bbotrade(MDRecordingSecEntry &md_entry) { + // === Always Update Book Snapshot === + TimeStamp book_ts; + co2::TotalBook book; + me->reusables.clean_books(); + md_entry.handle.get_direct_book(book_ts, me->settings.n_book_levels, + me->reusables.bids, me->reusables.asks); + + // Update book snapshot even if timestamp hasn't changed (for TBBO accuracy) + co2::BookMessage *direct_book = book.mutable_direct_book(); + copy_book(me->reusables.bids, true, me->settings.n_book_levels, *direct_book); + copy_book(me->reusables.asks, false, me->settings.n_book_levels, *direct_book); + md_entry.last_total_book.CopyFrom(book); // Always update + md_entry.direct_book_ts = book_ts; // Track timestamp + // === Trade Handling === + TimeStamp trade_ts; + PriceSize t_ps; + datetime::LLDateTime trade_time; + size_t total_volume; + int from_spread; + md_entry.handle.get_last_trade(trade_ts, t_ps, trade_time, &total_volume, &from_spread); + + if (trade_ts > md_entry.trade_ts) { + md_entry.trade_ts = trade_ts; + + co2::RecordedMDMessage rec_msg; + rec_msg.set_sec_key(md_entry.key.value()); + rec_msg.set_timestamp(trade_time); + rec_msg.set_subset("tradebbo_" + md_entry.subset_string); + auto* bboTrade = rec_msg.mutable_bbo_trade(); + bboTrade->set_event_type(co2::TRADE); + + // Directly populate the trade (no need for TradeMessage intermediary) + auto* trade = bboTrade->mutable_trade(); + trade->set_key(md_entry.key.value()); + trade->set_time(trade_time); + trade->set_mantissa(t_ps.mantissa()); + trade->set_exponent(t_ps.exponent()); + trade->set_size(t_ps.direct_size()); + trade->set_total_volume(total_volume); + + // Attach the freshly updated book snapshot + bboTrade->mutable_book()->CopyFrom(md_entry.last_total_book); + + _write_pb_to_file(rec_msg); + _write_pb_to_db(rec_msg); + } +} void MDRecorder::_poll_misc(MDRecordingSecEntry &md_entry) { auto misc_data = md_entry.handle.misc(); if (misc_data.misc_timestamp > md_entry.misc_ts) { @@ -388,4 +491,4 @@ bool MDRecorder::is_md_recording_file( file_name.find(search_txt) != std::string::npos; } -} // namespace bts::md::recording +} // namespace bts::md::recording \ No newline at end of file diff --git a/src/server/sparkd/md/recording/MDRecorder.h b/src/server/sparkd/md/recording/MDRecorder.h index 2455c9f46..d4444a0a1 100644 --- a/src/server/sparkd/md/recording/MDRecorder.h +++ b/src/server/sparkd/md/recording/MDRecorder.h @@ -30,6 +30,7 @@ class MDRecorder { void _scan_securities(); void _poll_books(MDRecordingSecEntry &md_entry); void _poll_trades(MDRecordingSecEntry &md_entry); + void _poll_bbotrade(MDRecordingSecEntry &md_entry); void _poll_misc(MDRecordingSecEntry &md_entry); void _write_pb_to_file(const bts::co2::RecordedMDMessage &rec_msg); void _write_pb_to_db(const bts::co2::RecordedMDMessage &rec_msg); diff --git a/src/server/sparkd/md/taifex/TaifexDataGateway.cpp b/src/server/sparkd/md/taifex/TaifexDataGateway.cpp index 27509e456..2af659555 100644 --- a/src/server/sparkd/md/taifex/TaifexDataGateway.cpp +++ b/src/server/sparkd/md/taifex/TaifexDataGateway.cpp @@ -21,6 +21,13 @@ #include #include #include +#include +#include // For opendir, readdir, closedir +#include +#include +#include +#include +#include // For logging namespace bts::md::taifex { enum class LIVE_DATA_STATES { @@ -287,13 +294,15 @@ bool LoadReferenceFromFile( std::visit( overloaded{ [&](const TaifexMessages::I010Data &i010) { - if (!I010_seen.contains(i010.prod_id) && TaifexUtils::sec_filter(i010.prod_id)) { + if (!I010_seen.contains(i010.prod_id) && + TaifexUtils::sec_filter(i010.prod_id)) { seen = false; I010_seen.insert(i010.prod_id); } }, [&](const TaifexMessages::I011Data &i011) { - if (!I011_seen.contains(i011.kind_id)&& TaifexUtils::sec_filter(i011.kind_id)) { + if (!I011_seen.contains(i011.kind_id) && + TaifexUtils::sec_filter(i011.kind_id)) { seen = false; I011_seen.insert(i011.kind_id); } @@ -388,13 +397,15 @@ void HandleReferenceFeed( std::visit( overloaded{ [&](const TaifexMessages::I010Data &i010) { - if (!I010_seen.contains(i010.prod_id) && TaifexUtils::sec_filter(i010.prod_id)) { + if (!I010_seen.contains(i010.prod_id) && + TaifexUtils::sec_filter(i010.prod_id)) { seen = false; I010_seen.insert(i010.prod_id); } }, [&](const TaifexMessages::I011Data &i011) { - if (!I011_seen.contains(i011.kind_id)&& TaifexUtils::sec_filter(i011.kind_id)) { + if (!I011_seen.contains(i011.kind_id) && + TaifexUtils::sec_filter(i011.kind_id)) { seen = false; I011_seen.insert(i011.kind_id); } @@ -575,7 +586,7 @@ void runLive( live_buffered_messages.clear(); TaifexUtils::close_sockets(sockets); last_seq_num = 0; - bts_assert(reset_counter < 5); + bts_assert(reset_counter < 50); state = LIVE_DATA_STATES::WAITING_FOR_REFRESH_DATA; break; @@ -647,6 +658,8 @@ void runLive( state = LIVE_DATA_STATES::REFRESH_DATA_DONE; break; } + + /* case LIVE_DATA_STATES::REFRESH_DATA_DONE: { LOG(md, Info, "State: REFRESH_DATA_DONE snapshot_buffered_messages size{}", @@ -713,6 +726,91 @@ void runLive( // stop reference data // apply all refresh data } + */ + case LIVE_DATA_STATES::REFRESH_DATA_DONE: { + LOG(md, Info, + "State: REFRESH_DATA_DONE snapshot_buffered_messages size{}", + snapshot_buffered_messages.unsafe_size()); + bts_assert(stop_refresh_thread); + + int max_iterations = 100; // Arbitrary limit + int iteration_count = 0; + + while ((!snapshot_buffered_messages.empty() || + !products_waiting.empty()) && + iteration_count < max_iterations) { + iteration_count++; + SNAPSHOT_BUFFER_MSG msg; + if (!snapshot_buffered_messages.try_pop(msg)) { + continue; + } + LOG(md, Info, + "State: REFRESH_DATA_DONE Waiting for Reference data products " + "waiting:{}, buffer_size:{} \n waiting: {}\n sec_deets: {}", + products_waiting.size(), + snapshot_buffered_messages.unsafe_size(), + print(products_waiting), security_details->to_string()); + + std::visit( + overloaded{ + [&](const REFERENCE_MSG &ref_msg) { + handleReferenceDataParsedMessage( + ref_msg, listener, sec_id_store, security_details); + + std::visit( + overloaded{ + [&](const TaifexMessages::I010Data &data) { + if (products_waiting.contains( + TaifexUtils::remove_spaces( + data.prod_id))) { + auto m = products_waiting.at( + TaifexUtils::remove_spaces( + data.prod_id)); + SNAPSHOT_BUFFER_MSG mes = + std::make_shared>(m); + snapshot_buffered_messages.push(mes); + products_waiting.erase(data.prod_id); + } + }, + [&](const TaifexMessages::I011Data) { + return; // Exit early for I011Data + }}, + ref_msg); + return; + }, + [&](const REFRESH_MSG &refresh_msg) { + if (!TaifexDataProcessors::processBookSnapShotMessage( + refresh_msg, listener, security_details)) { + products_waiting.insert_or_assign( + TaifexUtils::remove_spaces(refresh_msg.prod_id), + refresh_msg); + } + return; + }}, + *msg); + } + + if (iteration_count >= max_iterations) { + LOG(md, Info, + "Exceeded maximum iterations in REFRESH_DATA_DONE. Either " + "snapshot_buffered_messages or " + "products waiting are not empty."); + // Handle unresolved data or cleanup if necessary + if (!products_waiting.empty()) { + LOG(md, Info, "Unresolved products: {}", + print(products_waiting)); + } + if (!snapshot_buffered_messages.empty()) { + LOG(md, Info, "Unprocessed buffered messages: {}", + snapshot_buffered_messages.unsafe_size()); + } + } + + stop_reference_thread = true; + state = LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE; + break; + } case LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE: { LOG(md, Info, "State: WAITING_TO_SYNC_LIVE"); @@ -793,6 +891,8 @@ void runLive( }; } } + + //const std::string &filename, void bts::md::taifex::TaifexDataGateway::run( const api::md::TaifexMarketDataConfig &config, @@ -811,7 +911,7 @@ void bts::md::taifex::TaifexDataGateway::run( config::get().data_path(); runOnBinaryFile( base_path + reference_file_name, listner, sec_id_store, sec_details, - REFERENCE); + REFERENCE); runOnBinaryFile( base_path + realtime_file_name, listner, sec_id_store, sec_details, LIVE); diff --git a/src/server/sparkd/md/taifex/TaifexDataProcessors.h b/src/server/sparkd/md/taifex/TaifexDataProcessors.h index 106b8aafa..24e9757dd 100644 --- a/src/server/sparkd/md/taifex/TaifexDataProcessors.h +++ b/src/server/sparkd/md/taifex/TaifexDataProcessors.h @@ -1,7 +1,10 @@ #pragma once #include "TaifexMessages.h" #include "TaifexSecurityDetailsMapper.h" +#include "lib/config/config.h" +#include "lib/config/protos/taifex_reference_data.pb.h" #include "lib/core/TimeStamp.h" +#include "lib/domain/AggressorSide.h" #include "lib/domain/Security.h" #include "lib/domain/TradeRecord.h" #include "lib/logging/logging.h" @@ -9,8 +12,6 @@ #include "lib/persistence/IDGenerator.h" #include "lib/utils/bts_assert.h" #include -#include "lib/config/protos/taifex_reference_data.pb.h" -#include "lib/config/config.h" namespace bts::md::taifex { class TaifexDataProcessors { @@ -72,7 +73,7 @@ class TaifexDataProcessors { listener->on_book(book); return true; } - + static void processBookIncrements( const TaifexMessages::I081Data &msg, const std::shared_ptr &listener, @@ -85,7 +86,7 @@ class TaifexDataProcessors { LOG(md,Error,"sec_id or dec_loc not found for: {}",msg.prod_id); } return; - } + } for (const auto &entry : msg.entries) { IMarketDataListener::BookOp inc; inc.id = *sec_id; @@ -127,19 +128,65 @@ class TaifexDataProcessors { for (const auto &trade_record : msg.trades) { auto &record = trades.emplace_back(); record.sec_id = *sec_id; + // record.time_stamp = bts::core::TimeStamp::from_iso_string( + // TaifexUtils::convertToISO(msg.match_time, "datetime_no_timezone")); record.time_stamp = bts::core::TimeStamp::from_iso_string( TaifexUtils::convertToISO(msg.match_time, "datetime_no_timezone")); record.trade_quantity = bts::domain::Quantity(trade_record.match_qty); record.trade_price = bts::domain::Price( trade_record.match_price * std::pow(10, 9 - *dec_loc)); - // TODO: Set the aggressor side (record.agg_side) } + std::ostringstream oss; + oss << "Trades: ["; + for (const auto &trade : trades) { + oss << "{Sec ID: " << trade.sec_id + << ", Timestamp: " << trade.time_stamp + << ", Quantity: " << trade.trade_quantity.value() + << ", Price: " << trade.trade_price + << ", Aggressor Side: " + << ((trade.agg_side == domain::AggressorSide::Buy) ? "Buy" : "Sell") + << "}, "; + } + std::string trade_log = oss.str(); + if (!trades.empty()) { + trade_log.pop_back(); // Remove trailing comma + trade_log.pop_back(); // Remove trailing space + } + trade_log += "]"; + + // Log the string + LOG(md, Info, "{}", trade_log); + std::vector trade_ptrs; trade_ptrs.reserve(trades.size()); for (const auto &trade : trades) { trade_ptrs.push_back(&trade); } + + std::ostringstream ptr_oss; +ptr_oss << "Trade Pointers: ["; +for (const auto *trade_ptr : trade_ptrs) { + if (trade_ptr) { // Ensure the pointer is not null + ptr_oss << "{Sec ID: " << trade_ptr->sec_id + << ", Timestamp: " << trade_ptr->time_stamp + << ", Quantity: " << trade_ptr->trade_quantity.value() + << ", Price: " << trade_ptr->trade_price + << ", Aggressor Side: " + << ((trade_ptr->agg_side == domain::AggressorSide::Buy) ? "Buy" : "Sell") + << "}, "; + } +} +std::string ptr_log = ptr_oss.str(); +if (!trade_ptrs.empty()) { + ptr_log.pop_back(); // Remove trailing comma + ptr_log.pop_back(); // Remove trailing space +} +ptr_log += "]"; + +// Log the string +LOG(md, Info, "Sending to Listner {}", ptr_log); + // for (const auto *trade_ptr : trade_ptrs) { // if (trade_ptr != nullptr) { // LOG(md, Error, "Trade Quantity: {}, Trade Price: {}", @@ -158,16 +205,16 @@ class TaifexDataProcessors { for (const auto &p : config::get().tick_entry()) { values.insert(p); } - // {"TXF",1}, - // {"MXF",1}, - // {"TMF",1}, + // {"TXF",1}, + // {"MXF",1}, + // {"TMF",1}, // {"CDF",1}, // {"QFF",1}, // }; const auto get_min_inc = [&values](std::string symbol){ if(symbol.length()<3){ return 1.0; - } + } auto kind = symbol.substr(0,3); if(!values.contains(kind)){ return 1.0; @@ -248,7 +295,7 @@ class TaifexDataProcessors { day >= 1 && day <= 31, "Invalid day in end_date: {}", day); // Basic check - + // Create a TimeStamp from the parsed date bts::core::TimeStamp expiration; bts_assert_msgf( diff --git a/src/server/sparkd/md/taifex/TaifexMessages.h b/src/server/sparkd/md/taifex/TaifexMessages.h index d9a2ab5b4..e0fa84479 100644 --- a/src/server/sparkd/md/taifex/TaifexMessages.h +++ b/src/server/sparkd/md/taifex/TaifexMessages.h @@ -3,12 +3,14 @@ #include "lib/utils/bts_assert.h" #include "lib/utils/helper_macros.h" #include +#include // Include the correct header for trim functions #include #include + #include #include namespace bts::md::taifex { - using UNPROCESSED_MSG = std::vector; +using UNPROCESSED_MSG = std::vector; class TaifexMessages { public: struct MessageIdentifier { @@ -252,15 +254,14 @@ class TaifexMessages { uint8_t Version_No; uint Body_Length; bool valid = false; - Header_Fields( - const UNPROCESSED_MSG &buffer, const size_t &offset) + Header_Fields(const UNPROCESSED_MSG &buffer, const size_t &offset) : Esc_Code(buffer[offset]), message_type(buffer[offset + 1], buffer[offset + 2]) { // creates header feild struct // and populates all fields // Header_Fields header; // Read single-byte fields - if(message_type.identifier == MessageIdentifier::MessageID::I999){ + if (message_type.identifier == MessageIdentifier::MessageID::I999) { valid = false; return; } @@ -268,11 +269,13 @@ class TaifexMessages { unsigned char bl[2] = {buffer[offset + 17], buffer[offset + 18]}; Body_Length = std::stoul(TaifexUtils::decodePackBCD(bl, 2)); // / Extract Channel_Seq - size_t channel_seq_offset = offset + 11; // Starting at 11 bytes from offset - - Channel_Seq = TaifexUtils::extractBCD_STOUL(buffer,channel_seq_offset,5); - - valid = Channel_Seq!=0; + size_t channel_seq_offset = + offset + 11; // Starting at 11 bytes from offset + + Channel_Seq = + TaifexUtils::extractBCD_STOUL(buffer, channel_seq_offset, 5); + + valid = Channel_Seq != 0; } friend std::ostream &operator<<( @@ -289,7 +292,7 @@ class TaifexMessages { return os; } }; - + struct I024Data { struct trade { enum Sign { POSITIVE = 0, NEGATIVE = 1 }; @@ -355,27 +358,37 @@ class TaifexMessages { } // do we need this? size_t current_position = offset; + + // Extract Product ID prod_id = TaifexUtils::extractString(buffer, current_position, PROD_ID_SIZE); + LOG(md, Info, "FIND TRADE GAP: In constructor, Prod ID: {}", prod_id); + // Extract Sequence Number sequence_number = TaifexUtils::extractBCD_STOUL( buffer, current_position, SEQ_NUMBER_SIZE); + LOG(md, Info, "Sequence Number: {}", sequence_number); // Extract Calculated Flag std::string calculated_flag_str = TaifexUtils::extractString( buffer, current_position, CALCULATED_FLAG); calculated_flag = (calculated_flag_str[0] == '1'); + LOG(md, Info, "Calculated Flag: {}", calculated_flag); // Extract Match Time match_time = TaifexUtils::time_decodePackBCD( buffer.data() + current_position, MATCH_TIME); - //match_time = TaifexUtils::convertToISO(match_time); - //match_time = sanitizeISOString(match_time); - ; // extractBCD(buffer, current_position, MATCH_TIME); + match_time = TaifexUtils::convertToISOFormat(match_time); + boost::trim(match_time); + LOG(md, Info, "Match Time (ISO format): {}", match_time); + current_position += MATCH_TIME; + + // Extract the first trade trades.push_back( trade(buffer, current_position, FIRST_MATCH_QTY_SIZE)); current_position += TRADE_SIZE + 2; + // Extract Match Display Item auto getFirstBitAndRemainingValue = [](char input) -> std::tuple { @@ -388,25 +401,114 @@ class TaifexMessages { auto [new_message, trades_count] = getFirstBitAndRemainingValue(match_display_item); - // assert(new_message); + LOG(md, Info, + "Match Display Item: 0x{:02X}, New Message: {}, Trades Count: {}", + match_display_item, new_message, trades_count); + + // Extract additional trades for (int i = 0; i < trades_count; i++) { trades.push_back(trade(buffer, current_position)); current_position += TRADE_SIZE; } - // match quantity + + // Extract Match Total Quantity match_total_qty = TaifexUtils::extractBCD_STRING( buffer, current_position, MATCH_TOTAL_QTY_SIZE); - // match buy count + LOG(md, Info, "Match Total Quantity: {}", match_total_qty); + + // Extract Match Buy Count match_buy_count = TaifexUtils::extractBCD_STRING( buffer, current_position, MATCH_BUY_COUNT_SIZE); - // match sell count + LOG(md, Info, "Match Buy Count: {}", match_buy_count); + + // Extract Match Sell Count match_sell_count = TaifexUtils::extractBCD_STRING( buffer, current_position, MATCH_SELL_COUNT_SIZE); - // std::cout << "trades count: " << trades_count << std::endl; + LOG(md, Info, "Match Sell Count: {}", match_sell_count); + + // Ensure the message ends with the expected bytes (0x0D 0x0A) assert( buffer[current_position + 1] == 0x0D && buffer[current_position + 2] == 0x0A); } + + //I024Data( + // const UNPROCESSED_MSG &buffer, + // const size_t &offset = 0, + // const size_t &length = -1) { + // const size_t PROD_ID_SIZE = 20; + // const size_t SEQ_NUMBER_SIZE = 5; + // const size_t CALCULATED_FLAG = 1; + // const size_t MATCH_TIME = 6; + // const size_t MATCH_DISPLAY_ITEM_SIZE = 1; + // const size_t TRADE_SIZE = 8; + // const size_t MATCH_TOTAL_QTY_SIZE = 4; + // const size_t MATCH_BUY_COUNT_SIZE = 4; + // const size_t MATCH_SELL_COUNT_SIZE = 4; + // const size_t FIRST_MATCH_QTY_SIZE = 4; + // if (buffer.size() < offset + length) { + // throw std::out_of_range( + // "Buffer is smaller than the required length"); + // } + // // do we need this? + // size_t current_position = offset; + // prod_id = + // TaifexUtils::extractString(buffer, current_position, PROD_ID_SIZE); + // LOG(md, Info, "FIND TRADE GAP: In constructor, Prod ID: {}", prod_id); + + // sequence_number = TaifexUtils::extractBCD_STOUL( + // buffer, current_position, SEQ_NUMBER_SIZE); + + // // Extract Calculated Flag + // std::string calculated_flag_str = TaifexUtils::extractString( + // buffer, current_position, CALCULATED_FLAG); + // calculated_flag = (calculated_flag_str[0] == '1'); + // match_time = TaifexUtils::time_decodePackBCD(buffer.data() + current_position, MATCH_TIME); + // match_time = TaifexUtils::convertToISOFormat(match_time); + // boost::trim(match_time); + // /* + // // Extract Match Time + // match_time = TaifexUtils::time_decodePackBCD( + // buffer.data() + current_position, MATCH_TIME); + // */ + // //match_time = TaifexUtils::convertToISO(match_time); + // //match_time = sanitizeISOString(match_time); + // ; // extractBCD(buffer, current_position, MATCH_TIME); + // current_position += MATCH_TIME; + // trades.push_back( + // trade(buffer, current_position, FIRST_MATCH_QTY_SIZE)); + // current_position += TRADE_SIZE + 2; + // // Extract Match Display Item + // auto getFirstBitAndRemainingValue = + // [](char input) -> std::tuple { + // bool firstBit = (input & 0b10000000) != 0; + // int remainingValue = input & 0b01111111; + // return std::make_tuple(firstBit, remainingValue); + // }; + // match_display_item = buffer[current_position]; + // current_position += MATCH_DISPLAY_ITEM_SIZE; + + // auto [new_message, trades_count] = + // getFirstBitAndRemainingValue(match_display_item); + // // assert(new_message); + // for (int i = 0; i < trades_count; i++) { + // trades.push_back(trade(buffer, current_position)); + // current_position += TRADE_SIZE; + // } + // // match quantity + // match_total_qty = TaifexUtils::extractBCD_STRING( + // buffer, current_position, MATCH_TOTAL_QTY_SIZE); + // // match buy count + // match_buy_count = TaifexUtils::extractBCD_STRING( + // buffer, current_position, MATCH_BUY_COUNT_SIZE); + // // match sell count + // match_sell_count = TaifexUtils::extractBCD_STRING( + // buffer, current_position, MATCH_SELL_COUNT_SIZE); + // // std::cout << "trades count: " << trades_count << std::endl; + // assert( + // buffer[current_position + 1] == 0x0D && + // buffer[current_position + 2] == 0x0A); + // } // 833 251 1142 friend std::ostream &operator<<(std::ostream &os, const I024Data &data) { os << "Product ID: " << data.prod_id << '\n' @@ -467,10 +569,24 @@ class TaifexMessages { // Convert month code to month number static int getMonthFromCode(char code) { - if (code >= 'A' && code <= 'L') - return code - 'A' + - 1; // 'A' corresponds to 1 (January), 'B' to 2, ..., 'L' to 12 (December) - throw std::runtime_error("Invalid month code"); + if (code >= 'A' && code <= 'L') { + int month = code - 'A' + 1;//'A' corresponds to first January, 'B' to February etc. + //for logging + std::string str_month = std::to_string(month); + LOG(md, Info, "Returned value of getMonthFromCode: {}", + std::to_string(month)); + + return month; + } else { + //for logging + std::string str_code = + std::string(1, code); // Convert char to string + LOG(md, Error, + "Invalid Month Code, Returning default: 0, Received char: " + "{}", + str_code); + return 0; + } } // Method to parse Product ID and initialize ProductInfo @@ -721,12 +837,13 @@ class TaifexMessages { buffer, current_position, CHINESE_NAME_SIZE); stock_id = TaifexUtils::extractString( buffer, current_position, STOCK_ID_SIZE); - current_position++;//subtype + current_position++; //subtype contract_size = TaifexUtils::extractBCD_STOUL( - buffer, current_position, CONTRACT_SIZE_SIZE)/1000; + buffer, current_position, CONTRACT_SIZE_SIZE) / + 1000; status_code = static_cast(buffer[current_position++]); currency_enum_type = - static_cast(buffer[current_position++]-'0'); + static_cast(buffer[current_position++] - '0'); decimal_locator = TaifexUtils::extractBCD_STOUL( buffer, current_position, DECIMAL_LOCATOR_SIZE); strike_price_decimal_locator = TaifexUtils::extractBCD_STOUL( @@ -845,8 +962,7 @@ class TaifexMessages { return os; } - I081Data( - const UNPROCESSED_MSG &buffer, const size_t &offset = 0) { + I081Data(const UNPROCESSED_MSG &buffer, const size_t &offset = 0) { const size_t ENTRIES_COUNT_SIZE = 1; const size_t PROD_ID_SIZE = 20; const size_t SEQ_NUMBER_SIZE = 5; @@ -939,7 +1055,7 @@ class TaifexMessages { const UNPROCESSED_MSG &buffer, const size_t &offset = 0, size_t length = -1, - bool ignore_calc_flag=false) { + bool ignore_calc_flag = false) { UNUSED(length); const size_t ENTRIES_COUNT_SIZE = 1; const size_t PROD_ID_SIZE = 20; @@ -957,7 +1073,7 @@ class TaifexMessages { current_position += SEQ_NUMBER_SIZE; calculated_flag = static_cast(*current_position); - if(!ignore_calc_flag) + if (!ignore_calc_flag) current_position += CALCULATED_FLAG_SIZE; std::string entries_count_string = TaifexUtils::decodePackBCD( @@ -968,8 +1084,8 @@ class TaifexMessages { // Following fields group repeat NO-MD-ENTRIES times auto position = PROD_ID_SIZE + SEQ_NUMBER_SIZE + CALCULATED_FLAG_SIZE + ENTRIES_COUNT_SIZE; - if(ignore_calc_flag) - position-=CALCULATED_FLAG_SIZE; + if (ignore_calc_flag) + position -= CALCULATED_FLAG_SIZE; for (size_t i = 0; i < entries_count; ++i) { entries.push_back(MD_ENTRY(buffer, offset + position)); @@ -977,76 +1093,86 @@ class TaifexMessages { // current_position += ENTRIES_COUNT_SIZE;//need to fix } } - }; struct I084Data { - enum MESSAGE_TYPE { - UNDEFINED = 0, - A = 65, - O = 79, - S = 83, - P = 80, - Z = 90, - } message_type; + enum MESSAGE_TYPE { + UNDEFINED = 0, + A = 65, + O = 79, + S = 83, + P = 80, + Z = 90, + } message_type; - MESSAGE_TYPE charToMessageType(char c) { - switch (c) { - case 'A': return A; - case 'O': return O; - case 'S': return S; - case 'P': return P; - case 'Z': return Z; - default: return UNDEFINED; - } - } + MESSAGE_TYPE charToMessageType(char c) { + switch (c) { + case 'A': + return A; + case 'O': + return O; + case 'S': + return S; + case 'P': + return P; + case 'Z': + return Z; + default: + return UNDEFINED; + } + } - std::vector data; - unsigned long last_seq; + std::vector data; + unsigned long last_seq; - // Overload the << operator for convenient output - friend std::ostream &operator<<(std::ostream &os, const I084Data &data) { - os << "The Message Type is: " << char(data.message_type) << "\n"; - for (const auto &entry : data.data) { - os << entry; - } - return os; - } + // Overload the << operator for convenient output + friend std::ostream &operator<<(std::ostream &os, const I084Data &data) { + os << "The Message Type is: " << char(data.message_type) << "\n"; + for (const auto &entry : data.data) { + os << entry; + } + return os; + } - I084Data(const UNPROCESSED_MSG &buffer, const size_t &offset = 0, const bool skip_o =false) { - auto current_position = offset; - message_type = charToMessageType(buffer[current_position]); - current_position += 1; + I084Data( + const UNPROCESSED_MSG &buffer, + const size_t &offset = 0, + const bool skip_o = false) { + auto current_position = offset; + message_type = charToMessageType(buffer[current_position]); + current_position += 1; + + switch (message_type) { + case A: { + + last_seq = + TaifexUtils::extractBCD_STOUL(buffer, current_position, 5); + break; + } + case O: { + if (skip_o) + break; + unsigned int no_entries = + TaifexUtils::extractBCD_STOUL(buffer, current_position, 1); - switch (message_type) { - case A: { - - last_seq = TaifexUtils::extractBCD_STOUL(buffer, current_position,5); - break; - } - case O: { - if(skip_o) - break; - unsigned int no_entries = TaifexUtils::extractBCD_STOUL(buffer,current_position , 1); - // Inner loop: Process each Market Data Entry for (unsigned int i = 0; i < no_entries; ++i) { - auto d = I083Data(buffer, current_position,0,true); - data.push_back(d); - current_position += 26 + 12*d.entries_count; + auto d = I083Data(buffer, current_position, 0, true); + data.push_back(d); + current_position += 26 + 12 * d.entries_count; } - break; - } - case Z: { - last_seq = TaifexUtils::extractBCD_STOUL(buffer, current_position,5); - break; - } - case S: - case P: - default: - break; - } - } -}; - + break; + } + case Z: { + last_seq = + TaifexUtils::extractBCD_STOUL(buffer, current_position, 5); + break; + } + case S: + case P: + default: + break; + } + } + }; }; } // namespace bts::md::taifex \ No newline at end of file diff --git a/src/server/sparkd/md/taifex/TaifexUtils.h b/src/server/sparkd/md/taifex/TaifexUtils.h index dedcc8225..e7802af3d 100644 --- a/src/server/sparkd/md/taifex/TaifexUtils.h +++ b/src/server/sparkd/md/taifex/TaifexUtils.h @@ -270,7 +270,95 @@ class TaifexUtils { return result; } + + static std::string convertToISOFormat(const std::string& input) { + if (input.length() != 12) { + throw std::invalid_argument("Input must be exactly 12 characters (hhmmssxxxxxx)."); + } + // Extract components from the input + std::string hours = input.substr(0, 2); + std::string minutes = input.substr(2, 2); + std::string seconds = input.substr(4, 2); + std::string microseconds = input.substr(6, 6); + + // Validate the time components + int hh = std::stoi(hours); + int mm = std::stoi(minutes); + int ss = std::stoi(seconds); + + if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 59) { + throw std::invalid_argument("Invalid time values in input."); + } + + // Construct the ISO 8601 time string + std::string isoTime = hours + ":" + minutes + ":" + seconds + "." + microseconds; + return isoTime; +} + +static std::string convertToISO(const std::string &match_time, const std::string &format = "datetime_no_timezone") { + // Ensure match_time is not longer than 15 characters + if (match_time.length() > 15) { + throw std::invalid_argument( + "in function convertToISO: match_time must not be longer than 15 characters: -> " + match_time); + } + + // If match_time is shorter than 12 characters, append '0's to the end (for microseconds) + std::string adjusted_match_time = match_time; + while (adjusted_match_time.length() < 12) { + adjusted_match_time += '0'; // Append '0' for microseconds + } + + // Remove non-numeric characters (e.g., ":" and ".") + adjusted_match_time.erase(std::remove_if(adjusted_match_time.begin(), adjusted_match_time.end(), + [](char c) { return !std::isdigit(c); }), + adjusted_match_time.end()); + + // Validate time components + try { + if (adjusted_match_time.length() != 12) { + throw std::invalid_argument("Invalid length for time format: " + match_time); + } + + std::string hours = adjusted_match_time.substr(0, 2); + std::string minutes = adjusted_match_time.substr(2, 2); + std::string seconds = adjusted_match_time.substr(4, 2); + std::string microseconds = adjusted_match_time.substr(6, 6); // Ensure this is 6 digits + + // Now safely convert to integers + int h = std::abs(std::stoi(hours)) % 24; + int m = std::abs(std::stoi(minutes)) % 60; + int s = std::abs(std::stoi(seconds)) % 60; + + // Get the current date dynamically + std::string current_date = getCurrentDate(); + + // Construct the desired ISO format + std::ostringstream iso_stream; + if (format == "datetime_with_timezone") { + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s << "." << microseconds << "Z"; // Assuming UTC for now + } else if (format == "datetime_no_timezone") { + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s << "." << microseconds; + } else if (format == "date_only") { + iso_stream << current_date; + } else { + throw std::invalid_argument( + "Unknown format specified for convertToISO: " + format); + } + + return iso_stream.str(); + } catch (const std::exception &e) { + std::cerr << "Error in convertToISO: " << e.what() << std::endl; + throw; + } +} +/* static std::string convertToISO( const std::string &match_time, const std::string &format = "datetime_no_timezone") { @@ -374,6 +462,7 @@ class TaifexUtils { return result; } + */ static std::string time_decodePackBCD( const unsigned char *data, size_t length) { diff --git a/src/server/sparkd/md/twse/TwseDataGateway.cpp b/src/server/sparkd/md/twse/TwseDataGateway.cpp new file mode 100644 index 000000000..c078f52ee --- /dev/null +++ b/src/server/sparkd/md/twse/TwseDataGateway.cpp @@ -0,0 +1,666 @@ +#include "TwseDataGateway.h" +#include "TwseMessages.h" +#include "lib/api/domain/SecurityType.pb.h" +#include "lib/domain/Security.h" +#include "lib/domain/TradeRecord.h" +#include "lib/logging/logging.h" +#include "lib/md/IMarketDataListener.h" +#include "lib/persistence/IDGenerator.h" +#include "lib/utils/helper_macros.h" +#include +#include +namespace bts::md::twse { + +using UNPROCESSED_DATA = std::vector; + +bool runOnBinaryFile( + const std::string &file_name, + std::set &securities_set, + const std::unordered_set required_securities, + const std::string &twse_securities_path, + std::shared_ptr &listener, + std::shared_ptr &sec_id_store) { + LOG(md, Diag, "In runOnBinaryFile"); + LOG(md, Diag, "The path: {}", file_name); + LOG(md, Diag, "Absolute path: {}", + boost::filesystem::absolute(file_name).string()); + + std::ifstream file(file_name, std::ios::binary); + if (!file) { + LOG(md, Error, "File not found: {}", file_name); + bts_assert(false); + } + + size_t BUFFER_SIZE = 20000; + [[maybe_unused]] size_t counter = 0; + UNPROCESSED_DATA buffer(BUFFER_SIZE); + + while (file.read((reinterpret_cast(buffer.data())), BUFFER_SIZE)) { + size_t position = 0; + [[maybe_unused]] size_t format_counter = 0; + std::cout << std::dec << std::endl; + while (position < BUFFER_SIZE && buffer[position] != 0x1B) { + ++position; + } + + if (position >= BUFFER_SIZE) { + LOG(md, Error, "Escape code (0x0B) not found in buffer"); + break; + } + + while (position < BUFFER_SIZE - 10) { + LOG(md, Diag, "Esc Code in Hexadecimal: 0x{:02X}, format counter: {}", + static_cast(buffer[position]), format_counter); + std::cout << std::dec; + LOG(md, Diag, "Position: {}", position); + format_counter++; + position++; + + auto Header = TwseMessages::Header_Fields(buffer, position); + std::ostringstream oss; + oss << Header; + std::string headerStr = oss.str(); + // LOG(md, Diag, "Header: {}", headerStr); + //std::cout << "Header: \n" << Header; + if (Header.transmission_format_code == 06) { + + LOG(md, Diag, "We're in Case 06"); + auto format_6 = TwseMessages::Format_6(buffer, position); + std::ostringstream oss; + oss << format_6; + std::string format6Str = oss.str(); + LOG(md, Diag, "Format 6: {}", format6Str); + + + if(format_6.stock_code == "0050"){ + LOG(md, Diag, "0050 book!: {}", format6Str); + } + + domain::Book book; + auto &bids = book.bids(); + auto &asks = book.asks(); + + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( + api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, + format_6.stock_code)}; + + // std::vector trades; + + book.set_security_id(sec_id); + + for (unsigned long i = 0; i < format_6.bids.size(); ++i) { + const auto &entry = format_6.bids[i]; + + auto price = bts::domain::Price::from_double(entry.first / 100.0); + bts::domain::Quantity quantity(entry.second); + + bids[i].price = + price; //checck if the indexing starts from 1 or 0 + bids[i].total_quantity = quantity; + } + + // Similarly for asks + for (unsigned int i = 0; i < format_6.asks.size(); ++i) { + const auto &entry = format_6.asks[i]; + + auto price = bts::domain::Price::from_double(entry.first / 100.0); + bts::domain::Quantity quantity(entry.second); + + asks[i].price = price; + asks[i].total_quantity = quantity; + } + + std::vector trades; + // First, add the real-time quote if present + for (const auto "e : format_6.quotes) { + auto &record = trades.emplace_back(); + record.sec_id = sec_id; + // record.time_stamp = bts::core::TimeStamp::from_iso_string( + // format_6.matching_time); + record.time_stamp = bts::core::TimeStamp::from_iso_string( + TwseUtils::convertToISO(format_6.matching_time)); + + record.trade_quantity = + bts::domain::Quantity(quote.volume_field); + record.trade_price = bts::domain::Price( + stod(quote.price_field) * std::pow(10, 9 - 4)); + } + + std::vector trade_ptrs; + trade_ptrs.reserve(trades.size()); + for (const auto &trade : trades) { + trade_ptrs.push_back(&trade); + } + + std::ostringstream ptr_oss; + ptr_oss << "Trade Pointers: ["; + for (const auto *trade_ptr : trade_ptrs) { + if (trade_ptr) { // Ensure the pointer is not null + ptr_oss << "{Sec ID: " << trade_ptr->sec_id + << ", Timestamp: " << trade_ptr->time_stamp + << ", Quantity: " << trade_ptr->trade_quantity.value() + << ", Price: " << trade_ptr->trade_price + << ", Aggressor Side: " + << ((trade_ptr->agg_side == + domain::AggressorSide::Buy) + ? "Buy" + : "Sell") + << "}, "; + } + } + // std::string ptr_log = ptr_oss.str(); + if (!trade_ptrs.empty()) { + // ptr_log.pop_back(); // Remove trailing comma + // ptr_log.pop_back(); // Remove trailing space + } + // ptr_log += "]"; + + // Log the string + // LOG(md, Info, "TWSE Sending to Listner {}", ptr_log); + + listener->on_book(book); + listener->on_trades(trade_ptrs); + position = position + Header.information_length - 10; + } else if (Header.transmission_format_code == 01) { + LOG(md, Diag, "We're in Case 01"); + // Parse Format 1 message + auto format_1 = TwseMessages::Format_1(buffer, position); + + // Convert Format_1 to string for logging + std::ostringstream oss; + oss << format_1; + std::string format1Str = oss.str(); + LOG(md, Diag, "Format 1: {}", format1Str); + + // Extract security ID + const auto id = format_1.sec_code; + const auto symbol = id; + // LOG(md, Info, "Extracted security ID: {}, Symbol: {}", id, symbol); + + const std::string trimmed_id = TwseUtils::trim(id); + if (required_securities.find(trimmed_id) == + required_securities.end()) { + LOG(md, Diag, "Security {} not in required list. Skipping.", + trimmed_id); + continue; + } + + if (securities_set.find(trimmed_id) != securities_set.end()) { + LOG(md, Diag, "Security {} already processed. Skipping.", id); + } else { + securities_set.insert(trimmed_id); + + // Generate or retrieve SecurityID + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( + api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, + id)}; + // LOG(md, Info, "SecurityID in store: {}", sec_id); + + // Populate security details + bts::domain::Security sec; + sec.security_common.venue = bts::api::domain::VENUE_TWSE; + sec.security_common.id = sec_id; + sec.security_common.exchange_sec_id = id; + sec.security_common.desc = id; + sec.security_common.symbol = symbol; + sec.security_common.asset = id; + sec.security_common.group = id; + + auto get_min_inc = [](const std::string &id) { + // LOG(md, Info, "Getting minimum increment for ID: {}", id); + UNUSED(id); + return 0.01; + }; + + // Set minimum increments + sec.security_common.min_price_increment = get_min_inc(id); + sec.security_common.min_quantity = get_min_inc(id); + sec.security_common.min_quantity_increment = get_min_inc(id); + LOG(md, Info, "Set minimum increments for security."); + + sec.security_common.cash_per_point = stod(format_1.trading_unit); + sec.security_common.currency = format_1.trading_currency_code; + // LOG(md, Info, "Set cash per point: {}, Currency: {}", + // sec.security_common.cash_per_point, + // sec.security_common.currency); + + // Serialize Security to JSON + nlohmann::json j; + to_json(j, sec); + std::string json_str = j.dump() + "\n"; + + // Write JSON to file + std::ofstream outfile(twse_securities_path, std::ios::app); + if (outfile.is_open()) { + outfile << json_str; + outfile.close(); + // LOG(md, Info, "Security data written to file."); + } else { + // LOG(md, Info, "Failed to open securities file for writing."); + } + LOG(md, Diag, "securities_set size: {}", securities_set.size()); + + // Notify listener + std::vector const_security_list; + const_security_list.push_back(&sec); + listener->on_securities(const_security_list); + } + // Update position + position = position + Header.information_length - 10; + } else { + LOG(md, Diag, "Unknown Format"); + auto payload_length = Header.information_length; + position += payload_length - 10; + } + } + return true; + } + return false; +} + +int runLive( + [[maybe_unused]] std::set &securities_set, + [[maybe_unused]] const std::unordered_set required_securities, + [[maybe_unused]] const std::string &twse_securities_path, + std::shared_ptr &listener, + std::shared_ptr &sec_id_store) { + LOG(md, Diag, "In runLive"); + + //live connection + const std::string multicastIp = "224.0.100.100"; + const int port = 10000; + const std::string interfaceIp = "10.102.167.131"; + + // Create a UDP socket + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + LOG(md, Error, "Socket creation failed"); + + //perror("socket creation failed"); + return EXIT_FAILURE; + } + LOG(md, Diag, "Socket created successfully"); + + int reuse = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { + LOG(md, Error, "Failed to set SO_REUSEADDR on socket"); + + // perror("setsockopt(SO_REUSEADDR) failed"); + close(sock); + return EXIT_FAILURE; + } + + LOG(md, Diag, "Socket option SO_REUSEADDR set successfully"); + + struct sockaddr_in localAddr = {}; + localAddr.sin_family = AF_INET; + localAddr.sin_port = htons(port); + localAddr.sin_addr.s_addr = INADDR_ANY; + + if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) { + LOG(md, Error, "Socket bind failed"); + + // perror("bind failed"); + close(sock); + return EXIT_FAILURE; + } + + LOG(md, Diag, "Socket bound successfully to port"); + + // Join multicast group + struct ip_mreq mreq; + mreq.imr_multiaddr.s_addr = inet_addr(multicastIp.c_str()); + mreq.imr_interface.s_addr = inet_addr(interfaceIp.c_str()); + + if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < + 0) { + LOG(md, Error, "Failed to join multicast group"); + + // perror("setsockopt(IP_ADD_MEMBERSHIP) failed"); + close(sock); + return EXIT_FAILURE; + } + + LOG(md, Diag, "Joined multicast group successfully"); + + const size_t BUFFER_SIZE = 1024 * 1024; + std::vector buffer(BUFFER_SIZE); + + LOG(md, Diag, "Entering data reception loop"); + + while (true) { + struct sockaddr_in srcAddr; + socklen_t addrLen = sizeof(srcAddr); + size_t bytesRead = recvfrom( + sock, buffer.data(), BUFFER_SIZE, 0, (struct sockaddr *)&srcAddr, + &addrLen); + if (bytesRead < 0) { + std::string err = strerror(errno); + LOG(md, Error, "recvfrom failed: {}", err); + break; + } + // LOG(md, Info, "Received {} bytes from {}:{}", bytesRead, + // inet_ntoa(srcAddr.sin_addr), ntohs(srcAddr.sin_port)); + // Parse received data + size_t position = 0; + size_t format_counter = 0; + + while (position < bytesRead && buffer[position] != 0x1B) { + ++position; // Search for escape code (0x1B) + } + + if (position >= bytesRead) { + // std::cerr << "Escape code (0x1B) not found in buffer" << std::endl; + continue; + } + + while (position < bytesRead - 10) { + std::ostringstream sink; + sink << "Escape Code in Hexadecimal: 0x" << std::hex + << std::setw(2) << std::setfill('0') + << static_cast(buffer[position]) << " for format #" + << format_counter << std::endl; + + ++format_counter; + ++position; + + auto Header = TwseMessages::Header_Fields(buffer, position); + std::ostringstream oss; + oss << Header; + std::string headerStr = oss.str(); + LOG(md, Diag, "Header: {}", headerStr); + + if (Header.transmission_format_code == 6) { + LOG(md, Info, "Book Message --> Case 06"); + LOG(md, Diag, "Book-->Case 06"); + auto format_6 = TwseMessages::Format_6(buffer, position); + std::ostringstream oss; + oss << format_6; + std::string format6Str = oss.str(); + LOG(md, Diag, "Format 6: {}", format6Str); + if(format_6.stock_code == "0050"){ + // LOG(md, Diag, "0050 book!: {}", format6Str); + } + domain::Book book; + auto &bids = book.bids(); + auto &asks = book.asks(); + + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( + api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, + format_6.stock_code)}; + + // std::vector trades; + + book.set_security_id(sec_id); + + for (unsigned long i = 0; i < format_6.bids.size(); ++i) { + const auto &entry = format_6.bids[i]; + + auto price = bts::domain::Price::from_double(entry.first / 100.0); + bts::domain::Quantity quantity(entry.second); + + bids[i].price = + price; //checck if the indexing starts from 1 or 0 + bids[i].total_quantity = quantity; + } + + // Similarly for asks + for (unsigned int i = 0; i < format_6.asks.size(); ++i) { + const auto &entry = format_6.asks[i]; + + auto price = bts::domain::Price::from_double(entry.first / 100.0); + bts::domain::Quantity quantity(entry.second); + + asks[i].price = price; + asks[i].total_quantity = quantity; + } + + std::vector trades; + // First, add the real-time quote if present + for (const auto "e : format_6.quotes) { + auto &record = trades.emplace_back(); + record.sec_id = sec_id; + // record.time_stamp = bts::core::TimeStamp::from_iso_string( + // format_6.matching_time); + record.time_stamp = bts::core::TimeStamp::from_iso_string( + TwseUtils::convertToISO(format_6.matching_time)); + + record.trade_quantity = + bts::domain::Quantity(quote.volume_field); + record.trade_price = bts::domain::Price( + stod(quote.price_field) * std::pow(10, 9 - 4)); + } + + std::vector trade_ptrs; + trade_ptrs.reserve(trades.size()); + for (const auto &trade : trades) { + trade_ptrs.push_back(&trade); + } + + std::ostringstream ptr_oss; + ptr_oss << "Trade Pointers: ["; + for (const auto *trade_ptr : trade_ptrs) { + if (trade_ptr) { // Ensure the pointer is not null + ptr_oss << "{Sec ID: " << trade_ptr->sec_id + << ", Timestamp: " << trade_ptr->time_stamp + << ", Quantity: " << trade_ptr->trade_quantity.value() + << ", Price: " << trade_ptr->trade_price + << ", Aggressor Side: " + << ((trade_ptr->agg_side == + domain::AggressorSide::Buy) + ? "Buy" + : "Sell") + << "}, "; + } + } + std::string ptr_log = ptr_oss.str(); + if (!trade_ptrs.empty()) { + ptr_log.pop_back(); // Remove trailing comma + ptr_log.pop_back(); // Remove trailing space + } + ptr_log += "]"; + + // Log the string + LOG(md, Diag, "TWSE Sending to Listner {}", ptr_log); + + listener->on_book(book); + listener->on_trades(trade_ptrs); + position += Header.information_length - 10; + } else if (Header.transmission_format_code == 1) { + LOG(md, Info, "Case 01 --> Securities Message"); + LOG(md, Diag, "We're in Case 01"); + // Parse Format 1 message + auto format_1 = TwseMessages::Format_1(buffer, position); + + // Convert Format_1 to string for logging + std::ostringstream oss; + oss << format_1; + std::string format1Str = oss.str(); + LOG(md, Diag, "Format 1: {}", format1Str); + + // Extract security ID + const auto id = format_1.sec_code; + const auto symbol = id; + LOG(md, Diag, "Extracted security ID: {}, Symbol: {}", id, symbol); + + const std::string trimmed_id = TwseUtils::trim(id); + if (required_securities.find(trimmed_id) == + required_securities.end()) { + LOG(md, Diag, "Security {} not in required list. Skipping.", + trimmed_id); + continue; + } + + if (securities_set.find(trimmed_id) != securities_set.end()) { + LOG(md, Diag, "Security {} already processed. Skipping.", id); + } else { + securities_set.insert(trimmed_id); + + // Generate or retrieve SecurityID + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( + api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, + id)}; + // LOG(md, Info, "SecurityID in store: {}", sec_id); + // Populate security details + bts::domain::Security sec; + sec.security_common.venue = bts::api::domain::VENUE_TWSE; + sec.security_common.id = sec_id; + sec.security_common.exchange_sec_id = id; + sec.security_common.desc = id; + sec.security_common.symbol = symbol; + sec.security_common.asset = id; + sec.security_common.group = id; + + // Helper function for minimum increment + auto get_min_inc = [](const std::string &id) { + // LOG(md, Info, "Getting minimum increment for ID: {}", id); + UNUSED(id); + return 0.01; + }; + // Populate other fields + sec.security_common.min_price_increment = get_min_inc(id); + sec.security_common.min_quantity = get_min_inc(id); + sec.security_common.min_quantity_increment = get_min_inc(id); + // LOG(md, Info, "Set minimum increments for security."); + + sec.security_common.cash_per_point = stod(format_1.trading_unit); + sec.security_common.currency = format_1.trading_currency_code; + // LOG(md, Info, "Set cash per point: {}, Currency: {}", + // sec.security_common.cash_per_point, + // sec.security_common.currency); + + // Serialize Security to JSON + nlohmann::json j; + to_json(j, sec); + std::string json_str = j.dump() + "\n"; + + // Write JSON to file + std::ofstream outfile(twse_securities_path, std::ios::app); + if (outfile.is_open()) { + outfile << json_str; + outfile.close(); + // LOG(md, Info, "Security data written to file."); + } else { + // LOG(md, Info, "Failed to open securities file for writing."); + } + + std::vector const_security_list; + const_security_list.push_back(&sec); + listener->on_securities(const_security_list); + } + position += Header.information_length - 10; + } else { + LOG(md, Diag, "Unknown Format"); + auto payload_length = Header.information_length; + position += payload_length - 10; + } + } + } + close(sock); + return 0; +} + +void loadSecurities( + const std::string &filePath, + std::set &securitiesSet, + std::shared_ptr sec_id_store, + std::vector> &securitiesVector, + std::shared_ptr listener) { + + std::ifstream infile(filePath); + if (!infile.is_open()) { + LOG(md, Error, "Failed to open securities file for reading: {}", + filePath); + return; + } + + std::string line; + while (std::getline(infile, line)) { + try { + nlohmann::json j = nlohmann::json::parse(line); + std::shared_ptr sec = + std::make_shared(); + from_json(j, *sec); + + const std::string id = sec->security_common.exchange_sec_id; + if (securitiesSet.find(id) == securitiesSet.end()) { + // Generate or retrieve SecurityID + bts::domain::SecurityID sec_id{sec_id_store->get_or_add( + api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, id)}; + sec->security_common.id = sec_id; + securitiesSet.insert(id); + securitiesVector.push_back(sec); + LOG(md, Diag, "Loaded security: {}", id); + } else { + LOG(md, Diag, "Duplicate security ID: {}", id); + } + } catch (const nlohmann::json::parse_error &e) { + std::string err = e.what(); + LOG(md, Error, "JSON parse error: {}", err); + } catch (const std::exception &e) { + std::string err = e.what(); + LOG(md, Error, "Error loading security: {}", err); + } + } + infile.close(); + + // Notify listener about the loaded securities + if (!securitiesVector.empty()) { + std::vector securitiesToNotify; + for (const auto &sec : securitiesVector) { + securitiesToNotify.push_back(sec.get()); + } + listener->on_securities(securitiesToNotify); + } +} + +void bts::md::twse::TwseDataGateway::run( + [[maybe_unused]] const api::md::TwseMarketDataConfig &config, + [[maybe_unused]] std::shared_ptr listner, + [[maybe_unused]] std::shared_ptr sec_id_store) { + + LOG(md, Diag, "In run, twsedatagateway.cpp"); + std::string twse_securities_path = + "/home/bts/sparkdata/data/twse_load_securities.jsonl"; + std::string sec_path = "/home/bts/sparkdata/data/1st_ip_securities_20250116_4"; + std::string book_path = + "/home/bts/sparkdata/data/1st_ip_securities_20250116_27"; + std::set securities_set; + LOG(md, Diag, "securities_set size: {}", securities_set.size()); + + // const std::unordered_set required_securities = { + // "0050", "2317", "2454", "2603", "2615", "00631L", "00633L", + // "00634R", "00637L", "00638R", "00653L", "00654R", "00675L", "00676R", + // "00637L", "006204", "00929", "00919", "006208"}; + +const std::unordered_set required_securities = { + "0050", "2317", "2454", "2603", "2615", "00631L", "00633L", + "00634R", "00637L", "00638R", "00653L", "00654R", "00675L", "00676R", + "00637L", "006204", "00929", "00919", "006208",/* + "6239", "0050", "00703", "00706L", "00707R", "00961", "01001T", "2613", + "0056", "0055", "6239", "00703", "00706L", "00707R", "00961", "01001T", + "2613", "0056", "0055", "00657K", "00690", "00708L", "00712", "00715L", + "00919", "00934", "00938", "00943", "00952", "00685L",*/"054276", "054277", "054278" +}; + + std::vector> securities_vector; + loadSecurities( + twse_securities_path, securities_set, sec_id_store, securities_vector, + listner); + bool run_on_live = true; + if (run_on_live) { + runLive( + securities_set, required_securities, twse_securities_path, listner, + sec_id_store); + } else { + runOnBinaryFile( + sec_path, securities_set, required_securities, twse_securities_path, + listner, sec_id_store); + + runOnBinaryFile( + book_path, securities_set, required_securities, twse_securities_path, + listner, sec_id_store); + } +} + +} // namespace bts::md::twse diff --git a/src/server/sparkd/md/twse/TwseDataGateway.h b/src/server/sparkd/md/twse/TwseDataGateway.h new file mode 100644 index 000000000..4d34091f5 --- /dev/null +++ b/src/server/sparkd/md/twse/TwseDataGateway.h @@ -0,0 +1,27 @@ +#include "lib/api/md/TwseMarketDataConfig.pb.h" +#include // Add this line for std::shared_ptr + + +namespace bts::persistence { +class IDGenerator; +} + +namespace bts::md { +class IMarketDataListener; +} + +namespace bts::md::twse { + + +class TwseDataGateway { +public: + static void run(const api::md::TwseMarketDataConfig &config, + std::shared_ptr listner, + std::shared_ptr sec_id_store); + // (void)config; + // (void)listener; + // (void)sec_id_store; + // // Dummy implementation +}; + +} // namespace bts::md::twse diff --git a/src/server/sparkd/md/twse/TwseDataProcessors.h b/src/server/sparkd/md/twse/TwseDataProcessors.h new file mode 100644 index 000000000..ed3620578 --- /dev/null +++ b/src/server/sparkd/md/twse/TwseDataProcessors.h @@ -0,0 +1,37 @@ +// TwseDataProcessors.h +#ifndef TWSE_DATA_PROCESSORS_H +#define TWSE_DATA_PROCESSORS_H + +#include "TwseMessages.h" +#include "lib/domain/Security.h" +#include "lib/md/IMarketDataListener.h" + +namespace bts::md::twse { +class TwseDataProcessors { + public: + // TwseMessages::Format_1 format_1; + // static bool processBookMessage( + // const TwseMessages::Format_6 &format_6, + // const TwseMessages::Format_1 &format_1, + // std::shared_ptr listener) { + + // auto sec_id = format_1.sec_code; + // if (!sec_id) + // return false; + + // domain::Book book; + // auto &bids = book.bids(); + // auto &asks = book.asks(); + // book.set_security_id(sec_id.value()); + + // for(const auto "e : format_6.quotes){ + // bts::domain::Price price(quote.price_field); + // bts::domain::Quantity quantity(quote.volume_field); + // } + // listener -> on_book(book); + // return true; + // } +}; +} // namespace bts::md::twse + +#endif // TWSE_DATA_PROCESSORS_H diff --git a/src/server/sparkd/md/twse/TwseMessages.h b/src/server/sparkd/md/twse/TwseMessages.h new file mode 100644 index 000000000..8909a384e --- /dev/null +++ b/src/server/sparkd/md/twse/TwseMessages.h @@ -0,0 +1,430 @@ +// TwseMessages.h +#include "TwseUtils.h" +#include "lib/logging/logging.h" +#include +#include +#include +#include +#ifndef TWSE_MESSAGES_H +#define TWSE_MESSAGES_H + +namespace bts::md::twse { +class TwseMessages { + public: + struct Header_Fields { + size_t information_length; + size_t business_type; + size_t transmission_format_code; + size_t transmission_format_version; + size_t transmission_sn; + static const size_t HEADER_SIZE = + 9; // Total size of header including all fields + + Header_Fields(const std::vector &buffer, size_t &offset) { + information_length = + stoull(TwseUtils::decodePackBCD(&buffer[offset], 2)); + business_type = + stoull(TwseUtils::decodePackBCD(&buffer[offset + 2], 1)); + transmission_format_code = + stoull(TwseUtils::decodePackBCD(&buffer[offset + 3], 1)); + transmission_format_version = + stoull(TwseUtils::decodePackBCD(&buffer[offset + 4], 1)); + transmission_sn = + stoull(TwseUtils::decodePackBCD(&buffer[offset + 5], 4)); + + // move offset past header + offset += HEADER_SIZE; + } + friend std::ostream &operator<<( + std::ostream &os, const Header_Fields &hf) { + // std::cout<> bids; + std::vector> asks; + + struct RealTimeQuotes { + std::string price_field; + uint32_t volume_field; + + RealTimeQuotes( + const std::vector &buffer, + const size_t &offset = 0) { + + price_field = TwseUtils::decodePackBCD(&buffer[offset], 5); + volume_field = + stoul(TwseUtils::decodePackBCD(&buffer[offset + 5], 4)); + //offset = offset + 9; + } + + friend std::ostream &operator<<( + std::ostream &os, + const Format_6::RealTimeQuotes &real_time_quotes) { + os << "\n Price Field: " << real_time_quotes.price_field << "\n" + << "Volume Field: " << real_time_quotes.volume_field << "\n"; + return os; + } + }; + std::vector quotes; + // std::vector quotes; + friend std::ostream &operator<<( + std::ostream &os, const Format_6 &format) { + os << "\nStock Code: ." << format.stock_code << ".\n" + << "Matching Time: " << format.matching_time << "\n" + << "Disclosed Item Remarks (Binary): " + << std::bitset<8>(format.disclosed_item_remarks) + << " (Decimal: " << static_cast(format.disclosed_item_remarks) + << ")\n" + << "Rise/Fall Remarks (Binary): " + << std::bitset<8>(format.rise_fall_remarks) + << " (Decimal: " << static_cast(format.rise_fall_remarks) + << ")\n" + << "Status Remarks (Binary): " + << std::bitset<8>(format.status_remarks) + << " (Decimal: " << static_cast(format.status_remarks) << ")\n" + << "Accumulative Trading Volume: " + << format.accumalative_trading_volume << "\n"; + + os << "Real Time Quotes:\n"; + for (const auto "e : format.quotes) { + os << quote; + } + os << "Bids: \n"; + for (const auto &bid : format.bids) { + os << "Price = " << bid.first << " Quantity = " << bid.second + << "\n"; + } + + os << "\nAsks: \n"; + for (const auto &ask : format.asks) { + os << "Price = " << ask.first << " Quantity = " << ask.second + << "\n"; + } + // os << "Quotes:\n"; + // for (const auto &real_time_quotes : format.quotes) { + // os << real_time_quotes; + // } + return os; + } + + Format_6( + const std::vector &buffer, const size_t &offset = 0) { + size_t position = offset; + + stock_code = std::string( + buffer.begin() + position, buffer.begin() + position + 6); + stock_code = TwseUtils::trim(stock_code); + position += 6; + + matching_time = TwseUtils::decodePackBCD(&buffer[position], 6); + position += 6; + + disclosed_item_remarks = buffer[position]; + position += 1; + + rise_fall_remarks = buffer[position]; + position += 1; + + status_remarks = buffer[position]; + position += 1; + + accumalative_trading_volume = + stoul(TwseUtils::decodePackBCD(&buffer[position], 4)); + position += 4; + + if (disclosed_item_remarks & 0x80) { // If Bit 7 is 1 + LOG(md, Diag, "Price Field and Volume Field present"); + // std::cin.ignore(); + auto rtq = RealTimeQuotes(buffer, position); + quotes.push_back(rtq); + } else { + LOG(md, Diag, "No Price Field and Volume Field"); + } + LOG(md, Diag, "Purchasing Price and Volumes"); + + std::cout << std::dec; + // Read Purchase Price and Volume + uint8_t purchasing_count = + (disclosed_item_remarks >> 4) & 0x07; // Get bits 6-4 + for (uint8_t i = 0; i < purchasing_count; ++i) { + std::string purchase_price = + TwseUtils::decodePackBCD(&buffer[position], 5); // Price Field + double bid_price = + std::stod(TwseUtils::decodePackBCD(&buffer[position], 5)); + position += 5; // Move to the volume field + + std::string volume_field = + TwseUtils::decodePackBCD(&buffer[position], 4); // Volume Field + uint32_t bid_volume = + stoul(TwseUtils::decodePackBCD(&buffer[position], 4)); + position += 4; // Move to the next price field + LOG(md, Info, "Purchase Price {}: {} Volume {}: {}", i + 1, + purchase_price, i + 1, volume_field); + bids.emplace_back(bid_price, bid_volume); + } + + // Read Sell Price and Volume if applicable + uint8_t selling_count = + (disclosed_item_remarks >> 1) & 0x07; // Get bits 3-1 + for (uint8_t i = 0; i < selling_count; ++i) { + std::string sell_price = TwseUtils::decodePackBCD( + &buffer[position], 5); // Price Field: 5 bytes + double ask_price = + std::stod(sell_price); // Use the 5-byte decoded value + position += 5; // Move to the volume field + + std::string volume_field = TwseUtils::decodePackBCD( + &buffer[position], 4); // Volume Field: 4 bytes + uint32_t ask_volume = + stoul(volume_field); // Use the 4-byte decoded value + position += 4; // Move to the next price field + + LOG(md, Info, "Sell Price {}: {} Volume {}: {}", i + 1, sell_price, + i + 1, volume_field); + + asks.emplace_back(ask_price, ask_volume); + } + } + }; + + struct Format_1 { + std::string sec_code; + std::string stock_abbreviation; + std::string industry_category; + std::string stock_category; //can be blank + std::string stock_entries; //can be blank + std::string stock_anomaly_code; + std::string board_code; + std::string today_currency_price; + std::string trading_currency_code; + std::string rise_stop_price; + std::string fall_stop_price; + std::string non_10_face_value_indicator; + std::string abnormal_recommendation_indicator; + std::string abnormal_securities_indicator; + std::string day_trading_indicator; + std::string exemption_unchanged_market_margin_sale_indicator; + std::string exemption_unchanged_market_securities_lending_sale_indicator; + std::string matching_cycle_seconds; + std::string warrant_id; + std::string + exercise_strike_price; // This will need to be decoded from PACK BCD + std::string + prev_business_day_exercise_volume; // This will also need PACK BCD decoding + std::string prev_business_day_cancellation_volume; // PACK BCD format + std::string issuing_balance_volume; // PACK BCD format + std::string strike_ratio; // PACK BCD format + std::string upper_limit_price; // PACK BCD format + std::string lower_limit_price; // PACK BCD format + std::string maturity_date; + std::string foreign_stock_id; + std::string trading_unit; // PACK BCD format + std::string trading_currency_code_foreign_stock; + std::string market_information_note; + + Format_1( + const std::vector &buffer, const size_t &offset = 0) { + size_t position = offset; + + sec_code = std::string( + buffer.begin() + position, buffer.begin() + position + 6); + sec_code = TwseUtils::trim(sec_code); + position += 6; + + stock_abbreviation = std::string( + buffer.begin() + position, buffer.begin() + position + 16); + position += 16; + + industry_category = std::string( + buffer.begin() + position, buffer.begin() + position + 2); + + // std::cout << "Industry Category (Hex): "; + // for (char c : industry_category_str) { + // std::cout << std::setw(2) << std::setfill('0') << std::hex << + // (int)(unsigned char)c << " "; + // } + // std::cout << std::endl; + // Convert the ASCII string to an integer + position += 2; + + //hex values show pointing at the right place + stock_category = std::string( + buffer.begin() + position, buffer.begin() + position + 2); + // std::cout << "Stock Category (String): " << stock_category << std::endl; + // std::cout << "Stock Category (ASCII Values): "; + // for (char c : stock_category) { + // std::cout << (int)(unsigned char)c << " "; // Prints the ASCII value of each character + // } + // std::cout << std::endl; + + // std::cout << "Stock Category (Hex): "; + // for (char c : stock_category) { + // std::cout << std::setw(2) << std::setfill('0') << std::hex << + // (int)(unsigned char)c << " "; + // } + // std::cout << std::endl; + position += 2; + + stock_entries = std::string( + buffer.begin() + position, buffer.begin() + position + 2); + position += 2; + + stock_anomaly_code = TwseUtils::decodePackBCD(&buffer[position], 1); + position += 1; + + board_code = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + today_currency_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + rise_stop_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + fall_stop_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + non_10_face_value_indicator = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + abnormal_recommendation_indicator = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + abnormal_securities_indicator = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + day_trading_indicator = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + exemption_unchanged_market_margin_sale_indicator = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + exemption_unchanged_market_securities_lending_sale_indicator = + std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + matching_cycle_seconds = + TwseUtils::decodePackBCD(&buffer[position], 3); + position += 3; + + warrant_id = std::string( + buffer.begin() + position, buffer.begin() + position + 1); + position += 1; + + exercise_strike_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + prev_business_day_exercise_volume = + TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + prev_business_day_cancellation_volume = + TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + issuing_balance_volume = + TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + strike_ratio = TwseUtils::decodePackBCD(&buffer[position], 4); + position += 4; + + upper_limit_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + lower_limit_price = TwseUtils::decodePackBCD(&buffer[position], 5); + position += 5; + + maturity_date = TwseUtils::decodePackBCD(&buffer[position], 4); + position += 4; + + foreign_stock_id = TwseUtils::decodePackBCD(&buffer[position], 1); + position += 1; + + trading_unit = TwseUtils::decodePackBCD(&buffer[position], 3); + position += 3; + + trading_currency_code = TwseUtils::decodePackBCD(&buffer[position], 3); + position += 3; + + market_information_note = + TwseUtils::decodePackBCD(&buffer[position], 1); + position += 1; + } + + friend std::ostream &operator<<( + std::ostream &os, const Format_1 &format) { + os << "\nSEC Code: " << format.sec_code << "\n" + << "Stock Abbreviation: " << format.stock_abbreviation << "\n" + << "Industry Category: " << format.industry_category << "\n" + << "Stock Category(can be blank): " << format.stock_category << "\n" + << "Stock Entries(can be blank): " << format.stock_entries << "\n" + << "Stock Anomaly code: " << format.stock_anomaly_code << "\n" + << "Board Code: " << format.board_code << "\n" + << "Today Currency Price: " << format.today_currency_price << "\n" + << "Rise Stop Price: " << format.rise_stop_price << "\n" + << "Fall Stop Price: " << format.fall_stop_price << "\n" + << "Non-$10 Face Value Indicator: " + << format.non_10_face_value_indicator << "\n" + << "Abnormal Recommendation Indicator: " + << format.abnormal_recommendation_indicator << "\n" + << "Abnormal Securities Indicator: " + << format.abnormal_securities_indicator << "\n" + << "Day Trading Indicator: " << format.day_trading_indicator << "\n" + << "Exemption of Unchanged Market Margin Sale Indicator: " + << format.exemption_unchanged_market_margin_sale_indicator << "\n" + << "Exemption of Unchanged Market Securities Lending Sale " + "Indicator: " + << format + .exemption_unchanged_market_securities_lending_sale_indicator + << "\n" + << "Matching Cycle Seconds: " << format.matching_cycle_seconds + << "\n" + << "Warrant ID: " << format.warrant_id << "\n" + << "Exercise (Strike) Price: " << format.exercise_strike_price + << "\n" + << "Previous Business Day Exercise Volume: " + << format.prev_business_day_exercise_volume << "\n" + << "Previous Business Day Cancellation Volume: " + << format.prev_business_day_cancellation_volume << "\n" + << "Issuing Balance Volume: " << format.issuing_balance_volume + << "\n" + << "Strike Ratio: " << format.strike_ratio << "\n" + << "Upper Limit Price: " << format.upper_limit_price << "\n" + << "Lower Limit Price: " << format.lower_limit_price << "\n" + << "Maturity Date: " << format.maturity_date << "\n" + << "Foreign Stock ID: " << format.foreign_stock_id << "\n" + << "Trading Unit: " << format.trading_unit << "\n" + << "Trading Currency Code: " << format.trading_currency_code << "\n" + << "Market Information Note: " << format.market_information_note + << "\n"; + return os; + } + }; +}; +} //namespace bts::md::twse + +#endif // TWSE_MESSAGES_H diff --git a/src/server/sparkd/md/twse/TwseSecurityDetailsMapper.h b/src/server/sparkd/md/twse/TwseSecurityDetailsMapper.h new file mode 100644 index 000000000..110b28f78 --- /dev/null +++ b/src/server/sparkd/md/twse/TwseSecurityDetailsMapper.h @@ -0,0 +1,13 @@ +// TwseSecurityDetailsMapper.h +#ifndef TWSE_SECURITY_DETAILS_MAPPER_H +#define TWSE_SECURITY_DETAILS_MAPPER_H + +namespace TWSE { + class TwseSecurityDetailsMapper { + public: + TwseSecurityDetailsMapper() = default; + ~TwseSecurityDetailsMapper() = default; + }; +} + +#endif // TWSE_SECURITY_DETAILS_MAPPER_H diff --git a/src/server/sparkd/md/twse/TwseUtils.h b/src/server/sparkd/md/twse/TwseUtils.h new file mode 100644 index 000000000..008e83386 --- /dev/null +++ b/src/server/sparkd/md/twse/TwseUtils.h @@ -0,0 +1,124 @@ +// TwseUtils.h +#include +#include +#include +#include +#ifndef TWSE_UTILS_H +#define TWSE_UTILS_H + +namespace bts::md::twse { +class TwseUtils { + public: + // Function to trim whitespace from a string + static std::string trim(const std::string &str) { + size_t first = str.find_first_not_of(' '); + if (std::string::npos == first) { + return str; + } + size_t last = str.find_last_not_of(' '); + return str.substr(first, (last - first + 1)); + } + static std::string getCurrentDate() { + auto now = std::chrono::system_clock::now(); + std::time_t now_c = std::chrono::system_clock::to_time_t(now); + std::tm local_tm = *std::localtime(&now_c); + + char buffer[11]; // Buffer to hold formatted date + std::strftime(buffer, sizeof(buffer), "%Y-%m-%d", &local_tm); + return std::string(buffer); + } + static std::string convertToISO( + const std::string &match_time, + const std::string &format = "datetime_no_timezone") { + // Ensure match_time is not longer than 15 characters + if (match_time.length() > 15) { + throw std::invalid_argument( + "in function convertToISO: match_time must not be longer than 15 " + "characters: -> " + + match_time); + } + + // If match_time is shorter than 12 characters, append '0's to the end (for microseconds) + std::string adjusted_match_time = match_time; + while (adjusted_match_time.length() < 12) { + adjusted_match_time += '0'; // Append '0' for microseconds + } + + // Remove non-numeric characters (e.g., ":" and ".") + adjusted_match_time.erase( + std::remove_if( + adjusted_match_time.begin(), adjusted_match_time.end(), + [](char c) { return !std::isdigit(c); }), + adjusted_match_time.end()); + + // Validate time components + try { + if (adjusted_match_time.length() != 12) { + throw std::invalid_argument( + "Invalid length for time format: " + match_time); + } + + std::string hours = adjusted_match_time.substr(0, 2); + std::string minutes = adjusted_match_time.substr(2, 2); + std::string seconds = adjusted_match_time.substr(4, 2); + std::string microseconds = + adjusted_match_time.substr(6, 6); // Ensure this is 6 digits + + // Now safely convert to integers + int h = std::abs(std::stoi(hours)) % 24; + int m = std::abs(std::stoi(minutes)) % 60; + int s = std::abs(std::stoi(seconds)) % 60; + + // Get the current date dynamically + std::string current_date = getCurrentDate(); + + // Construct the desired ISO format + std::ostringstream iso_stream; + if (format == "datetime_with_timezone") { + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s << "." << microseconds + << "Z"; // Assuming UTC for now + } else if (format == "datetime_no_timezone") { + iso_stream << current_date << "T" << std::setfill('0') + << std::setw(2) << h << ":" << std::setfill('0') + << std::setw(2) << m << ":" << std::setfill('0') + << std::setw(2) << s << "." << microseconds; + } else if (format == "date_only") { + iso_stream << current_date; + } else { + throw std::invalid_argument( + "Unknown format specified for convertToISO: " + format); + } + + return iso_stream.str(); + } catch (const std::exception &e) { + std::cerr << "Error in convertToISO: " << e.what() << std::endl; + throw; + } + } + + static std::string decodePackBCD(const unsigned char *data, size_t length) { + std::stringstream ss; + for (size_t i = 0; i < length; ++i) { + // Extract the upper and lower nibble (4 bits each) + int upper = (data[i] >> 4) & 0x0F; + int lower = data[i] & 0x0F; + + // Append both nibbles to the stringstream + ss << upper << lower; + } + + std::string result = ss.str(); + + // Remove leading zeros + // result.erase(0, result.find_first_not_of('0')); + + // If the result is empty (all zeros), return "0" + return result.empty() ? "0" : result; + } +}; +} //namespace bts::md::twse + +#endif // TWSE_UTILS_H