Compare commits

..
Author SHA1 Message Date
Pedro Pinto d8b8a5d710 Updated release notes. 2019-07-23 15:44:49 -04:00
Pedro Pinto 5536f5f585 Cover should always detach from hedges when completing. 2019-07-23 15:04:11 -04:00
Kevin Darby c8badf5689 Merged in fix_span_error_message (pull request #306)
guard against UI setting cash and leverage factors for accounts I don't know about when span is off

Approved-by: Pedro Pinto <pedro.pinto+atlassian@bluetradesys.com>
2019-07-17 14:51:23 +00:00
Kevin Darby 58533bf16f guard against UI setting cash and leverage factors for accounts I don't know about when span is off 2019-07-17 10:48:16 -04:00
Pedro Pinto 6b3c3ded68 Fixed up release notes. 2019-07-17 10:24:51 -04:00
Pedro Pinto d65e00fade Merged in SP-132-make-algo-shutdown-orderly (pull request #305)
RTM. SP-132 make algo shutdown orderly
2019-07-17 14:23:09 +00:00
Pedro Pinto 68e5d07aef Merge branch 'master' of bitbucket.org:bluetradesys/spark 2019-07-17 09:36:15 -04:00
Pedro Pinto 68345a181e Updated release notes. 2019-07-17 09:35:43 -04:00
Kevin Darby 69c121a19c Merged in fix_span (pull request #301)
fix crash where account name > 12 chars, tested with long account name

Approved-by: Pedro Pinto <pedro.pinto+atlassian@bluetradesys.com>
2019-07-17 13:32:33 +00:00
Pedro Pinto 780ce7416f Merge branch 'master' into SP-132-make-algo-shutdown-orderly 2019-07-17 09:07:54 -04:00
Pedro Pinto 9fe338a62a Updated release notes. 2019-07-17 09:07:24 -04:00
Jake Norbut f027af66c8 Merged in ob_price_filter_tick_comparison (pull request #304)
RTM - Ob price filter tick comparison

Approved-by: John Colvin <john.colvin@bluetradesys.com>
2019-07-16 21:43:23 +00:00
Jake Norbut 6b2708b160 PR suggestions 2019-07-16 16:34:59 -05:00
Jake Norbut 534474621f price filter should use new add_price tick-based method 2019-07-16 15:51:27 -05:00
Jake Norbut 554614ab72 add means to perform price comparsion based on tick equality 2019-07-16 15:50:44 -05:00
Pedro Pinto 2ede69a263 Updated release notes. 2019-07-16 16:21:31 -04:00
Pedro Pinto 9def94aceb Changed IB to cancel rather than error if it sees a child cancel.
This allows IB to remain agnostic of wheter the child cancel was a
simply a consequence of the IB itself shutting down, in which case it
would be ignored. If the IB instead errorred out than that error
superseeds the cancel and results in the IB reporting an error.
2019-07-16 15:55:28 -04:00
Pedro Pinto 0af30b3cc0 Changed cover to handle fills while canceling. 2019-07-16 15:32:38 -04:00
Pedro Pinto 481c1fd2de Fixed gcc build. 2019-07-16 10:29:59 -04:00
Pedro Pinto e80fc807e0 Moved all reporting state calls to top level event handler.
Any CPU the algo order receives must originate from a top level event,
its simpler to consolidate all report guards in those events, instead
of chasing every call that comes out of the algo.
2019-07-16 10:20:30 -04:00
Pedro Pinto c8e054d079 Added algo wrapper documentation. 2019-07-16 10:10:46 -04:00
Pedro Pinto 9480e76d4b Cleaned up algo wrapper 2019-07-16 10:10:11 -04:00
Pedro Pinto 538411353a Improved cover to hedge while shutting down. 2019-07-16 08:48:36 -04:00
Pedro Pinto da6998c391 Do not error out when receiving an udpate from an unknown child.
Because the child is presumably a detached child.
2019-07-15 16:43:39 -04:00
Pedro Pinto 60786b105c Handled terminate_error while shutting down. 2019-07-15 16:26:22 -04:00
Pedro Pinto f488248abf Fixed handling of child update while shutdown. 2019-07-15 16:03:36 -04:00
Pedro Pinto 830b590e5b Algos now go through an orderly shutdown phase.
During which they can still process child updates.
2019-07-15 10:59:13 -04:00
Kevin Darby 9e5d43f44a fix crash where account name > 12 chars, tested with long account name 2019-07-11 17:53:48 -04:00
72 changed files with 551 additions and 674 deletions

No files matched your search

+3 -3
View File
@@ -135,13 +135,13 @@
"name": "Spreader Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"args": [
"test",
"[spreader]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server",
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
@@ -288,7 +288,7 @@
"name": "SparkVM attach",
"type": "cppdbg",
"request": "attach",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"processId": "${command:pickRemoteProcess}",
"MIMode": "gdb",
"pipeTransport": {
+25 -1
View File
@@ -4,6 +4,30 @@ weight = 3
sort_by = "weight"
insert_anchor_links = "right"
+++
## 2.7.1
### User Visible Changes
- Fixed some issues with the Cover algo, where in some circumstances
it would erroneously cancel launched hedges on completion.
## 2.7.0
### User Visible Changes
- Allowed algos to process "in-flight" fills while shutting down
- Changed the cover algo to continue to hedge while shutting down
### API Changes
- Changed the API so that algos do not fully terminate until all
their children are terminated. Algos that are in the process of
shutting down in response to a complete or cancel call will still
receive child updates, which they can use to calculate and report
an accurate fill count (during this shutdown stage algos cannot
create, cancel or update children). A new IAlgoServices method,
is_shutting_down(), can be used to determine if an algo is
shutting down.
## 2.6.2
### User Visible Changes
- Fixed an issue in the ladder where in some cases the mini order book could not be brought up from a badge
- Fixed a rare race condition that could lead to erroneous limit enforcement
- Fixed an issue with the margin limits where an error could occur if an account name with more than 12 chars was used
## 2.6.1
### User Visible Changes
@@ -311,7 +335,7 @@ insert_anchor_links = "right"
- The zoom slider can be enabled from Ladder Form -> Settings button -> Left Pane tab -> check Zoom Slider checkbox
- The zoom functionality can also be performed via hotkey and mouse wheel combinations
- Zoom In = CTRL + Mouse wheel up
- Zoom Out = CTRL + Mouse wheel down
- Zoom Out = CTRL + Mouse wheel down␍
- Reset zoom = CTRL + Mouse wheel click or double click on the zoom slider
### Exchange simulator
- Improved the exchange simulator to track real market data more closely
@@ -144,7 +144,7 @@ namespace bts.shell.orderbook {
pb.add_discrete_values(fs.symbols, o => o.security?.Symbol);
// numeric
pb.add_numeric(fs.qty, o => o.order.quantity());
pb.add_numeric(fs.price, o => o.order.price());
pb.add_price(fs.price, o => o.order.price(), o => o.security);
pb.add_numeric(fs.qty_filled, o => o.order.filled());
pb.add_numeric(fs.avg_price, o => o.order.avg_price());
pb.add_numeric(fs.last_price, o => o.order.last_price());
@@ -37,6 +37,51 @@ namespace mbts.spark.filters {
_predicates.Add(impl);
bool impl(TRow o) => max.CompareTo(selector(o)) >= 0;
}
}
// this is a copy of add_numeric except we do a tick_equals comparsion
// if the ticks are not equals, then it falls back to a regular double comparison
//
// if the SecurityImmutable? doesn't have a value
// then we fallback to double comparison
public void add_price(DoubleMinMaxState value, Func<TRow, double> selector, Func<TRow, SecurityImmutable?> si_selector) {
if (value == null)
return;
if (value.minimum.active) {
var min = value.minimum.value.Value;
if (value.maximum.active) {
var max = value.maximum.value.Value;
_predicates.Add(impl);
bool impl(TRow o) {
var v = selector(o);
var si = si_selector(o);
if (si.HasValue) {
return si.Value.ContractSpec.compare_tick_fallback_to_double(min, v) <= 0 &&
si.Value.ContractSpec.compare_tick_fallback_to_double(max, v) >= 0;
}
return min.CompareTo(v) <= 0 && max.CompareTo(v) >= 0;
}
} else {
_predicates.Add(impl);
bool impl(TRow o) {
var si = si_selector(o);
if (si.HasValue) {
return si.Value.ContractSpec.compare_tick_fallback_to_double(min, selector(o)) <= 0;
}
return min.CompareTo(selector(o)) <= 0;
}
}
} else if (value.maximum.active) {
var max = value.maximum.value.Value;
_predicates.Add(impl);
bool impl(TRow o) {
var si = si_selector(o);
if (si.HasValue) {
return si.Value.ContractSpec.compare_tick_fallback_to_double(max, selector(o)) >= 0;
}
return max.CompareTo(selector(o)) >= 0;
}
}
}
public void add_regex(string str, Func<TRow, string> selector) {
@@ -128,6 +128,9 @@ namespace mbts.spark {
public static IEqualityComparer<double> tick_equality_comparer(this ContractSpecificationImmutable contract) =>
EqualityComparer.Create((double a, double b) => tick_equals(contract, a, b), x => MathUtils.RoundFractionalUnits(x, contract.LowTick));
public static int compare_tick_fallback_to_double(this ContractSpecificationImmutable contract, double x, double y) =>
tick_equals(contract, x, y) ? 0 : x.CompareTo(y);
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) {
double intpart = (long)value;
double floatpart = value % 1;
+1 -1
View File
@@ -108,7 +108,7 @@ where
session.session_start = event_view.session_start and
event_view.channel=trace.channel and event_view.sn=trace.sn and
event_type='hedge' and
entry_kind='NativeOrder::on_update' and
entry_kind='NativeOrder::on_activate' and
cor_event=0;
/* A view on requote events, identifying each order sent as part of the event*/
-8
View File
@@ -38,8 +38,6 @@ inline api::Side other_side(api::Side side) {
inline double market_epislon() { return 1e-10; }
// this tells which price is better from a market data
// standpoint, ie for buys the higher price is better
inline bool is_better(api::Side side, Price p1, Price p2) {
switch (side) {
case api::SIDE_BUY:
@@ -83,12 +81,6 @@ inline Price better_price (api::Side side, Price p1, Price p2){
return is_equal_or_better(side, p1, p2) ? p1 : p2;
}
// returns true if p1 is a better order price than p2
// ie lower when buying, higher when selling
inline bool same_or_better_order_price (api::Side side, Price p1, Price p2){
return is_equal_or_better(side, p2, p1);
}
inline Price decode_exchange_price(api::Security const &sec, Price in) {
return Price(in.value() * sec.contract_spec().price_multiplier());
}
+116 -20
View File
@@ -16,7 +16,13 @@ namespace orderman {
using namespace api::orderman;
template <class K, class V> using Map = boost::container::flat_map<K, V>;
enum class AlgoWrapperOrder::Status { INACTIVE, W_ATTACH, WORKING, COMPLETED };
enum class AlgoWrapperOrder::Status {
INACTIVE,
W_ATTACH,
WORKING,
SHUTTING_DOWN,
COMPLETED
};
class ChildTemplate {
public:
@@ -62,6 +68,7 @@ struct AlgoWrapperOrder::PImpl {
OrderKey attach_target = null_order_key();
std::optional<api::orderman::Update> pending_update;
std::optional<std::pair<OrderStatus, std::string>> pending_terminate;
OrderStatus external_status() const { return _state.status(); }
void set_external_status(OrderStatus s) {
@@ -222,6 +229,7 @@ OrderOpResult AlgoWrapperOrder::on_activate(Price p, Quantity q,
return {};
case Status::W_ATTACH:
case Status::SHUTTING_DOWN:
case Status::WORKING:
bts_assert(false);
}
@@ -238,6 +246,7 @@ OrderOpResult AlgoWrapperOrder::on_update(Update const &update) {
me->pending_update = update;
return {};
case Status::COMPLETED:
case Status::SHUTTING_DOWN:
return {};
case Status::WORKING: {
me->set_price_quantity(Price(update.price()),
@@ -275,6 +284,7 @@ orderman::OrderOpResult AlgoWrapperOrder::on_detach() {
switch (me->status) {
case Status::W_ATTACH:
case Status::WORKING:
case Status::SHUTTING_DOWN:
for (auto &[_, c] : me->children) {
(void)_;
c.order.mark_detached_from_parent();
@@ -309,6 +319,7 @@ orderman::OrderOpResult AlgoWrapperOrder::on_cancel() {
break;
}
break;
case Status::SHUTTING_DOWN:
case Status::COMPLETED:
break;
case Status::INACTIVE:
@@ -347,13 +358,20 @@ Quantity AlgoWrapperOrder::total_fills() const {
return Quantity(me->state().filled_quantity());
}
bool AlgoWrapperOrder::is_shutting_down() const {
return me->status == Status::SHUTTING_DOWN;
}
void AlgoWrapperOrder::subscribe_book(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->book_subs.find(k) == me->book_subs.end());
me->book_subs[k] = me->services->subscribe_to_book(
k, [this, k](auto const &ev) { me->algo->on_book(k, ev.book); });
k, [this, k](auto const &ev) {
ReportStateGuard _(*this);
me->algo->on_book(k, ev.book);
});
}
void AlgoWrapperOrder::unsubscribe_book(SecurityKey k) {
@@ -392,7 +410,10 @@ void AlgoWrapperOrder::subscribe_timer() {
bts_assert(!me->has_timer_sub);
me->has_timer_sub = true;
me->services->subscribe_to_time(
[this](auto const &) { me->algo->on_timer(); });
[this](auto const &) {
ReportStateGuard _(*this);
me->algo->on_timer();
});
}
void AlgoWrapperOrder::unsubscribe_timer() {
@@ -485,10 +506,9 @@ void AlgoWrapperOrder::detach_all_children() {
}
void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) {
if (!is_working())
if (!is_working() && !is_shutting_down())
return;
ReportStateGuard _(*this);
auto previous_qty = me->state().filled_quantity();
if (previous_qty > q.value()) {
LOG(OrderMan, Error,
@@ -510,35 +530,37 @@ void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) {
void AlgoWrapperOrder::set_ladder_visibility(bool is_visible) {
if (!is_working())
return;
ReportStateGuard _(*this);
me->set_ladder_visibility(is_visible);
}
void AlgoWrapperOrder::cancel(std::string const &msg) {
if (!is_working())
return;
ReportStateGuard _(*this);
terminate(ORDER_STATUS_CANCELED, msg);
if (working_children_count() == 0)
terminate(ORDER_STATUS_CANCELED, msg);
else
shutdown(ORDER_STATUS_CANCELED, msg);
}
void AlgoWrapperOrder::terminate_error(std::string const &msg) {
if (!is_working() && me->status != Status::W_ATTACH)
if (!is_working() && !is_shutting_down() && me->status != Status::W_ATTACH)
return;
ReportStateGuard _(*this);
// If we attached and an error was signaled we do not want to
// cancel our child because that child might be a long running
// order with a good queue position that we want to preserve
if (is_attaching())
me->children.erase(me->attach_target);
terminate(ORDER_STATUS_ERROR, msg);
}
void AlgoWrapperOrder::complete() {
if (!is_working())
return;
ReportStateGuard _(*this);
terminate(ORDER_STATUS_COMPLETED);
if (working_children_count() == 0)
terminate(ORDER_STATUS_COMPLETED);
else
shutdown(ORDER_STATUS_COMPLETED);
}
// --------------------------------------------------------------------------------
@@ -573,6 +595,7 @@ void AlgoWrapperOrder::on_attach_complete(
break;
case Status::COMPLETED:
break;
case Status::SHUTTING_DOWN:
case Status::INACTIVE:
case Status::WORKING:
bts_assert(false);
@@ -587,6 +610,7 @@ void AlgoWrapperOrder::on_child_order_update(
switch (me->status) {
case Status::WORKING:
case Status::W_ATTACH:
case Status::SHUTTING_DOWN:
if (auto it = me->children.find(child_key); it != me->children.end()) {
auto &child_record = it->second;
switch (new_child_state.status()) {
@@ -625,16 +649,38 @@ void AlgoWrapperOrder::on_child_order_update(
break;
}
} else
terminate_error(
fmt::format("Unknown child order update: {}", child_key.value()));
return;
LOG(OrderMan, Info,
"AlgoOrder {} received update for presumably detached order {}. "
"Ignoring it",
key().value(), child_key.value());
break;
case Status::COMPLETED:
return;
case Status::INACTIVE:
bts_assert(false);
return;
}
bts_assert(false);
if (me->status == Status::SHUTTING_DOWN)
try_complete_shutdown();
}
void AlgoWrapperOrder::try_complete_shutdown() {
bts_assert(me->status == Status::SHUTTING_DOWN);
bts_assert(me->children.size());
bts_assert(me->pending_terminate.has_value());
if (working_children_count() == 0) {
LOG(OrderMan, Info, "AlgoOrder {} completed shutdown. Terminated",
key().value());
terminate(me->pending_terminate.value().first,
me->pending_terminate.value().second);
} else {
LOG(OrderMan, Info,
"AlgoOrder {} still has {} orders working. Shutdown still in "
"progress",
key().value(), working_children_count());
}
}
void AlgoWrapperOrder::setup_transitions() {
@@ -676,8 +722,21 @@ void AlgoWrapperOrder::setup_transitions() {
// From WORKING
me->transition_actions[{Status::WORKING, Status::COMPLETED}] = [this]() {
cleanup();
me->children.clear();
_transition(Status::COMPLETED);
};
me->transition_actions[{Status::WORKING, Status::SHUTTING_DOWN}] = [this]() {
cleanup();
_transition(Status::SHUTTING_DOWN);
};
// From SHUTTING_DOWN
me->transition_actions[{Status::SHUTTING_DOWN, Status::COMPLETED}] =
[this]() {
me->children.clear();
me->pending_terminate.reset();
_transition(Status::COMPLETED);
};
}
void AlgoWrapperOrder::check_invariants() {
@@ -697,6 +756,7 @@ void AlgoWrapperOrder::check_invariants() {
bts_assert(me->book_subs.empty());
bts_assert(me->children.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_terminate.has_value());
break;
case Status::WORKING:
@@ -704,10 +764,23 @@ void AlgoWrapperOrder::check_invariants() {
bts_assert(me->security);
bts_assert(me->external_status() == ORDER_STATUS_WORKING);
bts_assert(!me->pending_update.has_value());
bts_assert(!me->pending_terminate.has_value());
break;
case Status::SHUTTING_DOWN:
bts_assert(working_children_count());
bts_assert(me->services);
bts_assert(me->security);
bts_assert(me->external_status() == ORDER_STATUS_WORKING);
bts_assert(me->book_subs.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_update.has_value());
bts_assert(me->pending_terminate.has_value());
break;
case Status::COMPLETED:
bts_assert(me->children.empty());
bts_assert(!me->pending_update.has_value());
bts_assert(me->external_status() == ORDER_STATUS_CANCELED ||
me->external_status() == ORDER_STATUS_COMPLETED ||
me->external_status() == ORDER_STATUS_ERROR ||
@@ -715,6 +788,7 @@ void AlgoWrapperOrder::check_invariants() {
bts_assert(me->book_subs.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_update.has_value());
bts_assert(!me->pending_terminate.has_value());
break;
}
}
@@ -745,15 +819,25 @@ void AlgoWrapperOrder::terminate(api::orderman::OrderStatus st,
transition(Status::COMPLETED);
}
void AlgoWrapperOrder::shutdown(api::orderman::OrderStatus st,
std::string const &error) {
bts_assert(!me->pending_terminate.has_value());
bts_assert(working_children_count());
me->pending_terminate = std::make_pair(st, error);
LOG(OrderMan, Info,
"AlgoOrder {} is shutting down. Waiting for {} child orders to complete "
"before terminating",
key().value(), working_children_count());
transition(Status::SHUTTING_DOWN);
}
void AlgoWrapperOrder::cleanup() {
for (auto const &s : me->book_subs) {
me->services->unsubscribe_from_book(s.second);
me->book_subs.clear();
}
for (auto &c : me->children) {
for (auto &c : me->children)
c.second.order.cancel();
me->children.clear();
}
if (me->has_timer_sub)
unsubscribe_timer();
me->pending_update.reset();
@@ -785,6 +869,16 @@ OrderKey AlgoWrapperOrder::index_and_launch_child(ChildOrder &&child, Price p,
return k;
}
size_t AlgoWrapperOrder::working_children_count() const {
auto working_children_count = 0;
for (auto &c : me->children)
if (!c.second.state.has_value() ||
c.second.state.value().status == ChildStatus::WORKING) {
working_children_count++;
}
return working_children_count;
}
bool AlgoWrapperOrder::is_working() const {
return me->status == Status::WORKING;
}
@@ -799,6 +893,8 @@ log::CharPtrWrapper AlgoWrapperOrder::state_name(Status st) {
return {"INACTIVE"};
case Status::WORKING:
return {"WORKING"};
case Status::SHUTTING_DOWN:
return {"SHUTTING_DOWN"};
}
bts_assert(false);
return {""};
@@ -40,6 +40,7 @@ class AlgoWrapperOrder : public Order,
Price price() const override;
Quantity quantity() const override;
Quantity total_fills() const override;
bool is_shutting_down() const override;
void subscribe_book(SecurityKey) override;
void unsubscribe_book(SecurityKey) override;
void subscribe_child_change(OrderKey) override;
@@ -75,10 +76,13 @@ class AlgoWrapperOrder : public Order,
void transition(Status);
void _transition(Status);
void terminate(api::orderman::OrderStatus, std::string const &error = "");
void shutdown(api::orderman::OrderStatus, std::string const &error = "");
void try_complete_shutdown();
void cleanup();
void update_child_record(api::orderman::OrderState const &, ChildRecord *);
OrderKey index_and_launch_child(ChildOrder &&, Price, Quantity, bool);
bool is_working() const ;
size_t working_children_count() const;
log::CharPtrWrapper state_name(Status) ;
ChildStatus map_child_status(api::orderman::OrderStatus) ;
bool _is_attaching(api::orderman::OrderDefinition const &) const ;
@@ -20,6 +20,13 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
// Returns the filled quantity for this algo
virtual Quantity total_fills() const = 0;
// Returns wheter the algo is in the process of shutting down (due
// to a cancel, an error, or just having completed its work). When
// algo is shutting down any requests to create, update or cancel
// child orders will be ignored.
virtual bool is_shutting_down() const = 0;
// --------------------------------------------------------------
// Event Subscriptions
// --------------------------------------------------------------
@@ -10,18 +10,8 @@ namespace orderman {
using namespace api::orderman;
enum class CoverAlgo::Status { WORKING, WAITING_FOR_HEDGES, DONE };
const char *CoverAlgo::status_name(Status st) {
switch (st) {
case Status::WORKING:
return "WORKING";
case Status::WAITING_FOR_HEDGES:
return "WAITING_FOR_HEDGES";
case Status::DONE:
return "Done";
}
return nullptr;
}
enum class CoverAlgo::Status { WORKING, WAITING_FOR_HEDGES, DONE, CANCELING };
struct CoverAlgo::PImpl {
IAlgoServices *algo;
OrderKey child_key = null_order_key();
@@ -92,8 +82,11 @@ void CoverAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k,
on_child_change(k, st);
}
void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
if (k == me->child_key) {
void CoverAlgo::on_covered_change(ChildState const &st) {
// First launch hedge if appropriate
switch (me->status) {
case Status::WORKING:
case Status::CANCELING:
if (st.total_fills.value() > me->hedged_fills.value()) {
auto hedge_qty =
Quantity(st.total_fills.value() - me->hedged_fills.value());
@@ -116,6 +109,15 @@ void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
hedge_qty.value(), hedge_price.value());
}
algo().update_fill_state(st.total_fills, st.last_price);
break;
case Status::WAITING_FOR_HEDGES:
case Status::DONE:
break;
}
// Now analyze child to figure out wheter we should terminate
switch (me->status) {
case Status::WORKING:
switch (st.status) {
case ChildStatus::WORKING:
break;
@@ -125,36 +127,67 @@ void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
algo().order_key().value());
algo().set_ladder_visibility(false);
me->status = Status::WAITING_FOR_HEDGES;
terminate_if_hedges_complete();
break;
case ChildStatus::CANCELED:
LOG(OrderMan, Info, "CoverAlgo {}. Child was canceled, terminating",
LOG(OrderMan, Info, "CoverAlgo {}. Child was unexpectadly canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
on_done();
algo().terminate_error("Unexpected child cancel");
break;
}
} else {
break;
case Status::CANCELING:
switch (st.status) {
case ChildStatus::WORKING:
break;
case ChildStatus::CANCELED:
if (me->cancel_on_external_hedge_cancel) {
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
algo().terminate_error("Unexpected child cancel");
} else
me->hedges.erase(
std::remove(me->hedges.begin(), me->hedges.end(), k),
me->hedges.end());
break;
case ChildStatus::COMPLETED:
me->hedges.erase(std::remove(me->hedges.begin(), me->hedges.end(), k),
me->hedges.end());
LOG(OrderMan, Info, "CoverAlgo {}. Shutdown complete",
algo().order_key().value());
on_done();
algo().cancel();
break;
}
break;
case Status::WAITING_FOR_HEDGES:
case Status::DONE:
break;
}
check_terminate();
}
void CoverAlgo::on_hedge_change(OrderKey k, ChildState const &st) {
// First adjust our hedge count or cancel if something went wrong
switch (st.status) {
case ChildStatus::WORKING:
break;
case ChildStatus::COMPLETED:
me->hedges.erase(std::remove(me->hedges.begin(), me->hedges.end(), k),
me->hedges.end());
break;
case ChildStatus::CANCELED:
if (me->cancel_on_external_hedge_cancel) {
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
on_done();
algo().terminate_error("Unexpected child cancel");
return;
} else
me->hedges.erase(std::remove(me->hedges.begin(), me->hedges.end(), k),
me->hedges.end());
break;
}
// Now if we are waiting for hedges to complete, bail
terminate_if_hedges_complete();
}
void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
if (k == me->child_key)
on_covered_change(st);
else
on_hedge_change(k, st);
}
void CoverAlgo::do_update(api::orderman::Update const &update) {
@@ -211,7 +244,7 @@ void CoverAlgo::update_definition(
cover.cancel_on_external_hedge_cancel();
}
void CoverAlgo::check_terminate() {
void CoverAlgo::terminate_if_hedges_complete() {
LOG(OrderMan, Diag,
"CoverAlgo {} check_terminate. State: {} Hedge count: {}",
algo().order_key(), log::CharPtrWrapper{status_name(me->status)},
@@ -220,15 +253,61 @@ void CoverAlgo::check_terminate() {
if (me->status == Status::WAITING_FOR_HEDGES && me->hedges.empty()) {
LOG(OrderMan, Info, "CoverAlgo {}. Last hedge completed, terminating",
algo().order_key().value());
on_done();
algo().complete();
}
}
IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
switch (me->status) {
case Status::WORKING: {
algo().cancel_child(me->child_key);
LOG(OrderMan, Info,
"CoverAlgo {} received cancel. Canceling child and waiting for an "
"ack",
algo().order_key());
me->status = Status::CANCELING;
return IAlgoOrder::OnCancelResponse::IGNORE;
}
case Status::CANCELING:
return IAlgoOrder::OnCancelResponse::IGNORE;
case Status::WAITING_FOR_HEDGES:
maybe_detach_hedges();
return IAlgoOrder::OnCancelResponse::HONOR;
case Status::DONE:
bts_assert(false);
return IAlgoOrder::OnCancelResponse::HONOR;
}
bts_assert(false);
return IAlgoOrder::OnCancelResponse::HONOR;
}
void CoverAlgo::on_done()
{
me->status = Status::DONE;
maybe_detach_hedges();
}
void CoverAlgo::maybe_detach_hedges() {
if (!me->cancel_hedges_on_cancel)
for (auto &k : me->hedges)
algo().detach_child(k);
return IAlgoOrder::OnCancelResponse::HONOR;
}
const char *CoverAlgo::status_name(Status st) {
switch (st) {
case Status::WORKING:
return "WORKING";
case Status::WAITING_FOR_HEDGES:
return "WAITING_FOR_HEDGES";
case Status::DONE:
return "DONE";
case Status::CANCELING:
return "CANCELING";
}
return nullptr;
}
} // namespace orderman
@@ -30,8 +30,13 @@ private:
api::orderman::CoverOrderDefinition const &);
void init_hedge_template(IBeforeLaunchAlgoServices &,
api::orderman::CustomOrderDefinition const &);
void check_terminate();
void terminate_if_hedges_complete();
void on_hedge_change(OrderKey hedge, ChildState const&) ;
void on_covered_change(ChildState const&);
const char *status_name(Status st);
void maybe_detach_hedges();
void on_done();
};
} // namespace orderman
@@ -145,7 +145,7 @@ void IcebergAlgo::on_child_change(OrderKey k, ChildState const &st) {
on_timer();
return;
case ChildStatus::CANCELED:
algo().terminate_error("Unexpected child cancel");
algo().cancel("Unexpected child cancel");
return;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@@ -0,0 +1,39 @@
#+TITLE: Algo Wrapper State Machien
#+OPTIONS: ^:nil
#+OPTIONS: H:2
#+OPTIONS: ^:nil H:2 author:nil creator:nil timestamp:nil toc:nil
#+OPTIONS: html-postamble:nil
* State Machine
#+begin_src dot :file algo_wrapper_sm.png :cmdline -Kdot -Tpng
digraph G {
bgcolor="transparent";
edge [ fontname=Helvetica, fontsize=12 ];
start [style=invisible];
COMPLETED [style=filled] ;
start -> INACTIVE;
INACTIVE -> COMPLETED [label="qty=0|error"];
INACTIVE -> W_ATTACH [label="ok & attach"];
INACTIVE -> WORKING [label="ok & !attach"];
W_ATTACH -> COMPLETED [label=attach_fail];
W_ATTACH -> WORKING [label=attach_ok];
WORKING -> COMPLETED [label="[wchild=0]cancel|complete"];
WORKING -> COMPLETED [label=error];
WORKING -> SHUTTING_DOWN [label="[wchild>0]cancel|complete"];
SHUTTING_DOWN -> COMPLETED [label="wchild==0|error|on_detach"];
}
#+END_SRC
#+RESULTS:
[[file:algo_wrapper_sm.png]]
* Invariants
| | attach_target | exernal_status | pending_update | pending_terminate | working_children | subs |
|---------------+---------------+--------------------------------------+----------------+-------------------+------------------+------|
| INACTIVE | | | | | | 0 |
| W_ATTACH | 1 | WORKING | | 0 | 0 | 0 |
| WORKING | | WORKING | 0 | 0 | | |
| SHUTTING_DOWN | | WORKING | 0 | 1 | >0 | 0 |
| COMPLETED | | CANCELED, COMPLETED, ERROR, REJECTED | 0 | 0 | 0 | 0 |
@@ -130,7 +130,7 @@ public:
for (auto& o : _orders){
// is_cancelled() is checked so as not to keep
// sending cancel requests
if(!o.cancel_sent()&&o.acknowledged()&&!o.terminal_status())
if(!o.is_cancelled()&&o.acknowledged()&&!o.terminal_status())
o.cancel_order();
}
}
@@ -118,12 +118,6 @@ ChildOrder SpreaderOrder::get_new_hedge_order(size_t leg_index){
bts::orderman::ChildOrder child_order = leg_data.hedger_order_builder().build();
return child_order;
}
void SpreaderOrder::send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order){
_send_hedge(hedge_leg_index, hedge_price, hedge_qty, use_quoting_order);
}
// events from orders system ////////////////////
/////////////////////////////////////////////////
void SpreaderOrder::_on_time(const bts::mercury::TimerEvent& t_event){
@@ -374,12 +368,10 @@ bool SpreaderOrder::_quoters_can_accept_modification (){
}
void SpreaderOrder::_send_hedge(size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order){
Quantity hedge_qty){
_bookkeeping_data().add_new_hedger (hedge_leg_index,
hedge_price,
hedge_qty,
use_quoting_order);
hedge_qty);
}
void SpreaderOrder::_compute_hedge_price_quantity(size_t filled_leg_index,
Price fill_price,
@@ -140,13 +140,10 @@ public:
}
void setup_new_quoter_order (size_t leg_index) override;
ChildOrder get_new_hedge_order (size_t leg_index) override;
void send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order = false) override;
inline bool in_cache_warming_cycle() const override{
return _cw_helper.in_cache_warming_cycle;
}
private:
// events from orders system ////////////////////
/////////////////////////////////////////////////
@@ -238,8 +235,7 @@ private:
// quantity 'filled_quantity'
void _send_hedge(size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order);
Quantity hedge_qty);
void _compute_hedge_price_quantity(size_t filled_leg_index,
Price filled_price,
double filled_quantity,
@@ -7,17 +7,12 @@ namespace orderman {
class LegPropertyData;
class CacheWarmingState;
class SpreaderChildOrderState;
// The Spreader spawns a bunch of quoters and
// hedgers and hands them this interface to
// i. get data such as book and leg properties
// (in O(1) access time)
// ii. create new quoter order
class ISpreaderManager{
public:
struct OrderTransfer{
SpreaderChildOrderState* q_order;
};
public:
virtual bts::orderman::OrderKey spreader_order_key() const = 0;
virtual bts::TimeStamp current_time() const = 0;
@@ -33,14 +28,6 @@ public:
// it does not alter the state or has side effects (as
// as the spreader goes)
virtual ChildOrder get_new_hedge_order (size_t leg_index) = 0;
// sends a new hedge for the leg index at a specified
// hedge price and size. when use_quoting_order is
// set to true the hegder is passed over the quoting
// order (and its state) to hedge
virtual void send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order) = 0;
// the spreader can be in a cache warming cycle and generate
// fake updates, the quoters and hedgers should ignore them
// (however do as much as they can to keep the instruction
@@ -35,9 +35,7 @@ public:
const bts::api::Security& security() const { return _leg_contract.security(); }
double price_multiplier() const { return _leg_contract.price_multiplier(); }
double size_multiplier() const { return _leg_contract.quantity(); }
double tick_size() const {
return _leg_contract.security().contract_spec().low_tick();
}
double tick_size() const { return _leg_contract.security().contract_spec().low_tick(); }
bool is_active_quoting() const {return _leg_params.is_active_quoting();}
bool is_net_change() const{
return _price_calc==bts::api::SyntheticContract::PRICECALC_NET_CHANGE;
@@ -58,9 +56,6 @@ public:
uint32_t n_queue_holder_orders() const{
return _leg_params.quote_params().n_queue_holder_orders();
}
bts::spark::UseSpreaderQuoteForHedging use_quote_for_hedging() const{
return _leg_params.quote_params().use_quote_for_hedging();
}
};
}}
@@ -83,9 +83,8 @@ _end_state_worker (this, other._end_state_worker){
/****************************External Calls**************************/
/********************************************************************/
void SingleFillHedger::init_hedger (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order){
_worker->init(price, quantity, order);
Quantity quantity){
_worker->init(price,quantity);
}
void SingleFillHedger::on_order_update(const SpreaderChildOrderState& u){
//bts_assert (u.order_key() == _order.order_key());
@@ -139,9 +138,7 @@ void SingleFillHedger::transform_to_WAITING_FOR_FIRST_ACK_CANCELLED () {
_switch_state (&_waiting_for_first_ack_cancelled_state_worker);
}
void SingleFillHedger::transform_to_WORKING() {
bts_assert(_worker->state() == HedgerState::WAITING_FOR_FIRST_ACK ||
// in case of quoting orders assigned to hedger
_worker->state() == HedgerState::START);
bts_assert(_worker->state() == HedgerState::WAITING_FOR_FIRST_ACK);
_switch_state (&_working_state_worker);
}
void SingleFillHedger::transform_to_WAITING_FOR_CANCEL_ACK(){
@@ -58,9 +58,6 @@ private:
void _modify_order (Price new_price){
_child_order_state.modify_order(new_price);
}
void _modify_order (Price new_price, Quantity qty){
_child_order_state.modify_order(new_price, qty);
}
void _cancel_order () {
_child_order_state.cancel_order();
}
@@ -96,9 +93,7 @@ public:
//that live in the START state until...
//iii.until init_hedger is called which sets the price
//qty and causes the order to be submitted
void init_hedger (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr);
void init_hedger (Price price, Quantity quantity);
//b. called by the spreader when there is an order update
// reported by the exchange
void on_order_update(const SpreaderChildOrderState& order_update_message);
@@ -112,17 +112,13 @@ void SingleLegQuoter::on_book(size_t leg_index,
_worker->on_book (leg_index, book);
}
void SingleLegQuoter::update_other_leg_fills(size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
Quantity filled_quantity){
bts_assert(_active_quoting);
if(hedge_qty.value()>0)
LOG(OrderMan, Info, "SingleLegQuoter::update_other_leg_fills "
"spread_key:{} leg_idx:{} fill_idx:{} filled_quantity:{}",
_spreader.spreader_order_key(), _this_leg_data.leg_index(),
leg_index, filled_quantity);
_worker->on_other_leg_quoter_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
LOG(OrderMan, Info, "SingleLegQuoter::update_other_leg_fills "
"spread_key:{} leg_idx:{} fill_idx:{} filled_quantity:{}",
_spreader.spreader_order_key(), _this_leg_data.leg_index(),
leg_index, filled_quantity);
_worker->on_other_leg_quoter_fill (leg_index, filled_quantity);
}
void SingleLegQuoter::update_order_price_quantity(Price price,
Quantity quantity){
@@ -165,18 +161,8 @@ bool SingleLegQuoter::accept_modifications() const {
return _worker->state() == QuoterState::WAITING_FOR_SIZE ||
_worker->state() == QuoterState::WORKING;
}
void SingleLegQuoter::_incorporate_other_leg_fill (size_t,
Quantity hedge_reduction,
Price hedge_price,
Quantity hedge_qty,
bool send_new_hedge,
bool use_quoting_order){
void SingleLegQuoter::_incorporate_other_leg_fill (size_t, Quantity hedge_reduction){
_price_quantity_state.add_hedged_reduction (hedge_reduction);
if(send_new_hedge)
_spreader.send_hedge_order(_this_leg_data.leg_index(),
hedge_price,
hedge_qty,
use_quoting_order);
}
void SingleLegQuoter::_compute_quote(
Quantity target_qty,
@@ -15,7 +15,6 @@
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForOrderTransferStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.h"
#include "lib/orderman/actors/order_manager/ChildOrder.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
@@ -36,7 +35,6 @@ friend QuoterWaitingForIOCWorker;
friend QuoterWaitingForFirstAckCancelledWorker;
friend QuoterWaitingForCancelAckStateWorker;
friend QuoterWorkingStateWorker;
friend QuoterWaitingForOrderTransferStateWorker;
friend QuoterEndStateWorker;
private:
const bool _two_legged;
@@ -117,9 +115,7 @@ public:
//g. this is called by the spreader when a quoting fill
// (ie not hedging fill) happens on one of the quoting
// legs
void update_other_leg_fills(size_t leg_index, Quantity filled_quantity,
Price hedge_price = Price(0),
Quantity hedge_qty = Quantity(0));
void update_other_leg_fills(size_t leg_index, Quantity filled_quantity);
//h. called when the user modified the spreader order price or quantity
void update_order_price_quantity(Price price, Quantity quantity);
// true if the quoter has an active working order. the order can
@@ -185,12 +181,7 @@ private:
}
void _cancel_order () {_child_order_state.cancel_order();}
// this updates the hedge reduction in _price_quantity_state
void _incorporate_other_leg_fill (size_t leg_index,
Quantity hedge_reduction,
Price hedge_price,
Quantity hedge_qty,
bool send_new_hedge = true,
bool use_quoting_order_to_hedge = false);
void _incorporate_other_leg_fill (size_t leg_index, Quantity hedge_reduction);
// given a target quoting qty
// this figures out the price and the actual
// qty that can be quoted.
@@ -103,16 +103,12 @@ public:
// and returns a ref to it
// (dont keep pointers to hedgers since the vector
// can resize)
inline SingleFillHedger& add_new_hedger(
size_t leg_index,
inline SingleFillHedger& add_new_hedger(size_t leg_index,
Price hedge_price,
Quantity hedge_quantity,
bool use_quoting_order = false){
Quantity hedge_quantity){
bts_assert(leg_index < _leg_data.size());
SpreaderLegData& leg_data=_leg_data[leg_index];
return leg_data.add_new_hedger(hedge_price,
hedge_quantity,
use_quoting_order);
return leg_data.add_new_hedger(hedge_price,hedge_quantity);
}
// finds the spreader fill, price (ie averages it out, using
// the size and price ratio, across all legs)
@@ -10,20 +10,18 @@ _is_live(src._is_live),
_sec_key(src._sec_key),
_is_quoting (src._is_quoting),
_test_only_order_key(src._test_only_order_key),
_base_price(src._base_price),
_base_quantity(src._base_quantity),
_n_place_orders(src._n_place_orders),
_n_cancel_orders(src._n_cancel_orders),
_n_modify_orders(src._n_modify_orders),
_base_price(src._base_price),
_base_quantity(src._base_quantity),
_child_order(std::move(src._child_order)),
_handover_filled_qty(Quantity(0)),
_status(src._status),
_filled_price(src._filled_price),
_filled_quantity(src._filled_quantity),
_last_update_filled_price(src._last_update_filled_price),
_last_update_filled_quantity(src._last_update_filled_quantity),
_last_filled_price(src._last_filled_price),
_last_reported_order_price(src._last_reported_order_price),
_last_reported_order_qty(src._last_reported_order_qty),
_last_filled_quantity(src._last_filled_quantity),
_out_price(src._out_price),
_out_quantity(src._out_quantity),
_order_place_time(src._order_place_time)
@@ -42,8 +40,7 @@ _base_quantity(0){
ChildOrder& empty_order=_empty_order();
re_init(empty_order);
}
void SpreaderChildOrderState::re_init (ChildOrder& child_order,
Quantity handover_filled_qty){
void SpreaderChildOrderState::re_init (ChildOrder& child_order){
SpreaderUtils::compute_average_price(_base_price, _base_quantity,
_filled_price, _filled_quantity,
_base_price, _base_quantity);
@@ -51,14 +48,12 @@ void SpreaderChildOrderState::re_init (ChildOrder& child_order,
_n_cancel_orders = _n_modify_orders = 0;
_child_order = ChildOrder();
_child_order = std::move(child_order);
_handover_filled_qty = handover_filled_qty;
_status = bts::api::orderman::OrderStatus::ORDER_STATUS_INACTIVE;
_filled_price = Price(0);
_filled_quantity = Quantity (0);
_last_update_filled_price = Price(0);
_last_update_filled_quantity = Quantity(0);
_last_filled_price = Price(0);
_last_reported_order_price=Price(0);
_last_reported_order_qty=Quantity(0);
_last_filled_quantity = Quantity(0);
_out_price = Price(0);
_out_quantity = Quantity(0);
_order_place_time=bts::TimeStamp();
@@ -4,7 +4,6 @@
#include "lib/api/services/OrderService.pb.h"
#include "lib/orderman/events/OrderStateUpdateEvent.h"
#include "SpreaderUtils.h"
#include "lib/domain_model/Security.h"
namespace bts {
namespace orderman {
@@ -21,22 +20,17 @@ private:
const SecurityKey _sec_key;
const bool _is_quoting;
const OrderKey _test_only_order_key;
// Since SpreaderChildOrderState can be assigned
// multiple ChildOrders during its lifetime, the
// accumulated fills and fill price from previous
// orders is kept here
Price _base_price;
Quantity _base_quantity;
// just for statistics
uint16_t _n_place_orders, _n_cancel_orders;
uint32_t _n_modify_orders;
ChildOrder _child_order;
// If the child order handled through re_init already
// is in a working state with fills
Quantity _handover_filled_qty;
// while child orders can recycle, their
// accumulated price, qty is kept here
Price _base_price;
Quantity _base_quantity;
ChildOrder _child_order;
api::orderman::OrderStatus _status;
// this is the total filled qty and
// average filled price for the active order
// average price for the active order
Price _filled_price;
Quantity _filled_quantity;
// this is the fill price, qty reported
@@ -44,23 +38,16 @@ private:
// (if no fill was reported but it was
// merely an order update, the qty
// here will be 0).
Price _last_update_filled_price;
Quantity _last_update_filled_quantity;
// these are the order price and qty reported
// in the last update (this is the best knowledge
// of what is out there)
Price _last_reported_order_price;
Quantity _last_reported_order_qty;
// this is last price, qty sent out through
// the place_order or modify_order calls
// _last_reported_order_price is the
// the working order price as it was
// last reported
Price _last_filled_price;
Price _last_reported_order_price;
Quantity _last_filled_quantity;
// this is latest price, qty sent out
Price _out_price;
Quantity _out_quantity;
Quantity _out_quantity;
bts::TimeStamp _order_place_time;
private:
bool _change_in_flight() const{
return !securities::is_same(_out_price, _last_reported_order_price) ||
_out_quantity != _last_reported_order_qty;
}
public:
// constructors ///////////////////
///////////////////////////////////
@@ -69,52 +56,37 @@ public:
SpreaderChildOrderState(SecurityKey sec_key,
bool is_live,
bool is_quoting);
SpreaderChildOrderState (SpreaderChildOrderState&& src);
SpreaderChildOrderState (SpreaderChildOrderState&& src);
SpreaderChildOrderState& operator=(const SpreaderChildOrderState&) = delete;
SpreaderChildOrderState& operator=(SpreaderChildOrderState&&) = delete;
////////////////////////////////////////////////////////////////////////////
// const direct accessors //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
SpreaderChildOrderState& operator=(SpreaderChildOrderState&&) = delete;
// const accessors ////////////////////
///////////////////////////////////////
OrderKey order_key() const {
if (_is_live)
// TODO
return _child_order.empty() ? OrderKey(0) : _child_order.key();
return _child_order.key();
else
return _test_only_order_key;
}
api::orderman::OrderStatus status() const {
}
api::orderman::OrderStatus status () const {
return _status;
}
// this is the fills from the current active order
Quantity current_fills() const {
return _filled_quantity;
}
Price last_update_filled_price() const {
return _last_update_filled_price;
}
// if the last fill was a status change
// this will be zero
Quantity last_update_filled_quantity () const {
return _last_update_filled_quantity;
Price last_update_filled_price() const {
return _last_filled_price;
}
Price last_reported_order_price() const{
return _last_reported_order_price;
}
Quantity last_reported_order_quantity() const{
return _last_reported_order_qty;
// if the last fill was a status change
// this will be zero
Quantity last_update_filled_quantity () const {
return _last_filled_quantity;
}
Price out_price() const {
return _out_price;
}
Quantity out_quantity () const {
return _out_quantity;
}
bts::TimeStamp order_place_time() const{
return _order_place_time;
}
// status accessors ////////////////////////////////////////////////////////
// all the status calls are based on the
// current order (and not the subsumed ones)
bool terminal_status() const {
return SpreaderUtils::order_in_terminal_state(_status);
return SpreaderUtils::order_in_terminal_state(_status);
}
bool acknowledged() const {
return SpreaderUtils::order_acknowledged (_status);
@@ -128,13 +100,8 @@ public:
bool errored() const{
return SpreaderUtils::order_in_error_state(_status);
}
bool working() const{
return SpreaderUtils::order_in_working_state(_status);
}
bool cancel_sent() const{
return _n_cancel_orders > 0;
}
// total across multiple orders ////////////////////////////////////////////
// this is total fills across current and
// previous orders
Quantity total_fills() const {
return Quantity(_base_quantity.value() + _filled_quantity.value());
}
@@ -144,29 +111,30 @@ public:
_filled_price, _filled_quantity,
out_price, out_filled);
}
// returns true is there are no cancels
// or modifies in flight
bool stable_state() const{
return !cancel_in_flight() && !_change_in_flight();
// this is the fills from the current active order
Quantity current_fills () const {
return _filled_quantity;
}
Price out_price() const {
return _out_price;
}
// in-flight accessors /////////////////////////////////////////////////////
bool cancel_in_flight() const{
return cancel_sent() && !terminal_status();
Quantity out_quantity () const {
return _out_quantity;
}
bts::TimeStamp order_place_time() const{
return _order_place_time;
}
// returns true if the current order has been
// cancelled
bool is_cancelled() const{
return _n_cancel_orders>0;
}
// init ///////////////////
ChildOrder& active_order(){
return _child_order;
}
void re_init (){
ChildOrder empty_order;
re_init(empty_order);
}
///////////////////////////
// this assignes a new order, and subsumes the earlier order's
// fills and filled price into the base quantity and
// base filled price
void re_init (ChildOrder& child_order,
Quantity handover_filled_qty = Quantity(0));
void re_init (ChildOrder& child_order);
ChildOrder& _empty_order(){
_child_order = ChildOrder();
return _child_order;
@@ -176,20 +144,16 @@ public:
// last filled price
void on_order_update(const OrderStateUpdateEvent& e){
bts_assert(!_is_live || e.key == order_key());
bts_assert(e.filled_quantity >= _handover_filled_qty.value());
uint32_t effective_filled_qty = e.filled_quantity -
_handover_filled_qty.value();
bts_assert(effective_filled_qty >= _filled_quantity.value());
bts_assert(e.filled_quantity >= _filled_quantity.value());
_status = e.status;
_last_update_filled_quantity = Quantity(effective_filled_qty
_last_filled_quantity = Quantity(e.filled_quantity
- _filled_quantity.value());
_last_update_filled_price = Price(e.last_price);
_last_reported_order_price = Price(e.price);
_last_reported_order_qty = Quantity(e.quantity);
_last_filled_price = Price(e.last_price);
_last_reported_order_price=Price(e.price);
SpreaderUtils::compute_average_price(_filled_price,
_filled_quantity,
_last_update_filled_price,
_last_update_filled_quantity,
_last_filled_price,
_last_filled_quantity,
_filled_price,
_filled_quantity);
}
@@ -181,16 +181,9 @@ public:
return _hedger_manager.test_only_get_hedger_at(index);
}
SingleFillHedger& add_new_hedger(bts::Price hedge_price,
bts::Quantity hedge_quantity,
bool quote_as_hedge){
bts::Quantity hedge_quantity){
SingleFillHedger& rv = _hedger_manager.get_hedger();
ISpreaderManager::OrderTransfer* order_transfer = nullptr;
ISpreaderManager::OrderTransfer order_transfer_arg;
if(quote_as_hedge){
order_transfer_arg.q_order = _quoter_child_order_state;
order_transfer = &order_transfer_arg;
}
rv.init_hedger (hedge_price, hedge_quantity, order_transfer);
rv.init_hedger (hedge_price,hedge_quantity);
return rv;
}
};
@@ -114,9 +114,6 @@ public:
static bool order_in_cancelled_state (bts::api::orderman::OrderStatus order_status){
return order_status == api::orderman::OrderStatus::ORDER_STATUS_CANCELED;
}
static bool order_in_working_state(bts::api::orderman::OrderStatus order_status){
return order_status == api::orderman::OrderStatus::ORDER_STATUS_WORKING;
}
////////////////////////////////////////////////////
// market data /////////////////////////////////////
////////////////////////////////////////////////////
@@ -655,24 +652,6 @@ public:
out_cum_qty);
quantity = Quantity(std::min(quantity.value(),out_cum_qty.value()));
}
// given an order's filled and out qty, and the desired target
// from now on, this function finds the adjusted qty of the order
// example 1 : working order is 3/10, and we want to use
// this working order to get 9 from here on, this function
// will return 12, to make this 3/12, to allow for 9
// fills.
// example 2 : working order is 3/10, and we want 2 more fills,
// it will output 5
// increments are guarded by allow_inc
static uint32_t adjust_qty_to_target (uint32_t filled_qty,
uint32_t order_qty,
uint32_t target,
bool allow_inc){
uint32_t rv = filled_qty + target;
if (rv > order_qty && !allow_inc)
rv = order_qty;
return rv;
}
////////////////////////2 legged spreads
// given a quoting target qty, finds the "driver" price
// and qty, thats needed to hedge the quote. It also
@@ -4,7 +4,6 @@
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerState.h"
#include "lib/orderman/actors/order_manager/ChildOrder.h"
#include "lib/orderman/orders/spreader_orders/spreader/ISpreaderManager.h"
namespace bts {
namespace trace {struct CorID;}
@@ -23,8 +22,7 @@ public:
virtual const std::string state_text () const = 0;
// called once and only once, before any other calls.
virtual void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) = 0;
Quantity quantity) = 0;
// called only when this hedger's order is updated
virtual void on_order_update (const SpreaderChildOrderState& order_update) = 0;
// called only when the security that the hedger is working on
@@ -9,21 +9,12 @@ void HedgerEndStateWorker::on_transition (){
// this is to allow the hedger to be re-used.
// the state is cleared and the hedger returns
// to the start state, waiting for the init call
if(!_hedger->_is_permenantly_cancelled){
Quantity rem_to_fill = _hedger->_price_quantity_state.remaining_to_fill();
if(rem_to_fill.value() > 0)
_hedger->_spreader.send_hedge_order(
_hedger->_leg_property_data.leg_index(),
_hedger->_child_order_state.out_price(),
rem_to_fill,
false);
if(!_hedger->_is_permenantly_cancelled)
_hedger->transform_to_START();
}
}
void HedgerEndStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerEndStateWorker::init illegal operation");
}
void HedgerEndStateWorker::on_order_update(const SpreaderChildOrderState&){
@@ -23,9 +23,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::END;}
const std::string state_text () const override {return "END";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -14,31 +14,11 @@ void HedgerStartStateWorker::on_transition (){
}
void HedgerStartStateWorker::init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order_ptr){
Quantity quantity){
_hedger->_price_quantity_state.re_init(price,quantity);
if(quantity.value() > 0){
if(order_ptr==nullptr){
_hedger->_place_order (price, quantity);
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
}
else{
SpreaderChildOrderState& q_order = *(order_ptr->q_order);
bts_assert(q_order.working());
//bts_assert(q_order.active_order().is_active());
uint32_t hedge_order_qty = SpreaderUtils::adjust_qty_to_target(
q_order.current_fills().value(),
q_order.out_quantity().value(),
quantity.value(),
true);
ChildOrder& existing_order = q_order.active_order();
_hedger->_child_order_state.re_init(existing_order,
q_order.current_fills());
_hedger->_modify_order (price, Quantity(hedge_order_qty));
_hedger->transform_to_WORKING();
// figure out how many have been filled
// reinit the SCO and modify the price/qty
}
_hedger->_place_order (price, quantity);
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
}
}
void HedgerStartStateWorker::on_order_update(const SpreaderChildOrderState&){
@@ -21,9 +21,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::START;}
const std::string state_text () const override {return "START";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -6,20 +6,17 @@ namespace bts{
namespace orderman{
void HedgerWaitingForCancelAckStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForCancelAckStateWorker::init "
"illegal operation");
}
void HedgerWaitingForCancelAckStateWorker::on_order_update(
const SpreaderChildOrderState& order_update){
void HedgerWaitingForCancelAckStateWorker::on_order_update(const SpreaderChildOrderState& order_update){
bts_assert (order_update.acknowledged());
_hedger->_price_quantity_state.update_fill (
order_update.last_update_filled_quantity());
_hedger->_price_quantity_state.update_fill (order_update.last_update_filled_quantity());
if (order_update.terminal_status())
_hedger->transform_to_END ();
}
void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&){
void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&){
}
void HedgerWaitingForCancelAckStateWorker::cancel(){
}
@@ -25,9 +25,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_CANCEL_ACK";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -8,8 +8,7 @@ namespace orderman{
void HedgerWaitingForFirstAckCancelledStateWorker::init(
Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForFirstAckCancelledStateWorker::init "
"illegal operation");
}
@@ -27,8 +26,8 @@ void HedgerWaitingForFirstAckCancelledStateWorker::on_order_update(
_hedger->transform_to_WAITING_FOR_CANCEL_ACK ();
}
}
void HedgerWaitingForFirstAckCancelledStateWorker::on_book(
const bts::orderman::Book&){
void HedgerWaitingForFirstAckCancelledStateWorker::on_book(const bts::orderman::Book&){
}
void HedgerWaitingForFirstAckCancelledStateWorker::cancel(){
}
@@ -25,9 +25,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_FIRST_ACK_CANCELLED";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -5,8 +5,7 @@ namespace bts{
namespace orderman{
void HedgerWaitingForFirstAckStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForFirstAckStateWorker::init "
"illegal operation");
}
@@ -26,9 +26,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_FIRST_ACK";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -10,8 +10,7 @@ void HedgerWorkingStateWorker::on_transition(){
_order_touch_time = _hedger->_current_time();
}
void HedgerWorkingStateWorker::init(Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWorkingStateWorker::init illegal operation");
}
void HedgerWorkingStateWorker::on_order_update(
@@ -43,15 +42,12 @@ void HedgerWorkingStateWorker::terminate(){
}
void HedgerWorkingStateWorker::on_time(const TimeStamp& ts){
double new_price;
const auto& book =
_hedger->_spreader.get_book (_hedger->_leg_property_data.leg_index());
if (SpreaderUtils::post_hedge_time_based_price_action (
_order_touch_time,
ts,
_hedger->_leg_property_data,
book,
new_price))
{
_order_touch_time,
ts,
_hedger->_leg_property_data,
_hedger->_spreader.get_book (_hedger->_leg_property_data.leg_index()),
new_price)){
_hedger->_modify_order (Price(new_price));
_order_touch_time = _hedger->_current_time();
}
@@ -23,9 +23,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::WORKING;}
const std::string state_text () const override {return "WORKING";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -35,10 +35,7 @@ public:
// time update from the infrastructure
virtual void on_time(const TimeStamp&) = 0;
// on a quoting fill on one of the other legs
virtual void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) = 0;
virtual void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) = 0;
// when a spreader order gets updated, it could be that the one of
// the price or quantity does not change
virtual void update_spreader_order (Price price, Quantity quantity) = 0;
@@ -18,8 +18,7 @@ void QuoterEndStateWorker::on_transition (){
_quoter->irrecoverable_error();
if (!is_final){
// getting new order
_quoter->_spreader.setup_new_quoter_order(
_quoter->_this_leg_data.leg_index());
_quoter->_spreader.setup_new_quoter_order(_quoter->_this_leg_data.leg_index());
_quoter->_transform_to_WAITING_FOR_SIZE ();
}
}
@@ -38,10 +37,8 @@ void QuoterEndStateWorker::terminate()
{}
void QuoterEndStateWorker::on_time(const TimeStamp&)
{}
void QuoterEndStateWorker::on_other_leg_quoter_fill (size_t,
Quantity,
Price,
Quantity){}
void QuoterEndStateWorker::on_other_leg_quoter_fill (size_t, Quantity)
{}
void QuoterEndStateWorker::update_spreader_order (Price, Quantity)
{}
}}
@@ -29,10 +29,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -43,11 +43,8 @@ void QuoterStartStateWorker::on_time(const TimeStamp&){
// however for the purpose of this state, we can hide that detail and deal
// with it all !
void QuoterStartStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
// same as above, but we can deal with it like one_time_activate
void QuoterStartStateWorker::update_spreader_order (Price price, Quantity quantity){
@@ -27,10 +27,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -10,7 +10,6 @@ enum class QuoterState
WAITING_FOR_IOC,
WAITING_FOR_FIRST_ACK_CANCELLED,
WORKING,
WAITING_FOR_ORDER_TRANSFER,
WAITING_FOR_CANCEL_ACK,
END
};
@@ -30,13 +30,9 @@ void QuoterWaitingForCancelAckStateWorker::terminate(){
void QuoterWaitingForCancelAckStateWorker::on_time(const TimeStamp&){
// TODO check threshold
}
void QuoterWaitingForCancelAckStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForCancelAckStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForCancelAckStateWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -28,10 +28,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -34,13 +34,8 @@ void QuoterWaitingForFirstAckCancelledWorker::terminate(){
}
void QuoterWaitingForFirstAckCancelledWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForFirstAckCancelledWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForFirstAckCancelledWorker::on_other_leg_quoter_fill (size_t leg_index, Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForFirstAckCancelledWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -34,10 +34,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -34,11 +34,8 @@ void QuoterWaitingForFirstAckWorker::terminate(){
void QuoterWaitingForFirstAckWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForFirstAckWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_analyze_and_act ();
}
void QuoterWaitingForFirstAckWorker::update_spreader_order (Price price,
@@ -32,10 +32,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// checks if the target is reached, and cancels
@@ -34,13 +34,9 @@ void QuoterWaitingForIOCWorker::terminate(){
}
void QuoterWaitingForIOCWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForIOCWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForIOCWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForIOCWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -35,10 +35,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -1,60 +0,0 @@
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForOrderTransferStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterState.h"
#include "lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
namespace bts{
namespace orderman{
QuoterState QuoterWaitingForOrderTransferStateWorker::state () const {
return QuoterState::WAITING_FOR_ORDER_TRANSFER;
}
void QuoterWaitingForOrderTransferStateWorker::one_time_activate (Price,
Quantity){
bts_assert_msg (false,
"QuoterWaitingForOrderTransferStateWorker::one_time_activate "
"is an illegal operation");
}
void QuoterWaitingForOrderTransferStateWorker::on_order_update (
const SpreaderChildOrderState& u){
bts_assert (u.acknowledged());
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::on_book (
size_t,
const bts::orderman::Book&){
}
void QuoterWaitingForOrderTransferStateWorker::cancel(){
_quoter->_cancel_order();
_quoter->_transform_to_WAITING_FOR_CANCEL_ACK ();
}
void QuoterWaitingForOrderTransferStateWorker::terminate(){
_quoter->_transform_to_END ();
}
void QuoterWaitingForOrderTransferStateWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForOrderTransferStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::update_spreader_order (
Price price,
Quantity quantity){
_quoter->_price_quantity_state.update_target_price_quantity (price, quantity);
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::_analyze_and_act(){
const auto& u = _quoter->_child_order_state;
if(u.terminal_status() ||
_quoter->_price_quantity_state.target_reached()){
_quoter->_transform_to_END ();
return;
}
}
}}
@@ -1,43 +0,0 @@
#pragma once
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/utils/bts_chrono.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterState.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h"
namespace bts {
namespace orderman {
class SpreaderChildOrderState;
class Book;
class SingleLegQuoter;
// Quoter order is in the process of transferring ownership
// to thehedger
// exit:
class QuoterWaitingForOrderTransferStateWorker : public IQuoterStateWorker
{
private:
SingleLegQuoter* const _quoter;
public:
QuoterWaitingForOrderTransferStateWorker (SingleLegQuoter* quoter)
:_quoter(quoter){}
QuoterState state () const override;
const std::string state_text () const override {
return "WAITING_FOR_ORDER_TRANSFER";
}
virtual void on_transition () override {}
void one_time_activate (Price, Quantity) override;
void on_order_update (
const SpreaderChildOrderState& order_update) override;
void on_book (size_t leg_id, const bts::orderman::Book& book) override;
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
void _analyze_and_act ();
};
}}
@@ -34,11 +34,8 @@ void QuoterWaitingForSizeStateWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForSizeStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_longpath_analyze_and_act ();
}
void QuoterWaitingForSizeStateWorker::update_spreader_order (Price price,
@@ -34,10 +34,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// checks to see if target has reached and goes to end
@@ -5,7 +5,6 @@
#include "lib/orderman/orders/spreader_orders/spreader/ISpreaderManager.h"
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderCacheWarmingState.h"
#include "lib/domain_model/Security.h"
namespace bts{
namespace orderman{
@@ -42,28 +41,12 @@ void QuoterWorkingStateWorker::cancel(){
void QuoterWorkingStateWorker::terminate(){
_quoter->_transform_to_END ();
}
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
}
void QuoterWorkingStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
bool q_to_h = hedge_qty.value() > 0 &&
_use_quoting_order_to_hedge(hedge_price,hedge_qty);
// decide how to send hedge
_quoter->_incorporate_other_leg_fill (leg_index,
filled_quantity,
hedge_price,
hedge_qty,
true,
q_to_h);
if(q_to_h){
_quoter->_child_order_state.re_init();
_quoter->_transform_to_END();
}
else
_longpath_analyze_and_act ();
void QuoterWorkingStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_longpath_analyze_and_act ();
}
void QuoterWorkingStateWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -116,51 +99,4 @@ void QuoterWorkingStateWorker::_modify_order (Price price, Quantity quantity){
_quoter->_modify_order(price, quantity);
}
}
bool QuoterWorkingStateWorker::_use_quoting_order_to_hedge(Price h_price,
Quantity h_qty) const{
const LegPropertyData& leg = _quoter->_this_leg_data;
const SpreaderChildOrderState& q_ord = _quoter->_child_order_state;
// check to see if the order is in transition ?
auto q_for_h = leg.use_quote_for_hedging();
bool q_better = securities::same_or_better_order_price(
_quoter->_this_leg_data.trading_side(),
q_ord.last_reported_order_price(),
h_price) &&
// this is to make sure that the hedge price
// is also worse than anything in flight
securities::same_or_better_order_price(
_quoter->_this_leg_data.trading_side(),
q_ord.out_price(),
h_price);
bool rv;
switch(q_for_h){
case spark::UseSpreaderQuoteForHedging::NEVER:
rv = false;
break;
case spark::UseSpreaderQuoteForHedging::WHEN_CANT_OVERHEDGE:
rv = q_better &&
// max fill potential <= hedge qty
h_qty.value() >= SpreaderUtils::subtract_quanitities(
q_ord.out_quantity().value(),
q_ord.current_fills().value()) &&
h_qty.value() >= SpreaderUtils::subtract_quanitities(
q_ord.last_reported_order_quantity().value(),
q_ord.current_fills().value());
break;
case spark::UseSpreaderQuoteForHedging::ALWAYS:
rv = q_better;
break;
default:
bts_assert(false);
rv = false;
break;
}
LOG(OrderMan, Info, "QuoterWorkingStateWorker::_use_quoting_order_to_hedge "
"res: leg:{} hp:{} hq:{}",
rv,
leg.leg_index(),
h_price,
h_qty);
return rv;
}
}}
@@ -27,10 +27,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// this does the following in this order
@@ -39,7 +36,5 @@ private:
// iii. if reprice (ie qty changed or price changed beyond the threshold) => requote
void _longpath_analyze_and_act ();
void _modify_order (Price price, Quantity quantity);
bool _use_quoting_order_to_hedge(Price h_price,
Quantity h_qty) const;
};
}}
@@ -123,25 +123,17 @@ void SpreaderWorkingStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data)
LOG(OrderMan,cw.llevel,"h_p delta {} {}", q_idx, _spreader->_diff_ns());
// if it is an actively quoting leg, inform the quoter about it
// so it can decrease the proportional size
// if (!cw.in_cache_warming_cycle &&
// other_leg_data.leg_property_data().is_active_quoting()){
// if this leg is an active quoting leg, let it deal with
// hedging since it can use its own order to hedge
if (other_leg_data.leg_property_data().is_active_quoting()){
if (!cw.in_cache_warming_cycle &&
other_leg_data.leg_property_data().is_active_quoting()){
other_leg_data.quoter().update_other_leg_fills(
leg_data.leg_property_data().leg_index(),
Quantity(total_unhedged_qty),
hedge_price,
Quantity(total_unhedged_qty));
LOG(OrderMan,cw.llevel,"h_p q minus {} {}", q_idx, _spreader->_diff_ns());
}
else
// if it is not a quoting leg, the hedge needs to be
// sent explictely from here
_spreader->_send_hedge(other_leg_data.leg_property_data().leg_index(),
hedge_price,
Quantity(total_unhedged_qty),
false);
// a hedge is sent regardless
_spreader->_send_hedge(other_leg_data.leg_property_data().leg_index(),
hedge_price,
Quantity(total_unhedged_qty));
LOG(OrderMan,cw.llevel,"h_p send hedge {} {}", q_idx, _spreader->_diff_ns());
}
}
@@ -90,11 +90,6 @@ public:
ChildOrder rv;
return rv;
}
void send_hedge_order (size_t,
Price,
Quantity,
bool){
}
bool in_cache_warming_cycle() const override{
return false;
}
+2 -9
View File
@@ -31,12 +31,6 @@ message RulePriority
int32 priority = 20;
}
enum UseSpreaderQuoteForHedging
{
NEVER = 0;
WHEN_CANT_OVERHEDGE = 1;
ALWAYS = 2;
}
message LegSpreaderParams
{
@@ -52,7 +46,7 @@ message LegSpreaderParams
PreHedgeParams pre_hedge_params = 50;
PostHedgeParams post_hedge_params = 60;
MarketDataType market_data_type = 70;
//reserve LegMarketDataCalculation leg_md_calc = 80;
//reserve LegMarketDataCalculation leg_md_calc = 80;
}
// /*************************************************************************************************
@@ -80,8 +74,7 @@ message QuoteParams
// and the user can embed a QHO here)
uint32 n_queue_holder_orders=2000;
// this is the show quantity on the quoter order
NullableQuantity show_quantity = 2010;
UseSpreaderQuoteForHedging use_quote_for_hedging = 2020;
NullableQuantity show_quantity = 2010;
}
/*************************************Quote MuteZone***********************************
+1
View File
@@ -27,6 +27,7 @@ struct Proxy : public IAlgoServices {
Price price() const { return Price(0); }
Quantity quantity() const { return Quantity(0); }
Quantity total_fills() const { return Quantity(0); }
bool is_shutting_down() const {return false;}
void subscribe_book(SecurityKey){};
void unsubscribe_book(SecurityKey) {}
void subscribe_child_change(OrderKey) {}
+1 -1
View File
@@ -33,7 +33,7 @@ int Span::execute(const std::vector<std::string>&)
auto& disp = utils::Dispatcher::current();
MarginServiceCore core(disp);
auto acct = orderman::to<orderman::AccountName>("ACC A");
auto acct = std::string("ACC A");
Position p;
p.security_desc = "ESU9";
p.account = acct;
@@ -28,7 +28,7 @@ namespace bts
namespace position
{
using MarginMap = boost::container::flat_map<orderman::AccountName, MarginResult>;
using MarginMap = boost::container::flat_map<std::string, MarginResult>;
struct MarginServiceCore::PImpl
{
@@ -314,10 +314,9 @@ struct MarginServiceCore::PImpl
}
};
bool compute_margin(const orderman::AccountName& acct, const std::string& portfolid_id,
bool compute_margin(const std::string& account_name, const std::string& portfolid_id,
const std::vector<Position>& pos, std::function<void(const MarginResult&)> cb)
{
auto account_name = orderman::to_trim_str(acct);
pugi::xml_document doc;
pugi::xml_node trades_node;
create_margin_request(portfolid_id, doc, trades_node);
@@ -384,7 +383,7 @@ MarginServiceCore::MarginServiceCore(utils::Dispatcher& disp) : me(new PImpl(dis
MarginServiceCore::~MarginServiceCore() {}
void MarginServiceCore::compute_margin(const orderman::AccountName& acct, const std::vector<Position>& pos,
void MarginServiceCore::compute_margin(const std::string& acct, const std::vector<Position>& pos,
std::function<void(const MarginResult&)> cb)
{
me->dispatcher.post([=] ()
@@ -393,7 +392,7 @@ void MarginServiceCore::compute_margin(const orderman::AccountName& acct, const
}, me->throttle);
}
bool MarginServiceCore::query_margin_webapi(const orderman::AccountName& acct, const std::vector<Position>& pos,
bool MarginServiceCore::query_margin_webapi(const std::string& acct, const std::vector<Position>& pos,
std::function<void(const MarginResult&)> cb)
{
utils::Uuid guid;
@@ -425,7 +424,7 @@ void MarginServiceCore::set_verbose_debugging(bool verb)
me->verbose = verb;
}
bool MarginServiceCore::get_last_valid_result(const orderman::AccountName& acct, MarginResult& result)
bool MarginServiceCore::get_last_valid_result(const std::string& acct, MarginResult& result)
{
auto it = me->last_valid_results.find(acct);
if(it != me->last_valid_results.end())
@@ -436,7 +435,7 @@ bool MarginServiceCore::get_last_valid_result(const orderman::AccountName& acct,
return false;
}
bool MarginServiceCore::get_last_result(const orderman::AccountName& acct, MarginResult& result)
bool MarginServiceCore::get_last_result(const std::string& acct, MarginResult& result)
{
auto it = me->last_results.find(acct);
if(it != me->last_results.end())
@@ -22,18 +22,18 @@ public:
MarginServiceCore(utils::Dispatcher&);
~MarginServiceCore();
void compute_margin(const orderman::AccountName&, const std::vector<Position>&,
void compute_margin(const std::string&, const std::vector<Position>&,
std::function<void(const api::position::MarginResult&)>);
void set_verbose_debugging(bool);
bool get_last_valid_result(const orderman::AccountName&, api::position::MarginResult&);
bool get_last_result(const orderman::AccountName&, api::position::MarginResult&);
bool get_last_valid_result(const std::string&, api::position::MarginResult&);
bool get_last_result(const std::string&, api::position::MarginResult&);
private:
friend class PositionTests;
//This is a blocking call to a WebAPI. Very Slow.
bool query_margin_webapi(const orderman::AccountName&, const std::vector<Position>&,
bool query_margin_webapi(const std::string&, const std::vector<Position>&,
std::function<void(const api::position::MarginResult&)>);
private:
@@ -48,13 +48,6 @@ MarginServiceServer::MarginServiceServer(bts::api::ServiceContext& context, md::
LOG(Gen, Info, "MarginServiceServer: service started");
// _admin_service.get_admin_data(api::VoidMessage(),
// [=] (const bts::api::Result<::bts::api::admin::AdminData> r)
// {
// if(r.value())
// _admin_data = *r.value();
// });
_admin_service.subscribe_admin_data() |
rxcpp::operators::subscribe<api::admin::Admin_dataUpdate>(
[this](auto const &update)
@@ -94,8 +87,7 @@ void MarginServiceServer::publish_all()
if(_position->query_positions(acct, pos, pnl, &since) && pos.size())
{
LOG(Gen, Info, "MarginServiceServer: requesting margin for {} ", acct);
auto aname = orderman::to<orderman::AccountName>(acct);
_margin->compute_margin(aname, pos, [this, since, acct, pnl](const MarginResult& m)
_margin->compute_margin(acct, pos, [this, since, acct, pnl](const MarginResult& m)
{
std::scoped_lock<std::recursive_mutex> l(_lock);
publish_margin(m);
@@ -120,11 +112,9 @@ void MarginServiceServer::get_margin(const api::position::MarginRequest& request
}
else
{
orderman::AccountName acct;
orderman::str_to(request.account(), &acct);
std::vector<Position> pos; AccountPNL pnl;
_position->query_positions(request.account(), pos, pnl);
_margin->compute_margin(acct, pos, [=](const MarginResult& m)
_margin->compute_margin(request.account(), pos, [=](const MarginResult& m)
{
reply(m);
});
@@ -186,7 +176,7 @@ void MarginServiceServer::incremental_update_report(const std::string& account,
std::scoped_lock<std::recursive_mutex> l(_lock);
MarginResult margin;
if(!_margin->get_last_valid_result(orderman::to<orderman::AccountName>(account), margin))
if(!_margin->get_last_valid_result(account, margin))
{
margin.Clear();
margin.set_account(account);
@@ -206,6 +196,13 @@ void MarginServiceServer::incremental_update_report(const std::string& account,
void MarginServiceServer::set_cash_factor(const ::bts::api::position::CashFactorUpdate& request,
const api::Response<::bts::api::ResultMessage>& reply)
{
if(!config::get<bts::config::SpanMargin>().enabled())
{
api::ResultMessage resp; resp.set_success(true);
reply(resp);
return;
}
std::scoped_lock<std::recursive_mutex> l(_lock);
auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false);
if(!acct)
@@ -237,6 +234,13 @@ void MarginServiceServer::set_cash_factor(const ::bts::api::position::CashFactor
void MarginServiceServer::set_cash_balance(const ::bts::api::position::CashBalanceUpdate& request,
const api::Response<::bts::api::ResultMessage>& reply)
{
if(!config::get<bts::config::SpanMargin>().enabled())
{
api::ResultMessage resp; resp.set_success(true);
reply(resp);
return;
}
std::scoped_lock<std::recursive_mutex> l(_lock);
auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false);
if(!acct)
@@ -268,6 +272,13 @@ void MarginServiceServer::set_cash_balance(const ::bts::api::position::CashBalan
void MarginServiceServer::set_should_enforce_margin(const ::bts::api::position::EnforceUpdate& request,
const api::Response<::bts::api::ResultMessage>& reply)
{
if(!config::get<bts::config::SpanMargin>().enabled())
{
api::ResultMessage resp; resp.set_success(true);
reply(resp);
return;
}
std::scoped_lock<std::recursive_mutex> l(_lock);
auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false);
if(!acct)
+1 -1
View File
@@ -6,7 +6,7 @@ namespace bts {
namespace position {
struct Position
{
orderman::AccountName account;
std::string account;
std::string security_desc;
Quantity position;
api::Side side;
@@ -112,7 +112,7 @@ bool PositionAggregator::query_positions(const std::string& account, std::vector
if(sec && sec->has_glbx() && sec->has_future())
{
Position pos;
pos.account = orderman::to<orderman::AccountName>(account);
pos.account = account;
pos.security_desc = securities::descriptor(*sec);
eraseSubStr(pos.security_desc, "SIM:");
int32_t totalpos = unit.sod_long_pos() + unit.day_long_pos() - unit.sod_short_pos() - unit.day_short_pos();