Deribit orders (mostly) work

This commit is contained in:
taha afzal committed 2022-03-31 14:34:29 -04:00
1 parent 32c4d05106
commit 64240c5f3b
15 files changed
+889 -327

No files matched your search

+264 -244
View File
@@ -28,6 +28,7 @@
#include "lib/utils/bts_chrono.h"
#include "server/sparkd/md/platforms/emumba/EmMDListener.h"
#include <algorithm>
#include <bits/stdint-uintn.h>
#include <string>
#include <sys/time.h>
@@ -79,7 +80,7 @@ struct EMNativeOrder::PImpl {
: services(nullptr), session_services(), sec(nullptr),
previous_working_position(0), definition(), state(),
exchange_order_id() {}
bool inited = false;
OrderServices *services;
SessionServices *session_services;
@@ -97,7 +98,6 @@ struct EMNativeOrder::PImpl {
bool buffered_cancel = false;
std::optional<api::orderman::Update> buffered_update;
RoutingRecord routing_record;
bool stop_order_still_has_stop_px = true;
};
EMNativeOrder::EMNativeOrder() : me(new PImpl()) {}
@@ -108,22 +108,30 @@ api::orderman::OrderDefinition const &EMNativeOrder::definition() const {
return me->definition;
}
// Construction, the order is not yet live and it may never
// be. This can be slow. This is the first call
void EMNativeOrder::on_init_new(
api::orderman::OrderDefinition const &def,
const PreActivationOrderServices &serv) {
bts_assert(!me->inited);
me->inited = true;
LOG(OrderMan, Info,
"EMNativeOrder::on_init_new key: {} sec_key: {} user: {} account: {}",
key(), def.security_key(), def.user(), def.account());
me->definition = def;
me->sec = serv.sec_db.resolve(SecurityKey(def.security_key()));
// Check for invariants, if not met, reject the order
// 1. Sec can be resolved
// 2. Order is either Limit or Market
// 3. Routing Record can be constructed (serv.order_router.get_routing_record
// returns a valid record)
// Else, transition to ORDER_STATUS_INACTIVE, and set native strate
if (!me->sec) {
auto msg = fmt::format("Unknown security: {}", def.security_key());
me->state.set_last_msg(msg);
transition(ORDER_STATUS_REJECTED_BY_SPARK, msg);
return;
}
switch (def.custom_def().custom_case()) {
case CustomOrderDefinition::kMarket:
me->state.mutable_market();
@@ -131,16 +139,12 @@ void EMNativeOrder::on_init_new(
case CustomOrderDefinition::kLimit:
me->state.mutable_limit();
break;
case CustomOrderDefinition::kStop:
case CustomOrderDefinition::kStopLimit: {
default: {
auto msg = "Order type not supported at this venue";
me->state.set_last_msg(msg);
me->state.set_last_msg("Order type not supported at this venue");
transition(ORDER_STATUS_REJECTED_BY_SPARK, msg);
return;
}
default:
bts_assert(false);
break;
}
auto rq = serv.order_router.get_routing_record(
UserID(def.user_id()), AccountID(def.account_id()), *me->sec);
@@ -151,34 +155,32 @@ void EMNativeOrder::on_init_new(
transition(ORDER_STATUS_REJECTED_BY_SPARK, msg);
return;
}
// this is the initial state the order starts with
// Successful order always starts in ORDER_STATUS_INACTIVE
transition(ORDER_STATUS_INACTIVE);
auto &native_state = get_native_state(me->state);
me->routing_record = rq.routing_record;
*native_state.mutable_routing_record() = rq.routing_record;
LOG(OrderMan, Info, "EMNativeOrder::on_init_new routing_record: {}",
utils::pb::to_string(me->routing_record));
LOG(OrderMan, Info, "EMNativeOrder::on_init_new key: {} routing_record: {}",
key(), utils::pb::to_string(me->routing_record));
}
void EMNativeOrder::on_init_recovered(
api::orderman::OrderRecord const &rec,
const PreActivationOrderServices &serv) {
bts_assert(!me->inited);
me->inited = true;
auto const &def = rec.def();
me->definition = def;
me->state = rec.state();
me->sec = serv.sec_db.resolve(SecurityKey(def.security_key()));
me->previous_working_position = Quantity(0);
transition(
OrderStatus::ORDER_STATUS_COMPLETED, "Recoveredorders are not handled");
transition_to_error(
NativeOrderState::SUB_ERROR_UNKNOWN_SECURITY,
"EMNativeOrder - Not handling recovery yet");
OrderStatus::ORDER_STATUS_ERROR, "Recovered Orders are not handled");
}
OrderOpResult EMNativeOrder::on_activate(
Price p, Quantity q, OrderServices &services) {
bts_assert(me->inited);
LOG(OrderMan, Info, "EMNativeOrder::on_activate key: {} p: {} q: {}", key(),
p, q);
bts_assert(!me->services);
@@ -188,41 +190,31 @@ OrderOpResult EMNativeOrder::on_activate(
case ORDER_STATUS_INACTIVE: {
// this is a brand new order
// _on_activate sets the price, quantity
result = _on_activate(Warn, Info, p, q, services);
if (result.ok()) {
CreateOrderMsg c_msg = {};
_create_create_msg(c_msg);
transition(ORDER_STATUS_PENDING_WORKING);
me->services->queue_order_msg(*me->session_services, c_msg);
me->services->governor(*me->session_services).record_sent();
me->state.set_status(ORDER_STATUS_PENDING_WORKING);
LOG(OrderMan, Info,
"EMNativeOrder::on_activate sent new order with key {} to gateway",
"EMNativeOrder::on_activate sent new order with key {} to "
"gateway",
key().value());
// Early return so we skip the expensive report_state()
// call. It is OK to spkip it because we are bound to report
// our state once the excange aknowledges the order.
// call. It is OK to skip it because we are bound to report
// our state once the excange acknowledges the order.
update_working_position();
return OrderOpResult{};
} else {
report_state();
return result;
}
// When the order fails its limits checks we fall through the
// switch to report the error state at the end of this function
break;
}
// all cases below are for orders recovered from disk, since on_init_new's
// success => ORDER_STATUS_INACTIVE
case ORDER_STATUS_WORKING:
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_PENDING_WORKING:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_CANCELED:
case ORDER_STATUS_ERROR:
break;
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
bts_assert(false);
// control will only reach here if on_init_new failed, or it was a recocered
// order, in which case we are already in a terminal state, hence nothing to
default:
break;
}
report_state();
@@ -241,32 +233,22 @@ OrderOpResult EMNativeOrder::on_update(Price p, Quantity q) {
OrderOpResult EMNativeOrder::on_update(api::orderman::Update const &update) {
LOG(OrderMan, Info, "EMNativeOrder on_update update key: {} update: {}",
key().value(), utils::pb::to_string(update));
auto p = Price(update.price());
auto q = Quantity(update.quantity());
auto new_p = Price(update.price());
auto new_q = Quantity(update.quantity());
LOG(OrderMan, Info, "EMNativeOrder on_update update key: {} p: {} q: {}",
key().value(), p, q);
auto scoped_log =
me->services->log_scope("NativeOrder::on_update", key().value());
key().value(), new_p, new_q);
auto result = OrderOpResult{};
// the only state where we consider an update is ORDER_STATUS_WORKING
switch (me->state.status()) {
case ORDER_STATUS_WORKING: {
auto previous_working_qty = 0;
if (me->state.quantity() > me->state.filled_quantity())
previous_working_qty =
me->state.quantity() - me->state.filled_quantity();
auto current_working_qty = 0;
if (q.value() > me->state.filled_quantity())
current_working_qty = q.value() - me->state.filled_quantity();
auto curr_working_qty = _working_qty();
auto potential_working_qty = 0;
if (new_q.value() > me->state.filled_quantity())
potential_working_qty = new_q.value() - me->state.filled_quantity();
auto lqr = me->services->limiter().can_update_order(
AccountID(me->definition.account_id()), *me->sec,
me->definition.side(), Quantity(previous_working_qty),
Quantity(current_working_qty));
me->definition.side(), Quantity(curr_working_qty),
Quantity(potential_working_qty));
// are we under the position limits?
if (!lqr.ok()) {
@@ -275,95 +257,32 @@ OrderOpResult EMNativeOrder::on_update(api::orderman::Update const &update) {
LOG(OrderMan, Error,
"Order update failed due to limit breach. Order: {} Msg: {}",
key().value(), lqr.error_msg);
ignore_or_cancel(msg, ORDER_ERROR_LIMIT_BREACH, &result);
break;
}
// are we under the messaging threshold?
if (!me->services->governor(*me->session_services).can_send()) {
LOG(OrderMan, Warn,
"Cannot update order {} because of messaging limits. ",
key().value());
auto msg = "Messaging threshold breached";
ignore_or_cancel(msg, ORDER_ERROR_MESSAGING_LIMIT_BREACH, &result);
break;
}
// if (update.has_custom()) {
// bts_assert(
// update.custom().custom_case() ==
// me->definition.custom_def().custom_case());
// if (update.custom().custom_case() == CustomOrderDefinition::kStop) {
// // Stop orders do not have prices until they are triggered
// if (!stop_order_has_been_triggered()) {
// auto const &stop = update.custom().stop();
// auto stop_px = Price(stop.stop_price());
// me->definition.mutable_custom_def()
// ->mutable_stop()
// ->set_stop_price(stop_px.value());
// me->services->report_definition(me->definition);
// me->encoder->update_cancel_replace_stop_px(
// stop_px, me->price_encoding_precision);
// }
// } else if (
// update.custom().custom_case() ==
// CustomOrderDefinition::CustomOrderDefinition::kStopLimit) {
// if (!stop_order_has_been_triggered()) {
// auto const &stop_limit = update.custom().stop_limit();
// auto stop_px = Price(stop_limit.stop_price());
// me->definition.mutable_custom_def()
// ->mutable_stop_limit()
// ->set_stop_price(stop_px.value());
// me->services->report_definition(me->definition);
// me->encoder->update_cancel_replace_stop_px(
// stop_px, me->price_encoding_precision);
// }
// } else if (
// update.custom().custom_case() ==
// CustomOrderDefinition::kGlbxIceberg) {
// // GLBX Iceberg
// auto const &ib = update.custom().glbx_iceberg();
// if (ib.max_show_quantity() == 0 ||
// ib.max_show_quantity() > pow(10, max_show_sz()) - 1) {
// auto msg = fmt::format(
// "Invalid max show size: {}", ib.max_show_quantity());
// ignore_or_cancel(msg, ORDER_ERROR_INVALID_PARAMETER, &result);
// break;
// }
// me->encoder->update_cancel_replace_max_show(
// Quantity(ib.max_show_quantity()));
// }
// }
// All good
// if (is_stop_limit_order() || !is_stop_order() ||
// stop_order_has_been_triggered()) {
// // Stop orders become limit orders when triggered
// me->encoder->update_cancel_replace_encoding(
// p, me->price_encoding_precision, *me->services);
// }
CancelReplaceOrderMsg cxlr_msg = {};
_create_create_msg(cxlr_msg.create_fields);
cxlr_msg.create_fields.price = p;
cxlr_msg.create_fields.quantity = q;
me->services->queue_order_msg(*me->session_services, cxlr_msg);
CancelReplaceOrderMsg cxl_repl_msg = {};
_create_create_msg(cxl_repl_msg.create_fields);
cxl_repl_msg.create_fields.price = new_p;
cxl_repl_msg.create_fields.quantity = new_q;
me->services->queue_order_msg(*me->session_services, cxl_repl_msg);
me->services->governor(*me->session_services).record_sent();
update_working_position();
if (me->state.last_msg().size())
me->state.set_last_msg("");
// early return so we skip report_state (for speed)
// early return so we skip report_state (for speed) (an execution report
// should take care of it?)
return OrderOpResult{};
}
// the 2 other working states
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_PENDING_WORKING:
LOG(OrderMan, Warn,
@@ -371,12 +290,12 @@ OrderOpResult EMNativeOrder::on_update(api::orderman::Update const &update) {
key().value(), update.quantity(), update.price());
me->buffered_update.emplace(update);
break;
// terminal states, nothing to do
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_CANCELED:
case ORDER_STATUS_ERROR:
break;
case ORDER_STATUS_INACTIVE:
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
@@ -392,9 +311,8 @@ OrderOpResult EMNativeOrder::on_detach() { return {}; }
OrderOpResult EMNativeOrder::on_cancel() {
LOG(OrderMan, Info, "EMNativeOrder::on_cancel key: {}", key());
auto result = OrderOpResult{};
switch (me->state.status()) {
// the only state where a cancel is sent out
case ORDER_STATUS_WORKING: {
// TODO, CancelOrderMsg is not completely filled
CancelOrderMsg cxl_msg = {};
@@ -403,13 +321,12 @@ OrderOpResult EMNativeOrder::on_cancel() {
me->services->queue_order_msg(*me->session_services, cxl_msg);
break;
}
// already in a terminal state, nothing to do
case ORDER_STATUS_CANCELED:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_ERROR:
break;
case ORDER_STATUS_PENDING_WORKING: {
// we buffer this, and as soon as we get the exchnage id, we cxl it
me->buffered_cancel = true;
@@ -419,7 +336,6 @@ OrderOpResult EMNativeOrder::on_cancel() {
key().value());
break;
}
case ORDER_STATUS_DISCONNECTED: {
me->buffered_cancel = true;
LOG(OrderMan, Warn,
@@ -430,6 +346,7 @@ OrderOpResult EMNativeOrder::on_cancel() {
auto msg = "Order will be canceled when re-connected";
result.error = ORDER_ERROR_GATEWAY_NOT_READY;
result.error_msg = msg;
// to print the message
transition(me->state.status(), msg);
break;
}
@@ -441,16 +358,15 @@ OrderOpResult EMNativeOrder::on_cancel() {
}
report_state();
return result;
return {};
}
void EMNativeOrder::on_attached(api::orderman::OrderDefinition const &) {
// TODO
// do nothing
}
api::orderman::OrderDefinition EMNativeOrder::on_init_from_exe_report(
ExecutionReport const &, const PreActivationOrderServices &) {
// TODO
return me->definition;
}
@@ -518,9 +434,11 @@ void EMNativeOrder::update_working_position() {
key().value(), me->definition.security_key());
}
// Returns the open position for a working order. If there are fills,
// returns the difference
Quantity EMNativeOrder::working_position() {
switch (me->state.status()) {
// working
case ORDER_STATUS_WORKING:
case ORDER_STATUS_PENDING_WORKING:
case ORDER_STATUS_DISCONNECTED:
@@ -528,7 +446,7 @@ Quantity EMNativeOrder::working_position() {
return Quantity(me->state.quantity() - me->state.filled_quantity());
else
return Quantity(0);
// terminal
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_ERROR:
case ORDER_STATUS_COMPLETED:
@@ -556,6 +474,7 @@ OrderOpResult EMNativeOrder::_on_activate(
Price p,
Quantity q,
bts::orderman::OrderServices & /*order_services*/) {
// update state wrt price, qty, fills
me->state.set_price(p.value());
me->state.set_quantity(q.value());
me->state.set_filled_quantity(0);
@@ -566,12 +485,15 @@ OrderOpResult EMNativeOrder::_on_activate(
get_native_state(me->state).routing_record().session());
// TODO: just to get going
me->session_services = &me->services->get_session_services("sim");
// me->price_encoding_precision =
// me->services->price_encoding_precision(*me->session_services);
// is our gateway connected?
// TODO
if (false && _is_gateway_connected(me->session_services)) {
// Checks for the following:
// 1. Gateway connection
// 2. Risk (can_trade, clip, position)
// 3. Governor (orders/sec)
// If any of the above fail, it goes to terminal state
// (ORDER_STATUS_REJECTED_BY_SPARK) abd returns error
// Else, subscribes to service events (including execution report)
if (!_is_gateway_connected(me->session_services)) {
LOG(OrderMan, reject_level,
"Attempt to send order to a disconnected gateway. "
"Dropping order {}",
@@ -580,35 +502,39 @@ OrderOpResult EMNativeOrder::_on_activate(
transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg);
return OrderOpResult{ORDER_ERROR_GATEWAY_NOT_READY, msg};
}
// this is to skip risk limits for options
bool turn_risk_off = me->sec->has_option();
// the following consults the limiter
// can the user trade ?
auto lqr = me->services->limiter().can_trade(
UserID(me->definition.user_id()),
AccountID(me->definition.account_id()));
if (turn_risk_off) {
lqr.result = Limiter::LimiterErrorCode::OK;
}
if (!lqr.ok()) {
LOG(OrderMan, reject_level,
"Unauthorized order attempted. User: {} on "
"Account: {}. Msg: {} Order: {}. Dropping order",
me->definition.user(), me->definition.account(), lqr.error_msg,
key().value());
auto msg = fmt::format("Unauthorized order: {}", lqr.error_msg);
transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg);
return OrderOpResult{ORDER_ERROR_UNAUTHORIZED, msg};
}
// risk limits (clip size, position)
lqr = me->services->limiter().can_send_new_order(
AccountID(me->definition.account_id()), *me->sec, me->definition.side(),
q);
if (turn_risk_off) {
lqr.result = Limiter::LimiterErrorCode::OK;
}
if (!lqr.ok()) {
LOG(OrderMan, reject_level,
"New order would breach limit. User: {} Account: "
"{} Msg: {} Order: {}. Dropping order",
me->definition.user(), me->definition.account(), lqr.error_msg,
key().value());
auto msg = fmt::format("Order would breach limit: {}", lqr.error_msg);
transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg);
return OrderOpResult{ORDER_ERROR_LIMIT_BREACH, msg};
@@ -625,7 +551,6 @@ OrderOpResult EMNativeOrder::_on_activate(
return OrderOpResult(ORDER_ERROR_MESSAGING_LIMIT_BREACH, msg);
}
// if we are here we are good.
// subscribe to usefull events
// TODO
me->exe_report_sid = me->services->subscribe_to_exe_report(
@@ -638,15 +563,13 @@ OrderOpResult EMNativeOrder::_on_activate(
// *me->session_services,
// [this](auto const &gw) { this->on_gateway_status(gw); });
// me->encoder->update_create_order_encoding(
// p, me->price_encoding_precision, q, order_services);
LOG(OrderMan, Info, "EMNativeOrder::_on_activate sucessful key: {}", key());
return OrderOpResult{};
}
// OrderState's CustomOrderState has some OrderStates' corresponding to
// NativeOrder (ex MarketOrderState, LimitOrderState etc). Each of these special
// OrderState have NativeOrderState - this function plucks that out
// OrderStates have NativeOrderState - this function plucks that out
api::orderman::NativeOrderState &EMNativeOrder::get_native_state(
api::orderman::OrderState &st) {
switch (st.custom_case()) {
@@ -689,103 +612,187 @@ void EMNativeOrder::_create_create_msg(CreateOrderMsg &c) {
c.routing_record = &me->routing_record;
}
// void EMNativeOrder::_on_exe_report(const NewExecutionReportEvent &er) {
// LOG(OrderMan, Info, "EMNativeOrder::_on_exe_report key: {} er: {}", key(),
// er.data->to_string());
// auto &state = me->state;
// auto &native_state = get_native_state(state);
// // if we have a previous state we want to ensure this execution
// // report was not already considered.
// // TODO, just id the report in EMEG
// if (_is_old_exe_report(native_state, er)) {
// LOG(OrderMan, Info,
// "Ignoring already seen execution report {} in order {}",
// er.data->msg_seq_num, key().value());
// return;
// }
// // we do not care about spread leg fills for purposes of order
// // state maintenance
// if (er.data->leg_security) {
// LOG(OrderMan, Diag, "Ignoring leg execution report for order {}",
// key().value());
// return;
// }
// native_state.set_last_msg_seq_num(er.data->msg_seq_num);
// set_last_transact_time(er.data->transact_time, &native_state);
// auto external_status = em_map_external_status(er.data->order_status);
// // filled quantity is reset back to 0 when the order is canceled
// if (external_status != ORDER_STATUS_CANCELED) {
// if (er.data->exec_type == api::orderman::EXEC_TYPE_PARTIAL_FILL ||
// er.data->exec_type == api::orderman::EXEC_TYPE_FILL) {
// bts_assert(er.data->last_shares.value());
// auto previous_avg = state.avg_price();
// auto previous_sz = state.filled_quantity();
// auto fill_price = er.data->last_price.value();
// auto fill_sz = er.data->last_shares.value();
// auto new_avg =
// ((previous_avg * previous_sz) + (fill_price * fill_sz)) /
// (previous_sz + fill_sz);
// state.set_avg_price(new_avg);
// state.set_filled_quantity(er.data->filled_quantity.value());
// state.set_last_price(er.data->last_price.value());
// }
// }
// state.set_last_msg(er.data->msg);
// native_state.set_native_status(er.data->order_status);
// native_state.set_native_type(er.data->order_type);
// native_state.set_stop_px(er.data->stop_price.value());
// // The FIX message we send for updates has to change once a stop
// // order is triggered. Post triggering we no longer can update the
// // stop px. Instead the stop order turns into a regular limit
// // order, which means we can now update the actual price.
// // TODO: stop order
// // if (is_stop_order() && stop_order_has_been_triggered() &&
// // me->stop_order_still_has_stop_px) {
// // me->stop_order_still_has_stop_px = false;
// // init_encodings();
// // }
// // bool got_first_exchange_order_id = !has_exchange_order_id();
// // if (got_first_exchange_order_id) {
// // me->exchange_order_id = er.data->exchange_order_id;
// // set_exchange_order_id(me->exchange_order_id.value(), &native_state);
// // me->encoder->update_exchange_order_id(me->exchange_order_id.value());
// // }
// if (!is_terminal_state(me->state.status())) {
// state.set_price(er.data->price.value());
// state.set_quantity(er.data->quantity.value());
// }
// switch (me->state.status()) {
// // terminal states, nothing can change them
// case ORDER_STATUS_COMPLETED:
// case ORDER_STATUS_CANCELED:
// return;
// // receiving an execution report does does not mean
// // we are connected
// case ORDER_STATUS_DISCONNECTED:
// break;
// case ORDER_STATUS_PENDING_WORKING:
// if (external_status == ORDER_STATUS_WORKING &&
// !_is_gateway_connected(me->session_services))
// transition(ORDER_STATUS_DISCONNECTED);
// else {
// transition(external_status);
// if (external_status == ORDER_STATUS_WORKING) {
// if (me->buffered_cancel) {
// LOG(OrderMan, Warn,
// "Applying buffered cancel to order {}, on first ack",
// key().value());
// on_cancel();
// } else if (me->buffered_update.has_value()) {
// auto update = me->buffered_update.value();
// me->buffered_update.reset();
// LOG(OrderMan, Warn,
// "Applying buffered update ({}@{}) to order {}, on "
// "first ack",
// update.quantity(), update.price(), key().value());
// on_update(update);
// }
// }
// }
// break;
// case ORDER_STATUS_WORKING:
// transition(external_status);
// break;
// case ORDER_STATUS_INACTIVE:
// case ORDER_STATUS_ERROR:
// case ORDER_STATUS_REJECTED_BY_SPARK:
// case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
// case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
// bts_assert(false);
// break;
// }
// report_state();
// // we only need the exhange order id and the routing record
// // reported once, since they are both immutable, so we clear them
// // after their first report to make subsquent state updates faster
// // if (got_first_exchange_order_id) {
// // native_state.clear_exchange_order_id();
// // native_state.mutable_routing_record()->Clear();
// // }
// }
void EMNativeOrder::_on_exe_report(const NewExecutionReportEvent &er) {
LOG(OrderMan, Info, "EMNativeOrder::_on_exe_report key: {} er: {}", key(),
er.data->to_string());
auto scoped_log =
me->services->log_scope("NativeOrder::on_exe_report", key().value());
auto &state = me->state;
auto &native_state = get_native_state(state);
// if we have a previous state we want to ensure this execution
// report was not already considered.
if (_is_old_exe_report(native_state, er)) {
LOG(OrderMan, Info,
"Ignoring already seen execution report {} in order {}",
er.data->msg_seq_num, key().value());
return;
}
// we do not care about spread leg fills for purposes of order
// state maintenance
if (er.data->leg_security) {
LOG(OrderMan, Diag, "Ignoring leg execution report for order {}",
key().value());
return;
}
native_state.set_last_msg_seq_num(er.data->msg_seq_num);
set_last_transact_time(er.data->transact_time, &native_state);
auto external_status = em_map_external_status(er.data->order_status);
// filled quantity is reset back to 0 when the order is canceled
if (external_status != ORDER_STATUS_CANCELED) {
if (er.data->exec_type == api::orderman::EXEC_TYPE_PARTIAL_FILL ||
er.data->exec_type == api::orderman::EXEC_TYPE_FILL) {
bts_assert(er.data->last_shares.value());
auto previous_avg = state.avg_price();
auto previous_sz = state.filled_quantity();
auto fill_price = er.data->last_price.value();
auto fill_sz = er.data->last_shares.value();
auto new_avg =
((previous_avg * previous_sz) + (fill_price * fill_sz)) /
(previous_sz + fill_sz);
state.set_avg_price(new_avg);
state.set_filled_quantity(er.data->filled_quantity.value());
state.set_last_price(er.data->last_price.value());
}
}
state.set_last_msg(er.data->msg);
native_state.set_native_status(er.data->order_status);
native_state.set_native_type(er.data->order_type);
native_state.set_stop_px(er.data->stop_price.value());
// The FIX message we send for updates has to change once a stop
// order is triggered. Post triggering we no longer can update the
// stop px. Instead the stop order turns into a regular limit
// order, which means we can now update the actual price.
// TODO: stop order
// if (is_stop_order() && stop_order_has_been_triggered() &&
// me->stop_order_still_has_stop_px) {
// me->stop_order_still_has_stop_px = false;
// init_encodings();
// }
// bool got_first_exchange_order_id = !has_exchange_order_id();
// if (got_first_exchange_order_id) {
// me->exchange_order_id = er.data->exchange_order_id;
// set_exchange_order_id(me->exchange_order_id.value(), &native_state);
// me->encoder->update_exchange_order_id(me->exchange_order_id.value());
// }
if (!is_terminal_state(me->state.status())) {
state.set_price(er.data->price.value());
state.set_quantity(er.data->quantity.value());
}
switch (me->state.status()) {
// terminal states, nothing can change them
case api::orderman::ORDER_STATUS_INACTIVE:
// as soon an order is sent we get leave this state, so there is no way we
// should get an er while in this state
bts_assert(false);
break;
// terminal state already, nothing to do
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_CANCELED:
return;
// receiving an execution report does does not mean
// we are connected
case ORDER_STATUS_ERROR:
LOG(OrderMan, Error,
"Received er: {} for key: {} while in terminal state",
er.data->to_string(), key());
break;
// receiving an execution report does does not mean
// we are connected
case api::orderman::ORDER_STATUS_WORKING:
me->state.set_price(er.data->price.value());
me->state.set_quantity(er.data->quantity.value());
_absorb_fill(*er.data);
// this is where most of the action happens
transition(external_status);
break;
case ORDER_STATUS_DISCONNECTED:
// we only get out of this state via gw's connected event (not thorugh an
// order)
break;
case ORDER_STATUS_PENDING_WORKING:
if (external_status == ORDER_STATUS_WORKING &&
!_is_gateway_connected(me->session_services))
transition(ORDER_STATUS_DISCONNECTED);
else {
transition(external_status);
// deal with buffered operations
if (external_status == ORDER_STATUS_WORKING) {
if (me->buffered_cancel) {
LOG(OrderMan, Warn,
@@ -805,27 +812,18 @@ void EMNativeOrder::_on_exe_report(const NewExecutionReportEvent &er) {
}
break;
case ORDER_STATUS_WORKING:
transition(external_status);
break;
case ORDER_STATUS_INACTIVE:
case ORDER_STATUS_ERROR:
case ORDER_STATUS_REJECTED_BY_SPARK:
// it only gets rejected before the order is sent, so similiar to
// inactive, we should never get an er here
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
bts_assert(false);
break;
}
LOG(OrderMan, Info,
"EMNativeOrder::_on_exe_report calling report_state key: {} p: {} q: {}",
key(), me->state.price(), me->state.quantity());
report_state();
// we only need the exhange order id and the routing record
// reported once, since they are both immutable, so we clear them
// after their first report to make subsquent state updates faster
// if (got_first_exchange_order_id) {
// native_state.clear_exchange_order_id();
// native_state.mutable_routing_record()->Clear();
// }
}
bool EMNativeOrder::_is_old_exe_report(
@@ -893,5 +891,27 @@ void EMNativeOrder::ignore_or_cancel(
*out = {error, msg};
}
Quantity EMNativeOrder::_working_qty() const {
auto rv = Quantity(0);
if (me->state.quantity() > me->state.filled_quantity()) {
rv = Quantity(me->state.quantity() - me->state.filled_quantity());
}
return rv;
}
void EMNativeOrder::_absorb_fill(const ExecutionReport &er) {
if (me->state.filled_quantity() < er.filled_quantity.value()) {
// new fills
uint32_t last_fills =
er.filled_quantity.value() - me->state.filled_quantity();
double last_price = er.avg_price.value() * er.filled_quantity.value() -
me->state.avg_price() * me->state.filled_quantity();
last_price /= last_fills;
me->state.set_avg_price(er.avg_price.value());
me->state.set_filled_quantity(er.filled_quantity.value());
me->state.set_last_price(last_price);
}
}
} // namespace orderman
} // namespace bts