13#include <slick/logger.hpp>
14#include <nlohmann/json.hpp>
19#include <unordered_map>
35 const char*
name()
const override {
return name_.c_str(); }
36 const char*
version()
const override {
return version_.c_str(); }
48 slick::queue<uint8_t>& order_request_queue
50 LOG_INFO(
"Strategy {}: Initializing", name_);
51 position_tracker_ = &position_tracker;
52 pnl_calculator_ = &pnl_calculator;
53 risk_manager_ = &risk_manager;
54 order_request_queue_ = &order_request_queue;
55 config_params_ = config;
61 if (!running_.load(std::memory_order_relaxed)) {
62 LOG_INFO(
"Strategy {}: Starting", name_);
63 running_.store(
true, std::memory_order_release);
69 if(running_.load(std::memory_order_relaxed)) {
70 LOG_INFO(
"Strategy {}: Stopping", name_);
72 running_.store(
false, std::memory_order_release);
78 LOG_INFO(
"Strategy {}: Shutting down", name_);
89 config_params_ = params;
96 void on_order_book(std::string_view ,
const slick::orderbook::OrderBookL2& )
override {}
101 const std::string order_id(event.
order_id);
107 LOG_DEBUG(
"Strategy {}: ignoring ACK for foreign order client_order_id={} order_id={}",
108 name_, client_id, order_id);
112 LOG_INFO(
"Strategy {}: on_order_ack client_order_id={} order_id={}", name_, client_id, order_id);
115 if (client_id.empty()) {
116 LOG_DEBUG(
"Strategy {}: ignoring ACK with empty client_order_id for order_id={}", name_, order_id);
120 auto it = orders_by_client_id_.find(client_id);
121 if (it == orders_by_client_id_.end()) {
124 LOG_INFO(
"Strategy {}: ACK for unknown client_order_id={} - inserting new entry", name_, client_id);
130 order.
side =
event.side;
131 order.
type =
event.order_type;
133 order.
price =
event.price;
135 order.
qty =
event.quantity;
137 order.
status =
event.status;
141 order_id_to_client_id_[order.
order_id] = client_id;
142 orders_by_client_id_.emplace(client_id, std::move(order));
146 LOG_INFO(
"Strategy {}: ACK updating existing entry client_order_id={} order_id={}", name_, client_id, order_id);
147 it->second.order_id = order_id;
148 it->second.status =
event.status;
149 it->second.price =
event.price;
150 it->second.stop_price =
event.stop_price;
151 it->second.qty =
event.quantity;
152 it->second.remaining_qty =
event.quantity;
153 it->second.time_in_force =
event.time_in_force;
154 it->second.post_only =
event.post_only;
155 it->second.last_update_time =
event.timestamp_ns;
156 order_id_to_client_id_[it->second.order_id] = client_id;
164 const std::string order_id(event.
order_id);
165 auto cid_it = order_id_to_client_id_.find(order_id);
169 if (cid_it == order_id_to_client_id_.end() && !
owns_order(client_id, order_id)) {
171 LOG_DEBUG(
"Strategy {}: ignoring fill for foreign order_id={}", name_, order_id);
175 LOG_INFO(
"Strategy {}: on_order_fill order_id={} qty={} price={} side={}",
182 position_tracker_->on_fill(name_, event);
187 auto order_it = orders_by_client_id_.find(cid_it != order_id_to_client_id_.end() ? cid_it->second : client_id);
188 if (order_it != orders_by_client_id_.end()) {
189 auto& order = order_it->second;
190 const qty_t new_filled = order.filled_qty +
event.fill_quantity;
191 if (new_filled > 0) {
197 order.filled_qty = new_filled;
198 order.remaining_qty =
event.remaining_quantity;
199 order.last_update_time =
event.timestamp_ns;
200 order.status = (order.remaining_qty == 0)
204 LOG_INFO(
"Strategy {}: fill for client_order_id={}, an order not tracked since a restart - booked",
209 position_tracker_->on_fill(name_, event);
216 const std::string order_id(event.
order_id);
218 LOG_DEBUG(
"Strategy {}: ignoring reject for foreign order client_order_id={} order_id={}",
219 name_, client_id, order_id);
222 auto it = orders_by_client_id_.find(client_id);
223 if (it != orders_by_client_id_.end()) {
225 it->second.last_update_time =
event.timestamp_ns;
232 const std::string order_id(event.
order_id);
234 LOG_DEBUG(
"Strategy {}: ignoring cancel for foreign order client_order_id={} order_id={}",
235 name_, client_id, order_id);
238 auto cid_it = order_id_to_client_id_.find(order_id);
239 if (cid_it != order_id_to_client_id_.end()) {
240 auto& order = orders_by_client_id_.at(cid_it->second);
242 order.remaining_qty =
event.remaining_quantity;
243 order.last_update_time =
event.timestamp_ns;
288 return client_order_id.size() > name_.size() + 1
289 && client_order_id.starts_with(name_)
290 && client_order_id[name_.size()] ==
'_';
298 bool owns_order(
const std::string& client_order_id,
const std::string& order_id)
const {
299 if (!client_order_id.empty()) {
300 return orders_by_client_id_.contains(client_order_id)
303 return !order_id.empty() && order_id_to_client_id_.contains(order_id);
319 instrument_broker_map_[std::string(instrument)] = broker_id;
322 std::string reject_reason;
323 if (!risk_manager_->validate_order(name_, instrument, side, quantity, price, &reject_reason)) {
324 LOG_WARN(
"Strategy {}: Order {} REJECTED by risk: {}",
325 name_, client_order_id, reject_reason);
335 *refusal = std::move(reject_reason);
369 pending.instrument = std::string(instrument);
370 pending.broker_id = broker_id;
373 pending.price = price;
374 pending.qty = quantity;
375 pending.remaining_qty = quantity;
376 pending.time_in_force = tif;
377 pending.post_only = post_only;
380 pending.last_update_time = pending.created_time;
381 orders_by_client_id_.emplace(client_order_id, std::move(pending));
383 LOG_DEBUG(
"Strategy {}: Submitted order {} for {} {}@{}",
384 name_, client_order_id, instrument,
386 return client_order_id;
389 void cancel_order(
const std::string& order_id,
const std::string& client_order_id) {
390 const auto it = orders_by_client_id_.find(client_order_id);
394 if (it != orders_by_client_id_.end()) {
397 ev.
side = it->second.side;
402 LOG_DEBUG(
"Strategy {}: Cancelled order {}", name_, order_id);
408 for (
const auto& [cid, order] : orders_by_client_id_) {
432 LOG_INFO(
"Strategy {}: Modify order {} new_price={} new_qty={}",
440 auto it = orders_by_client_id_.find(client_order_id);
441 if (it != orders_by_client_id_.end()) [[likely]] {
442 modify_order(it->second, new_price, new_quantity, new_stop_price);
452 const auto positions = position_tracker_->get_all_positions(name_);
453 for (
const auto& [instrument, pos] : positions) {
454 if (pos.is_flat())
continue;
456 auto broker_it = instrument_broker_map_.find(instrument);
457 if (broker_it == instrument_broker_map_.end()) {
458 LOG_WARN(
"Strategy {}: Cannot close position for {} — no broker mapping known",
465 const qty_t close_qty = pos.is_long() ? pos.quantity : -pos.quantity;
468 price_t ref_price = pos.avg_price;
469 if (pnl_calculator_->has_mark_price(instrument)) {
470 ref_price = pnl_calculator_->get_mark_price(instrument);
475 const price_t close_price = pos.is_long()
479 const BrokerId broker_id = broker_it->second;
482 LOG_WARN(
"Strategy {}: Emergency close {} qty={} limit@{} (ref={})",
492 order.
side = close_side;
494 order.
price = close_price;
503 pending.instrument = instrument;
504 pending.broker_id = broker_id;
505 pending.side = close_side;
507 pending.price = close_price;
508 pending.qty = close_qty;
509 pending.remaining_qty = close_qty;
511 pending.post_only =
false;
514 pending.last_update_time = pending.created_time;
515 orders_by_client_id_.emplace(client_order_id, std::move(pending));
520 const std::unordered_map<std::string, Order>&
get_orders()
const {
521 return orders_by_client_id_;
526 auto it = orders_by_client_id_.find(client_order_id);
527 return it != orders_by_client_id_.end() ? &it->second :
nullptr;
534 const std::string& client_order_id)
const {
541 auto it = order_id_to_client_id_.find(order_id);
542 if (it == order_id_to_client_id_.end())
return nullptr;
543 auto oit = orders_by_client_id_.find(it->second);
544 return oit != orders_by_client_id_.end() ? &oit->second :
nullptr;
549 std::vector<const Order*> result;
550 for (
const auto& [cid, order] : orders_by_client_id_) {
551 if (order.is_open()) result.push_back(&order);
558 for (
auto it = orders_by_client_id_.begin(); it != orders_by_client_id_.end(); ) {
559 if (it->second.is_done()) {
560 order_id_to_client_id_.erase(it->second.order_id);
561 it = orders_by_client_id_.erase(it);
568 bool is_running()
const {
return running_.load(std::memory_order_acquire); }
570 const std::string&
get_name()
const {
return name_; }
575 if (config_params_.contains(key)) {
577 return config_params_[key].get<T>();
578 }
catch (
const std::exception&) {
579 return default_value;
582 return default_value;
585 const nlohmann::json&
get_config()
const {
return config_params_; }
594 std::string version_;
595 std::atomic_bool running_{
false};
596 slick::queue<uint8_t>* order_request_queue_{
nullptr};
599 nlohmann::json config_params_;
602 PositionTracker* position_tracker_{
nullptr};
603 PnLCalculator* pnl_calculator_{
nullptr};
604 RiskManager* risk_manager_{
nullptr};
607 std::unordered_map<std::string, Order> orders_by_client_id_;
608 std::unordered_map<std::string, std::string> order_id_to_client_id_;
611 std::unordered_map<std::string, BrokerId> instrument_broker_map_;
static BrokerStatusRegistry & instance()
static bool publish(slick::SlickQueue< uint8_t > &queue, uint32_t size, populate_event_fn &&populate_event_func)
void modify_order(Order &order, price_t new_price, qty_t new_quantity, price_t new_stop_price=NULL_PRICE)
bool initialize(const json &config, PositionTracker &position_tracker, PnLCalculator &pnl_calculator, RiskManager &risk_manager, slick::queue< uint8_t > &order_request_queue) override
const char * name() const override
virtual bool owns_client_order_id(std::string_view client_order_id) const
void on_order_fill(const OrderFillEvent &event) override
void on_order_ack(const OrderAckEvent &event) override
const char * version() const override
void on_order_reject(const OrderRejectEvent &event) override
const nlohmann::json & get_config() const
const Order * get_order_by_id(const std::string &order_id) const
virtual void on_config(const nlohmann::json ¶ms)
PositionTracker * get_position_tracker()
RiskManager * get_risk_manager()
void on_quote(const QuoteEvent &event) override
void on_trade(const TradeEvent &event) override
const std::string & get_name() const
void close_all_positions()
void on_order_book(std::string_view, const slick::orderbook::OrderBookL2 &) override
const Order * get_order(const std::string &client_order_id) const
StrategyBase(const std::string &name, const std::string &version)
friend class StrategyManager
PnLCalculator * get_pnl_calculator()
std::vector< SubscriptionRequest > get_subscriptions() const override
T get_parameter(const std::string &key, const T &default_value) const
virtual void on_shutdown()
void cancel_order(const std::string &order_id, const std::string &client_order_id)
virtual void on_leg_fill(const OrderFillEvent &event)
void on_order_cancel(const OrderCancelEvent &event) override
virtual std::string generate_order_id()
void modify_order(const std::string &client_order_id, price_t new_price, qty_t new_quantity, price_t new_stop_price=NULL_PRICE)
const std::unordered_map< std::string, Order > & get_orders() const
std::string submit_order(std::string_view instrument, BrokerId broker_id, Side side, qty_t quantity, OrderType type, price_t price=NULL_PRICE, TimeInForce tif=TimeInForce::FOK, bool post_only=true, std::string *refusal=nullptr)
bool owns_order(const std::string &client_order_id, const std::string &order_id) const
std::optional< QueuePosition > get_queue_position(const slick::orderbook::OrderBookL3 &book, const std::string &client_order_id) const
virtual void on_ack(const OrderAckEvent &event)
virtual ~StrategyBase() override=default
void set_config(const nlohmann::json ¶ms)
virtual void on_cancel(const OrderCancelEvent &event)
virtual void on_fill(const OrderFillEvent &event)
virtual void on_reject(const OrderRejectEvent &event)
virtual bool on_initialize()
std::vector< const Order * > get_open_orders() const
double from_price_t(price_t value)
price_t to_price_t(double value)
uint64_t get_timestamp_ns()
constexpr price_t NULL_PRICE
std::optional< QueuePosition > queue_position(const slick::orderbook::OrderBookL3 &book, slick::orderbook::OrderId order_id) noexcept
double from_qty_t(qty_t value)
char instrument[MAX_INSTRUMENT_LENGTH]
void set_instrument(std::string_view instr)
TimeInForce new_time_in_force
TimeInForce time_in_force
void set_client_order_id(std::string_view id)
char order_id[MAX_ORDER_ID_LENGTH]
void set_order_id(std::string_view id)
void set_reason(std::string_view r)
std::string client_order_id
uint64_t last_update_time
TimeInForce time_in_force