Merge branch 'master' into SP-42-manual-fills-should-not-go-into-so

This commit is contained in:
Pedro Pinto committed 2019-06-17 11:01:11 -04:00
commit c1fb53ff06
20 files changed
+329 -66

No files matched your search

@@ -3,6 +3,7 @@ using bts.persist.algo;
using bts.utils;
using ProtoBuf;
using System;
using System.Linq;
namespace mbts.spark {
[ProtoContract]
@@ -14,6 +15,11 @@ namespace mbts.spark {
[ProtoMember(3)]
readonly uint? _persisted_key;
public static readonly AlgoID[] exchange_algo_keys = utilities.OrderDataHelper.outright_order_types
.Concat(new CustomOrderDefinition.CustomOneofCase[] { CustomOrderDefinition.CustomOneofCase.Spreader })
.Select(cooc => new AlgoID(cooc))
.ToArray();
public AlgoID(CustomOrderDefinition.CustomOneofCase factory_key) {
_factory_key = factory_key;
_dynamic_key = null;
@@ -1,5 +1,6 @@
using bts.api;
using bts.api.orderman;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using System;
@@ -297,7 +298,8 @@ namespace mbts.spark {
new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(_owner.security),
price = price_filter,
statuses = new[] { OrderStatus.Working }
statuses = new[] { OrderStatus.Working },
order_types = AlgoID.exchange_algo_keys
},
bts.shell.orderbook.OrderBookStartupData.default_mini_grid,
use_defaults: false
@@ -335,6 +337,7 @@ namespace mbts.spark {
}
obvm.columns.Insert(0, new OrderBookVM.UpdateColumn(typeof(MiniOrderBookView)));
obvm.columns.Insert(0, new OrderBookVM.CancelColumn(nameof(OrderBookRowVM.cancel_command)));
obvm.columns.Insert(0, new OrderBookVM.CheckColumn(nameof(OrderBookRowVM.is_selected)));
obvm.load_from(state);
return obvm;
@@ -139,6 +139,7 @@ namespace mbts.spark {
// properly Dispose of it later when the popup is closed.
DataContext = obvm,
Child = view,
// StaysOpen true for debugging
StaysOpen = false,
PlacementTarget = popup_placement_target,
Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom,
@@ -99,7 +99,16 @@
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</Style.Triggers>
<!-- We added this IsSelected after seeing some strangeness when bringing up the Mini OB,
then clicking the attach button, then performing a click to modify a param in the popup, the grid
would lose the appearance of its selected row. I think this was actually a result of a bad path
in the SelectionHighlight expression below, but that leaves me questioning how if it was bad (and
it was, I confirmed in Snoop) did the Grid successfully show a highlighted row in the first place.
At any rate, I have a strong suspicion this Setter is no longer necessary, but I am too exhausted
and scared to remove it at this point.
-->
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}" />
</Style>
<DataTemplate x:Key="{x:Static sp:MiniOrderBookView.RowTemplateKey}">
<sp:MiniOrderBookRowView/>
@@ -121,10 +130,9 @@
Rows="{Binding rows}"
RowStyle="{StaticResource {x:Static sp:MiniOrderBookView.RowStyleKey}}"
RowTemplate="{StaticResource {x:Static sp:MiniOrderBookView.RowTemplateKey}}"
SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}"
SelectionHighlight="{Binding grid_settings_manager.core_manager.selection_highlight, Mode=OneWay}"
RowsHorizontalScrollBarVisibility="Collapsed"
RowHeight="20"
SelectionMode="Single"
>
<c:DIYGrid.Resources>
<ResourceDictionary>
@@ -724,6 +724,28 @@ namespace mbts.spark {
}
}
public class CheckColumn : FrameworkElementColumnBase<Columns> {
readonly BindingBase _checked_binding;
public CheckColumn(string checked_property) : base(Columns.Check) {
id = key.ToString();
Width = 30;
_checked_binding = new Binding(checked_property);
}
public override FrameworkElement view_factory() {
var grid = new Grid() {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
};
var cb = new CheckBox();
cb.Name = "check_col";
cb.SetBinding(CheckBox.IsCheckedProperty, _checked_binding);
grid.Children.Add(cb);
return grid;
}
}
public class CancelColumn : FrameworkElementColumnBase<Columns> {
readonly BindingBase _command_binding;
@@ -829,13 +851,13 @@ namespace mbts.spark {
var row_vm_attach_command_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.attach_command)));
row_vm_attach_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
attach_button.SetBinding(Button.CommandProperty, row_vm_attach_command_binding);
attach_button.SetBinding(Button.CommandProperty, row_vm_attach_command_binding);
#region OrderParamsPanel
// finally, set the order_params DataContext to that of the ContextMenu
var order_params = AlgoEditorGridView.create_attach_view();
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.attach_vm)));
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
@@ -857,6 +879,7 @@ namespace mbts.spark {
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
// pure genious!
var send_attach_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.send_attached_orders_cmd))) {
// set to true for debugging
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
};
send_attach_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
@@ -907,6 +930,7 @@ namespace mbts.spark {
#endregion
popup.Child = border;
// set to true for debugging
popup.StaysOpen = false;
popup.PlacementTarget = attach_button;
popup.Placement = PlacementMode.Bottom;
@@ -914,7 +938,6 @@ namespace mbts.spark {
popup.SetBinding(Popup.DataContextProperty, new Binding("PlacementTarget.DataContext") {
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
});
#endregion
#region Detach Button
@@ -970,15 +993,16 @@ namespace mbts.spark {
public override FrameworkElement view_factory() {
var popup = new System.Windows.Controls.Primitives.Popup();
#region Attach Button
#region Update Button
// create the attach button and assign the menu to it
// create the update button and assign the menu to it
var update_button = new Button() {
Name = "update_button",
Content = "···",
Margin = new Thickness(2),
VerticalAlignment = VerticalAlignment.Center,
Focusable = false
Focusable = false,
ToolTip = "Update"
};
update_button.Click += (s, e) => { popup.IsOpen = !popup.IsOpen; };
@@ -995,21 +1019,26 @@ namespace mbts.spark {
row_vm_update_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
update_button.SetBinding(Button.CommandProperty, row_vm_update_command_binding);
// update button is only visible for orders under the control of an algo
var update_button_visibility_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.root_algo_order_type))) {
Converter = ValueConverter.create<CustomOrderDefinition.CustomOneofCase, Visibility>(ord_type => utilities.OrderDataHelper.outright_order_types.Contains(ord_type) ? Visibility.Hidden : Visibility.Visible)
};
update_button_visibility_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
update_button.SetBinding(Button.VisibilityProperty, update_button_visibility_binding);
#endregion
#region OrderParamsPanel
// finally, set the order_params DataContext to that of the ContextMenu
var order_params = new AlgoEditorGridView {
Margin = new Thickness(6),
CanUserChangeAlgoRoot = false,
};
;
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.order_mod_vm)));
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
order_params.SetBinding(AlgoEditorGridView.AlgoParamRowsProperty, new Binding(nameof(OrderParamsVM.param_rows)));
#endregion
#region Dialog Skirt
@@ -1027,6 +1056,7 @@ namespace mbts.spark {
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
// pure genious!
var modify_selected_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.modify_selected_orders_cmd))) {
// set to true for debugging
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
};
modify_selected_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
@@ -1086,8 +1116,9 @@ namespace mbts.spark {
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
});
popup.Closed += (s, e) => {
if (popup.try_find_ancestor_of_type(out MiniOrderBookView mini_ob) && mini_ob.DataContext is OrderBookVM ob_vm)
if (popup.try_find_ancestor_of_type(out MiniOrderBookView mini_ob) && mini_ob.DataContext is OrderBookVM ob_vm) {
ob_vm.is_attaching_orders = false;
}
};
var the_whole_thing = new Grid();
@@ -190,14 +190,18 @@ namespace mbts.spark {
public ICommand attach_command => _attach_command ?? (
_attach_command = new DelegateCommand(() => {
// the _select me will trigger the OBVM.attach_vm to get primed
_select_me();
if (!is_selected) {
_select_me();
}
_owner.begin_attach_algos();
})
);
public ICommand update_command => _update_command ?? (
_update_command = new DelegateCommand(() => {
_select_me();
if (!is_selected) {
_select_me();
}
})
);
@@ -233,12 +237,10 @@ namespace mbts.spark {
private void _unselect_me() {
this.is_selected = false;
_owner.current_row = null;
}
private void _select_me() {
this.is_selected = true;
_owner.current_row = this;
}
// These fns present a way for the orderbook to avoid noisy, intermittent collection changes during "Expand/Collapse All" ops,
@@ -290,6 +292,10 @@ namespace mbts.spark {
// root display name
if (old_order_tuple.root_algo.name != order_tuple.root_algo.name)
RaisePropertyChanged(nameof(root_algo_display_name));
// root order type
if (old_order_tuple.root_algo.value.CustomCase != order_tuple.root_algo.value.CustomCase) {
RaisePropertyChanged(nameof(root_algo_order_type));
}
// status
if ((Columns.Status & dirty) != 0)
RaisePropertyChanged(nameof(status));
@@ -63,6 +63,7 @@ namespace mbts.spark {
_attachable_selected_orders = new HashSet<uint>(),
_detachable_selected_orders = new HashSet<uint>();
FilterData _cached_filter_data;
Dictionary<uint, IDisposable> _on_updated_single_callback_gatekeeper = new Dictionary<uint, IDisposable>();
public OrderBookVM(
IObservable<string> owner_title,
@@ -430,19 +431,43 @@ namespace mbts.spark {
if (e.RemovedItems != null) {
foreach (var row_vm in e.RemovedItems.OfType<OrderBookRowVM>()) {
row_vm.is_selected = false;
_selected_params_mon.on_row_unselected(row_vm);
_selected_params_mon.on_order_unselected(_get_root(row_vm.order_tuple));
_attachable_selected_orders.Remove(row_vm.order_key);
_detachable_selected_orders.Remove(row_vm.order_key);
}
}
if (e.AddedItems != null) {
foreach (var row_vm in e.AddedItems.OfType<OrderBookRowVM>()) {
var root = _get_root(row_vm.order_tuple);
row_vm.is_selected = true;
_selected_params_mon.on_row_selected(row_vm);
if (!_on_updated_single_callback_gatekeeper.ContainsKey(row_vm.order_key)) {
row_vm.updated += on_updated;
_on_updated_single_callback_gatekeeper.Add(row_vm.order_key, Disposable.Create(() => row_vm.updated -= on_updated));
}
_selected_params_mon.on_order_selected(root);
if (row_vm.is_attachable)
_attachable_selected_orders.Add(row_vm.order_key);
if (row_vm.is_detachable)
_detachable_selected_orders.Add(row_vm.order_key);
void on_updated((OrderSecurity oldval, OrderSecurity newval) change) {
if (!row_vm.is_selected) {
// self destruct
if (_on_updated_single_callback_gatekeeper.TryGetValue(row_vm.order_key, out var unsubscribe_updated_disposable)) {
unsubscribe_updated_disposable.Dispose();
_on_updated_single_callback_gatekeeper.Remove(row_vm.order_key);
}
_selected_params_mon.on_order_unselected(_get_root(row_vm.order_tuple));
return;
}
var new_root = _get_root(change.newval);
if (!new_root.Equals(root)) {
// unselect and select in one smooth motion via on_row_updated
// because we thought there may be gremlins afoot when doing
// on_row_unselected and then on_row_selected
_selected_params_mon.on_order_updated((root, new_root));
root = new_root;
}
}
}
}
RowSelectionHelper.apply_changes(selected_rows, e);
@@ -547,15 +572,25 @@ namespace mbts.spark {
public bool try_get_parent(OrderBookRowVM row, out OrderSecurity parent) =>
_cached_orders.TryGetValue(row.parent_order_key, out parent);
public OrderRecordImmutable get_root(OrderRecordImmutable r) {
while (r.ParentKey != 0 && _cached_orders.TryGetValue(r.ParentKey, out var parent_osam)) {
r = parent_osam.order;
}
return r;
OrderBookRowVM _get_root_row(OrderBookRowVM row) {
while (row.parent_order_key != 0 && _row_collection.get_parent(row.parent_order_key) is OrderBookRowVM prow)
row = prow;
return row;
}
internal void detach_orders(OrderBookRowVM order) =>
_detach_orders_async(new[] { order }).ignore();
OrderSecurity _get_root(OrderSecurity os) {
while (os.order.ParentKey != 0 && _cached_orders.TryGetValue(os.order.ParentKey, out var pos))
os = pos;
return os;
}
internal void detach_orders(OrderBookRowVM row) {
if (row.is_selected) {
_detach_orders_async(selected_rows).ignore();
} else {
_detach_orders_async(new[] { row }).ignore();
}
}
public OrderSecurity get_ordersecurityalgometa(OrderRecordImmutable order) {
_cached_orders.TryGetValue(order.Key, out var osam);
@@ -571,8 +606,13 @@ namespace mbts.spark {
internal void show_order_modify(OrderBookRowVM row) =>
_bus.post(SparkTags.ShowModifyOrderTag, row.order_key);
internal void cancel_order(OrderBookRowVM row) =>
_bus.post(SparkTags.CancelOrders, new List<uint> { row.order_key });
internal void cancel_order(OrderBookRowVM row) {
if (row.is_selected) {
_bus.post(SparkTags.CancelOrders, selected_rows.Select(r => r.order_key).ToList());
} else {
_bus.post(SparkTags.CancelOrders, new List<uint> { row.order_key });
}
}
internal void modify_order_quantity(OrderBookRowVM row, uint size) =>
_bus.post(SparkTags.UpdateOrder, (row.order_key, row.price, size));
@@ -611,6 +651,7 @@ namespace mbts.spark {
}
}
// Note: modifications are performed on the selected orders' ROOT orders.
async Task _modify_selected_orders_async() {
double? price = DoubleHelper.nan_nullable(order_mod_vm.price);
uint? size = order_mod_vm.size;
@@ -623,17 +664,17 @@ namespace mbts.spark {
// their values will be cleared (in the param grid gui), and the modifications will not be applied.
// FYI this behavior is implemented to support 'partial edits.' (e.g., changing the 'price' for multiple orders that do not have the same 'size').
// ----
var update_params = selected_rows.Select(update_params_factory).ToList();
var update_params = selected_rows.Select(r => update_params_factory(_get_root(r.order_tuple))).ToList();
await Task.WhenAll(update_params.Select(t => _model.update_order(t.order, new_price: price, new_size: size, new_algo: t.new_algo)));
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderBookRowVM row) {
var mod_algo = row.order.Def.CustomDef.CloneToMutable();
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderSecurity order_tuple) {
var mod_algo = order_tuple.order.Def.CustomDef.CloneToMutable();
if (mod_algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
mod_algo_vm.assign_to(mod_algo.Composite.Definition);
} else {
mod_algo_vm.assign_to(mod_algo);
}
var mod_algoi = new CustomOrderDefinitionImmutable(mod_algo);
return (row.order, OrderDataHelper.EqualsHelpers.equals(row.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi);
return (order_tuple.order, OrderDataHelper.EqualsHelpers.equals(order_tuple.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi);
}
} else await Task.WhenAll(selected_rows.Select(r => _model.update_order(r.order, price)));
}
@@ -1006,22 +1047,18 @@ namespace mbts.spark {
public IDisposable begin_udpate() =>
_group_mon.defer_updates();
public void on_row_selected(OrderBookRowVM row) {
_group_mon.add(row.order_tuple);
row.updated += _on_row_updated;
}
public void on_order_selected(OrderSecurity order_tuple) =>
_group_mon.add(order_tuple);
public void on_row_unselected(OrderBookRowVM row) {
_group_mon.remove(row.order_tuple);
row.updated -= _on_row_updated;
}
public void on_order_unselected(OrderSecurity order_tuple) =>
_group_mon.remove(order_tuple);
public void on_security_md_map(IReadOnlyDictionary<uint, SecurityMD> security_md_map) {
_security_md_map = security_md_map;
_security_md_map_changed?.Invoke();
}
void _on_row_updated((OrderSecurity oldval, OrderSecurity newval) ch) {
public void on_order_updated((OrderSecurity oldval, OrderSecurity newval) ch) {
using (begin_udpate()) {
_group_mon.remove(ch.oldval);
_group_mon.add(ch.newval);
@@ -108,4 +108,9 @@
<MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
<KeyBinding Key="Return" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
</c:DIYGrid.InputBindings>
<c:DIYGrid.RowStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource DIYGridRowStyle}">
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}" />
</Style>
</c:DIYGrid.RowStyle>
</c:DIYGrid>
@@ -50,7 +50,8 @@ namespace mbts.spark {
Update = 1 << 27,
Commit = 1 << 28,
RootAlgoType = 1 << 29,
Piq = 1 << 30
Piq = 1 << 30,
Check = 1 << 31
}
public OrderBookGridView() {
@@ -622,6 +622,13 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Join,
CustomOrderDefinition.CustomOneofCase.Cover,
CustomOrderDefinition.CustomOneofCase.Top
},
outright_order_types = new[] {
CustomOrderDefinition.CustomOneofCase.Market,
CustomOrderDefinition.CustomOneofCase.Limit,
CustomOrderDefinition.CustomOneofCase.Stop,
CustomOrderDefinition.CustomOneofCase.StopLimit,
CustomOrderDefinition.CustomOneofCase.GlbxIceberg,
};
public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray();
@@ -65,8 +65,12 @@ namespace bts.collections {
return false;
}
public TRow get_parent(TKey key) =>
_tree.TryGetNode(key, out var n) ? n.value : default;
public TRow get_parent(TKey key) {
if (try_get_row(key, out TRow r)) {
return _tree.GetParent(r).value;
}
return default;
}
public IEnumerable<TRow> get_descendent_rows(TKey key) {
if (_tree.TryGetNode(key, out var n)) {
+2
View File
@@ -174,6 +174,8 @@ message CoverOrderDefinition {
CustomOrderDefinition hedge = 1;
uint32 hedge_ticks = 2;
CustomOrderDefinition child = 3;
bool cancel_on_external_hedge_cancel = 4;
bool cancel_hedges_on_cancel = 5;
}
message OffsetOrderDefinition {
uint32 tick_offset_on_deploy = 1;
@@ -135,9 +135,9 @@ void AlgoWrapperOrder::on_init_new(OrderDefinition const &def,
if (can_consume_attachment(me->definition.custom_def().custom_case())) {
me->attach_target = OrderKey(me->definition.attach_target_order_key());
me->definition.clear_attach_target_order_key();
}
else {
terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Algo does not support attachment");
} else {
terminate(ORDER_STATUS_REJECTED_BY_SPARK,
"Algo does not support attachment");
return;
}
}
@@ -290,9 +290,19 @@ orderman::OrderOpResult AlgoWrapperOrder::on_cancel() {
switch (me->status) {
case Status::W_ATTACH:
case Status::WORKING:
terminate(ORDER_STATUS_CANCELED);
break;
case Status::WORKING:
switch (me->algo->on_cancel()) {
case IAlgoOrder::OnCancelResponse::HONOR:
cancel();
break;
case IAlgoOrder::OnCancelResponse::IGNORE:
LOG(OrderMan,Info,"Algo order with key {} ignored cancel request",
key().value());
break;
}
break;
case Status::COMPLETED:
break;
case Status::INACTIVE:
@@ -64,6 +64,14 @@ class IAlgoOrder {
// implementation should validate the update and either apply it,
// if valid or terminate with an error otherwise
virtual void do_update(api::orderman::Update const &) {}
// Override this method to provide custom handling of a cancel
// request. The default behaviour is to cancel both this order and
// recursively any of its children. Algos may override this method
// for example to detach from specific children before canceling or
// to implement custom cleanup behaviour when canceled.
enum class OnCancelResponse {IGNORE, HONOR};
virtual OnCancelResponse on_cancel() {return OnCancelResponse::HONOR;}
};
} // namespace orderman
@@ -26,6 +26,8 @@ struct CoverAlgo::PImpl {
IAlgoServices *algo;
OrderKey child_key = null_order_key();
Price price_improvement_delta;
bool cancel_on_external_hedge_cancel = false;
bool cancel_hedges_on_cancel = false;
ChildTemplate *child_template = nullptr;
ChildTemplate *hedge_template = nullptr;
Quantity hedged_fills = Quantity(0);
@@ -64,7 +66,7 @@ OrderOpResult CoverAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) {
}
init_hedge_template(serv, cover.hedge());
set_price_improvement_delta(serv, cover);
update_definition(serv, cover);
return {};
}
@@ -134,16 +136,17 @@ void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
switch (st.status) {
case ChildStatus::WORKING:
break;
case ChildStatus::COMPLETED:
if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k);
it != me->hedges.end())
me->hedges.erase(it);
break;
case ChildStatus::CANCELED:
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
algo().terminate_error("Unexpected child cancel");
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
std::remove(me->hedges.begin(), me->hedges.end(), k);
break;
case ChildStatus::COMPLETED:
std::remove(me->hedges.begin(), me->hedges.end(), k);
break;
}
}
@@ -167,7 +170,7 @@ void CoverAlgo::do_update(api::orderman::Update const &update) {
// process custom part of the udpate if any
if (update.has_custom()) {
auto &cover_update = update.custom().cover();
set_price_improvement_delta(algo(), cover_update);
update_definition(algo(), cover_update);
if (cover_update.has_child()) {
*child_update.mutable_custom() = cover_update.child();
}
@@ -194,11 +197,14 @@ void orderman::CoverAlgo::init_hedge_template(
me->hedge_template = &(algo.make_child_template(hedge_def));
}
void CoverAlgo::set_price_improvement_delta(
void CoverAlgo::update_definition(
IBeforeLaunchAlgoServices &serv,
api::orderman::CoverOrderDefinition const &cover) {
me->price_improvement_delta = Price(
securities::tick_size(serv.security()).value() * cover.hedge_ticks());
me->cancel_hedges_on_cancel = cover.cancel_hedges_on_cancel();
me->cancel_on_external_hedge_cancel =
cover.cancel_on_external_hedge_cancel();
}
void CoverAlgo::check_terminate() {
@@ -214,5 +220,12 @@ void CoverAlgo::check_terminate() {
}
}
IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
if (!me->cancel_hedges_on_cancel)
for (auto &k : me->hedges)
algo().detach_child(k);
return IAlgoOrder::OnCancelResponse::HONOR;
}
} // namespace orderman
} // namespace bts
@@ -18,6 +18,7 @@ public:
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
void do_update(api::orderman::Update const &) override;
void on_child_change(OrderKey, ChildState const &) override;
IAlgoOrder::OnCancelResponse on_cancel() override;
private:
struct PImpl;
@@ -25,7 +26,7 @@ private:
std::unique_ptr<PImpl> me;
IAlgoServices &algo() const;
void
set_price_improvement_delta(IBeforeLaunchAlgoServices &,
update_definition(IBeforeLaunchAlgoServices &,
api::orderman::CoverOrderDefinition const &);
void init_hedge_template(IBeforeLaunchAlgoServices &,
api::orderman::CustomOrderDefinition const &);