390 lines
16 KiB
C++
390 lines
16 KiB
C++
#include "OnixFIXAdapter.h"
|
|
#include "OnixS/FIXEngine/FIX/Engine.h"
|
|
#include "lib/config/protos/marex_fix_cfg.pb.h"
|
|
#include "lib/domain_model/Security.pb.h"
|
|
#include "lib/logging/logging.h"
|
|
#include "lib/orderman/CancelOrderMsg.h"
|
|
#include "lib/orderman/CancelReplaceOrderMsg.h"
|
|
#include "lib/orderman/CreateOrderMsg.h"
|
|
#include "lib/orderman/gateways/OnixFIXListener.h"
|
|
#include "lib/orderman/gateways/TrafixOrderStateHandler.h"
|
|
#include "lib/orderman/orderman_utils/orderman_common.h"
|
|
#include "lib/utils/bts_assert.h"
|
|
#include "lib/utils/helper_macros.h"
|
|
#include <OnixS/FIXEngine/FIX/Exception.h>
|
|
#include <OnixS/FIXEngine/FIX/FIX42.h>
|
|
#include <OnixS/FIXEngine/FIX/Message.h>
|
|
#include <OnixS/FIXEngine/FIX/Numeric.h>
|
|
#include <OnixS/FIXEngine/FIX/ProtocolVersion.h>
|
|
#include <cassert>
|
|
#include <chrono>
|
|
#include <memory>
|
|
#include <quickfix/FixFields.h>
|
|
#include <ratio>
|
|
#include <string>
|
|
#include <unistd.h>
|
|
|
|
namespace bts::orderman {
|
|
void handleException(
|
|
const std::string &context, const std::string &error) {
|
|
bts_assert_msgf(false, "{} Exception: {}", context, error);
|
|
}
|
|
OnixFIXAdapter::OnixFIXAdapter(md::SecurityOracle sec_oracle)
|
|
: state_handler(std::make_shared<TrafixOrderStateHandler>(sec_oracle)),
|
|
listener(state_handler) {
|
|
try {
|
|
auto onix_cfg = config::get<config::MarexFixCfg>();
|
|
LOG(OrderMan, Warn, "Initializing OnixFIXAdapter");
|
|
OnixS::FIX::Engine::
|
|
init(); // OnixS::FIX::Engine::init() needs to run before initialising session
|
|
LOG(OrderMan, Diag, "Initializing OnixFIXAdapter engine initailes trying login");
|
|
session = std::make_unique<Session>(
|
|
onix_cfg.sender_sub_id(), onix_cfg.target_sub_id(),
|
|
OnixS::FIX::ProtocolVersion::FIX_42, &listener);
|
|
} catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
LOG(OrderMan, Error, "Initializing OnixFIXAdapter ...{}",err);
|
|
Engine::shutdown();
|
|
handleException("OnixFIXAdapter::Construcotr init", err);
|
|
}
|
|
}
|
|
OnixFIXAdapter::~OnixFIXAdapter() {
|
|
try {
|
|
if (session)
|
|
session->logout();
|
|
Engine::instance()->unregisterListener();
|
|
Engine::shutdown();
|
|
} catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
handleException("OnixFIXAdapter::Destructor ", err);
|
|
}
|
|
}
|
|
void OnixFIXAdapter::start() {
|
|
auto cfg = config::get<config::MarexFixCfg>();
|
|
const std::string counterpartyHost = cfg.counterparty_host();
|
|
const int heartBtInt = cfg.heart_bt_int();
|
|
const int counterpartyPort = cfg.counterparty_port();
|
|
const int retryInterval = cfg.retry_interval(); // Add this field in MarexFixCfg
|
|
const int maxRetries = cfg.max_retries(); // Optional: Set a limit on retries
|
|
|
|
int attempt = 0;
|
|
|
|
while (true) {
|
|
try {
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::start Attempting login (Attempt: {})", attempt + 1);
|
|
session->logonAsInitiator(counterpartyHost, counterpartyPort, heartBtInt);
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::start Login successful");
|
|
break; // Exit loop on success
|
|
} catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
LOG(OrderMan, Error, "OnixFIXAdapter::start Login failed: {}. Retrying in {} seconds.", err, retryInterval);
|
|
|
|
if (maxRetries > 0 && ++attempt >= maxRetries) {
|
|
Engine::shutdown();
|
|
LOG(OrderMan, Error, "OnixFIXAdapter::start Exceeded max retries ({}). Aborting.", maxRetries);
|
|
handleException("OnixFIXAdapter::start", err);
|
|
break; // Exit if retries are exhausted
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::seconds(std::max(60,retryInterval)));
|
|
}
|
|
}
|
|
}
|
|
template <typename T>
|
|
uint translateEnum(T enum_value, const std::map<int, int> &translationMap) {
|
|
auto it = translationMap.find(enum_value);
|
|
bts_assert(it != translationMap.end()); // Using assert instead of bts_assert
|
|
return it->second;
|
|
}
|
|
|
|
uint translateTimeInForce(api::orderman::TimeInForce time_in_force) {
|
|
//0 = Day 1 = GTC 2 = At the Open 3 = IOC 4 = FOK 5 = GTX
|
|
static const std::map<int, int> tifMap = {
|
|
{api::orderman::TimeInForce::TIME_IN_FORCE_DAY, 0},
|
|
{api::orderman::TimeInForce::TIME_IN_FORCE_GTC, 1},
|
|
{api::orderman::TimeInForce::TIME_IN_FORCE_IOC, 3}};
|
|
|
|
return translateEnum(time_in_force, tifMap);
|
|
}
|
|
|
|
uint translateOrderType(api::orderman::NativeOrderType order_type) {
|
|
//1 = Market 2 = Limit 3 = Stop 4 = Stop Limit 5 = Market on close A = On Close B = Limit on Close
|
|
static const std::map<int, int> orderTypeMap = {
|
|
{api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_MARKET, 1},
|
|
{api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_LIMIT, 2},
|
|
{api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP, 3},
|
|
{api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP_LIMIT, 4}};
|
|
|
|
return translateEnum(order_type, orderTypeMap);
|
|
}
|
|
uint translateSide(api::Side side) {
|
|
//1 = Buy 2 = Sell 5 = Sell short 6 = Sell short Exempt
|
|
static const std::map<int, int> sideMap = {
|
|
{api::Side::SIDE_BUY, 1}, {api::Side::SIDE_SELL, 2}};
|
|
|
|
return translateEnum(side, sideMap);
|
|
}
|
|
|
|
std::string pad_string(
|
|
const std::string &str, size_t length, char padding = ' ') {
|
|
if (str.size() > length) {
|
|
return str.substr(0, length);
|
|
}
|
|
return str + std::string(length - str.size(), padding);
|
|
}
|
|
|
|
// Function to create the OSI Symbol
|
|
static std::string create_osi_symbol(
|
|
const std::string &symbol,
|
|
const uint32_t &year,
|
|
const uint32_t &month,
|
|
const uint32_t &day,
|
|
const char &call_put_indicator,
|
|
const double &strike_price) {
|
|
if (symbol.size() > 6) {
|
|
throw std::invalid_argument("Symbol length cannot exceed 6 characters.");
|
|
}
|
|
|
|
std::ostringstream osi_stream;
|
|
|
|
// Symbol: 6 bytes, padded with spaces
|
|
osi_stream << pad_string(symbol, 6);
|
|
|
|
// Year: last 2 digits of the year
|
|
osi_stream << std::setw(2) << std::setfill('0') << (year % 100);
|
|
|
|
// Month: 2 digits
|
|
osi_stream << std::setw(2) << std::setfill('0') << month;
|
|
|
|
// Day: 2 digits
|
|
osi_stream << std::setw(2) << std::setfill('0') << day;
|
|
|
|
// Call/Put Indicator: 1 byte
|
|
osi_stream << call_put_indicator;
|
|
|
|
// Strike Price: 5 bytes for dollars, 3 bytes for decimal part
|
|
int strike_dollars = static_cast<int>(strike_price);
|
|
int strike_decimals =
|
|
static_cast<int>((strike_price - strike_dollars) * 1000);
|
|
osi_stream << std::setw(5) << std::setfill('0') << strike_dollars;
|
|
osi_stream << std::setw(3) << std::setfill('0') << strike_decimals;
|
|
|
|
return osi_stream.str();
|
|
}
|
|
|
|
void parse_option(Message &order, const api::Security &sec) {
|
|
auto osi = create_osi_symbol(
|
|
sec.symbol(), sec.option().expiration_year(),
|
|
sec.option().expiration_month(), sec.option().expiration_day(),
|
|
sec.option().call_put() == bts::api::PutOrCall::PUTORCALL_CALL ? 'c'
|
|
: 'p',
|
|
sec.option().strike());
|
|
std::ostringstream month_stream;
|
|
month_stream << std::setw(2) << std::setfill('0')
|
|
<< sec.option().expiration_month();
|
|
std::string month = month_stream.str();
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::parse_option parsing osi:{}", osi);
|
|
order
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::PutOrCall,
|
|
sec.option().call_put() == bts::api::PutOrCall::PUTORCALL_CALL ? "1"
|
|
: "0")
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::StrikePrice,
|
|
std::to_string(sec.option().strike()))
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::MaturityMonthYear,
|
|
std::to_string(sec.option().expiration_year()) + month)
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::MaturityDay,
|
|
std::to_string(sec.option().expiration_day()))
|
|
.set(OnixS::FIX::FIX42::Tags::SecurityType, "OPT")
|
|
.set(OnixS::FIX::FIX42::Tags::Symbol, sec.symbol());
|
|
}
|
|
|
|
void add_cfg_fields(Message &order, const config::MarexFixCfg &cfg) {
|
|
order
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::HandlInst,
|
|
cfg.handl_inst()) // 1: DMA 2: ALGO 3:CARE
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::Rule80A,
|
|
cfg.Rule80A_Name(cfg.rule80a())) //A = AGENCY P = PRINCIPAL
|
|
.set(OnixS::FIX::FIX42::Tags::SenderSubID, cfg.sender_sub_id())
|
|
.set(OnixS::FIX::FIX42::Tags::TargetSubID, cfg.target_sub_id())
|
|
.set(OnixS::FIX::FIX42::Tags::ClientID, cfg.client_id())
|
|
.set(OnixS::FIX::FIX42::Tags::CustomerOrFirm, cfg.customer_or_firm())
|
|
.set(OnixS::FIX::FIX42::Tags::OpenClose, cfg.open_close());
|
|
order.set(FIX42::Tags::Currency,cfg.currency());
|
|
order.set(FIX42::Tags::SecurityExchange,cfg.security_exchange());
|
|
order.set(FIX42::Tags::ExDestination,cfg.ex_destination());
|
|
}
|
|
void populate_common_order_fields(Message &order, const CreateOrderMsg &msg) {
|
|
order.set(OnixS::FIX::FIX42::Tags::Account, msg.routing_record->account())
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::TimeInForce,
|
|
translateTimeInForce(msg.time_in_force))
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::OrdType, translateOrderType(msg.order_type))
|
|
.set(OnixS::FIX::FIX42::Tags::Side, translateSide(msg.side))
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::Price,
|
|
static_cast<float>(msg.price.value()))
|
|
.set(OnixS::FIX::FIX42::Tags::OrderQty, msg.quantity.value());
|
|
if (msg.security->has_option()) {
|
|
parse_option(order, *msg.security);
|
|
} else {
|
|
order.set(OnixS::FIX::FIX42::Tags::Symbol, msg.security->symbol())
|
|
.set(OnixS::FIX::FIX42::Tags::SecurityType, "FUT") //need to fix this
|
|
.set(OnixS::FIX::FIX42::Tags::Currency, msg.security->currency());
|
|
}
|
|
}
|
|
void OnixFIXAdapter::dispatch_incoming_fix_messages() {
|
|
listener.dispatch_incoming_fix_messages();
|
|
}
|
|
void OnixFIXAdapter::modify_order(
|
|
const CancelReplaceOrderMsg &msg) { //confirm will have everything
|
|
try {
|
|
|
|
//use this fileOnixS.FixEngineCpp-Ubuntu2204-gcc1210-c++17-x64-4.10.1/OnixS.FixEngineCpp-Ubuntu2204-gcc1210-c++17-x64-4.10.1/doc/html/group__double-decimal-conversion.html
|
|
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::modify_order modifying order{}",
|
|
msg);
|
|
auto order_cfg = config::get<config::MarexFixCfg>();
|
|
auto id =
|
|
state_handler->get_marex_key(OrderKey(msg.create_fields.key.value()));
|
|
|
|
if (id == "") {
|
|
LOG(OrderMan, Error,
|
|
"OnixFIXAdapter::modify_order could not find clorid");
|
|
return;
|
|
}
|
|
auto new_id = state_handler->new_id(id);
|
|
|
|
Message order(
|
|
OnixS::FIX::FIX42::Values::MsgType::Order_Cancel_Replace_Request,
|
|
OnixS::FIX::ProtocolVersion::FIX_42);
|
|
order.set(OnixS::FIX::FIX42::Tags::OrigClOrdID, id)
|
|
.set(OnixS::FIX::FIX42::Tags::ClOrdID, new_id) // ID for order
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::TransactTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
|
|
add_cfg_fields(order, order_cfg);
|
|
populate_common_order_fields(order, msg.create_fields);
|
|
order.validate();
|
|
LOG(OrderMan, Warn, "order Validated");
|
|
order.set(OnixFIXAdapter::FIX_TAG_SMART_ROUTING, "SMART").set(
|
|
OnixS::FIX::FIX42::Tags::SendingTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
std::string order_string = order.toString('|');
|
|
state_handler->modifyOrder(msg, new_id);
|
|
session->send(&order);
|
|
LOG(OrderMan, Warn, "Order update sent :{}", order_string);
|
|
} catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
handleException("Modify order", err);
|
|
}
|
|
}
|
|
|
|
void OnixFIXAdapter::launch_new_order(const CreateOrderMsg &msg) {
|
|
LOG(OrderMan, Warn, "launch order {}", msg);
|
|
|
|
try {
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::launch_new_order creating order");
|
|
auto order_cfg = config::get<config::MarexFixCfg>();
|
|
|
|
auto new_id =
|
|
state_handler->new_id(":" + std::to_string(msg.key.value()));
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::launch_new_order new id:'{}'",
|
|
new_id);
|
|
std::string symbol = msg.security->symbol();
|
|
Message order(
|
|
OnixS::FIX::FIX42::Values::MsgType::Order_Single,
|
|
OnixS::FIX::ProtocolVersion::FIX_42);
|
|
order
|
|
.set(OnixS::FIX::FIX42::Tags::ClOrdID, new_id) // ID for order
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::TransactTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
add_cfg_fields(order, order_cfg);
|
|
populate_common_order_fields(order, msg);
|
|
|
|
std::string order_string = order.toString('|');
|
|
std::string order_json = order.toJson();
|
|
order.validate();
|
|
LOG(OrderMan, Warn, "order Validated");
|
|
|
|
order.set(OnixFIXAdapter::FIX_TAG_SMART_ROUTING, "SMART").set(
|
|
OnixS::FIX::FIX42::Tags::SendingTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
state_handler->launchOrder(msg, new_id);
|
|
// listener.fire_dummy_report(msg);
|
|
session->send(&order);
|
|
LOG(OrderMan, Warn, "Order sent :{} json:{}", order_string, order_json);
|
|
|
|
}
|
|
// Shut down all reactors if they exist.
|
|
catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
handleException("Launch order", err);
|
|
}
|
|
}
|
|
void OnixFIXAdapter::register_callback(const OnExecutionReport &cb) {
|
|
LOG(OrderMan, Warn, "OnixFIXAdapter::register_callback callback registered");
|
|
listener.setCallback(cb);
|
|
}
|
|
void OnixFIXAdapter::cancel_order(const CancelOrderMsg &msg) {
|
|
LOG(OrderMan, Warn, "cancel order {}", msg);
|
|
try {
|
|
auto id = state_handler->get_marex_key(OrderKey(msg.key.value()));
|
|
auto order_cfg = config::get<config::MarexFixCfg>();
|
|
|
|
if (id == "") {
|
|
LOG(OrderMan, Error,
|
|
"OnixFIXAdapter::modify_order could not find clorid");
|
|
return;
|
|
}
|
|
auto new_id = state_handler->new_id(id);
|
|
Message order_cancel(
|
|
OnixS::FIX::FIX42::Values::MsgType::Order_Cancel_Request,
|
|
OnixS::FIX::ProtocolVersion::FIX_42);
|
|
order_cancel.set(
|
|
OnixS::FIX::FIX42::Tags::HandlInst, order_cfg.handl_inst());
|
|
order_cancel.set(OnixS::FIX::FIX42::Tags::ClOrdID, new_id);
|
|
order_cancel.set(OnixS::FIX::FIX42::Tags::OrigClOrdID, id)
|
|
.set(OnixS::FIX::FIX42::Tags::Side, translateSide(msg.side))
|
|
.set(
|
|
OnixS::FIX::FIX42::Tags::TransactTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
if (msg.security->has_option()) {
|
|
parse_option(order_cancel, *msg.security);
|
|
} else {
|
|
order_cancel
|
|
.set(OnixS::FIX::FIX42::Tags::Symbol, msg.security->symbol())
|
|
.set(OnixS::FIX::FIX42::Tags::Currency, msg.security->currency());
|
|
}
|
|
std::string order_str = order_cancel.toString('|');
|
|
LOG(OrderMan, Warn, "order_cancel Created: {}", order_str);
|
|
// order_cancel.validate(); fails becasuse of HandlInst
|
|
LOG(OrderMan, Warn, "order Validated");
|
|
order_cancel.set(OnixFIXAdapter::FIX_TAG_SMART_ROUTING, "SMART").set(
|
|
OnixS::FIX::FIX42::Tags::SendingTime,
|
|
OnixS::FIX::Timestamp::utc(),
|
|
OnixS::FIX::TimestampFormat::YYYYMMDDHHMMSSMsec);
|
|
state_handler->cancelOrder(msg, new_id);
|
|
session->send(&order_cancel);
|
|
LOG(OrderMan, Warn, "order cancel sent");
|
|
|
|
}
|
|
// Shut down all reactors if they exist.
|
|
catch (const OnixS::FIX::Exception &ex) {
|
|
const std::string err = ex.what();
|
|
handleException("Cacnel order", err);
|
|
}
|
|
}
|
|
} // namespace bts::orderman
|