diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md
index 073897876..ebf921c38 100644
--- a/doc/user/content/release_notes/_index.md
+++ b/doc/user/content/release_notes/_index.md
@@ -4,6 +4,22 @@ weight = 3
sort_by = "weight"
insert_anchor_links = "right"
+++
+## 2.10.0
+### User Visible Changes
+ - Fills now include information about the algo that originated the fill
+### API Changes
+ - Added security state information (pre open, halted, normal, closed, etc)
+
+## 2.9.1
+### Bug Fixes
+ - Fixed an issue with trade sound alerts, where in some cases the use of a "In Between" condition could lead to a UI failure.
+ - Fixed an issue with the display of the new raw position column in the market view window.
+ - Fixed the popup label that describes the raw position information in the ladder
+### Internal Changes
+ - Avoided shipping production configuration defaults that lead to trying to download a position file for the development sftp server.
+### Api
+ - C# API sample now uses synchronous calls.
+
## 2.9.0
### User Visible Changes
- Improved Workspace management User Interface
diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs
index 6e7087128..ea1f86fbd 100644
--- a/src/client/spark/Images/Icons.cs
+++ b/src/client/spark/Images/Icons.cs
@@ -151,7 +151,7 @@ namespace mbts.ui {
public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey);
public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } }
public static ImageSource CopyWF => create_icon(CopyWFGeometryKey);
- public static ImageSource DataEdit => create_icon(DataEditGeometryKey, Brushes.White, new Pen(Brushes.Black, 1).frozen());
+ public static ImageSource DataEdit => create_icon(DataEditGeometryKey);
public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } }
public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red);
public static ImageSource Disk => create_icon(DiskGeometryKey);
diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml
index e44d4267a..0248f9523 100644
--- a/src/client/spark/Images/Vector/Icons.xaml
+++ b/src/client/spark/Images/Vector/Icons.xaml
@@ -1,7 +1,7 @@
@@ -18,9 +18,7 @@
Ttile: Add free icon
Credit: Icon made by Gregor Cresnar from www.flaticon.com-->
- M393,480.3c0-5-4.1-9.1-9.1-9.1H18.2V105.5c0-5-4.1-9.1-9.1-9.1S0,100.5,0,105.5v374.8c0,5,4.1,9.1,9.1,9.1h374.8 C388.9,489.4,393,485.3,393,480.3z
- M373.9,187.5H302v-71.9c0-5-4.1-9.1-9.1-9.1s-9.1,4.1-9.1,9.1v71.9h-71.9c-5,0-9.1,4.1-9.1,9.1s4.1,9.1,9.1,9.1h71.9v71.9 c0,5,4.1,9.1,9.1,9.1s9.1-4.1,9.1-9.1v-71.9h71.9c5,0,9.1-4.1,9.1-9.1C382.9,191.5,378.9,187.5,373.9,187.5z
- M105.5,393h374.8c5,0,9.1-4.1,9.1-9.1V9.1c0-5-4.1-9.1-9.1-9.1H105.5c-5,0-9.1,4.1-9.1,9.1v374.8 C96.4,388.9,100.5,393,105.5,393z M114.5,18.2h356.7v356.7H114.5V18.2z
+ M 87.5 10 C 80.313542 10 74.400391 15.913151 74.400391 23.099609 V 397.90039 C 74.400391 405.08685 80.313541 411 87.5 411 h 374.80078 c 7.18646 0 13.09961 -5.91315 13.09961 -13.09961 V 23.099609 C 475.40039 15.913151 469.48724 10 462.30078 10 Z m 13 26.199219 H 449.19922 V 384.90039 H 100.5 Z M 21.099609 76.400391 C 13.912943 76.400391 8 82.313333 8 89.5 v 374.80078 c 0 7.18667 5.912943 13.09961 13.099609 13.09961 H 395.90039 c 7.18667 0 13.09961 -5.91294 13.09961 -13.09961 0 -7.18667 -5.91294 -13.10156 -13.09961 -13.10156 H 34.199219 V 89.5 c 0 -7.186667 -5.912943 -13.099609 -13.09961 -13.099609 z M 274.90039 116.5 c -7.18667 0 -13.09961 5.91294 -13.09961 13.09961 V 197.5 h -67.90039 c -7.18667 0 -13.09961 5.91294 -13.09961 13.09961 0 7.18667 5.91294 13.09961 13.09961 13.09961 h 67.90039 v 67.90039 c 0 7.18667 5.91294 13.09961 13.09961 13.09961 7.18667 0 13.09961 -5.91294 13.09961 -13.09961 v -67.90039 h 67.90039 c 7.18667 0 13.09961 -5.91294 13.09961 -13.09961 v -0.0391 -0.0391 C 368.85982 203.37217 363.03372 197.5 355.90039 197.5 H 288 V 129.59961 C 288 122.41294 282.08706 116.5 274.90039 116.5 Z
-
+
diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs
index c214902cd..6f3688e77 100644
--- a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs
+++ b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs
@@ -92,7 +92,10 @@ namespace mbts.spark {
_dispose = Disposable.Create(
_orders_model.on_security_root_orders(security.Id).OnDispatcher().Subscribe(_on_orders),
_position.OnDispatcher().Subscribe(v => _animation.animate_position(v.newval > v.oldval)),
- _orders_model.on_security_positions(security.Id).OnDispatcher().Subscribe(t => Set(ref _raw_day_position, t.state.Values.Sum(p => p.Item2.raw_day_pos()), nameof(raw_day_position))),
+ _orders_model.on_security_positions(security.Id).OnDispatcher().Subscribe(t => {
+ if (Set(ref _raw_day_position, t.state.Values.Sum(p => p.Item2.raw_day_pos()), nameof(raw_day_position)))
+ raise_invalidated();
+ }),
_inside_bids.OnDispatcher().Subscribe(v => _animation.animate_working_bids_inside(v.newval)),
_inside_asks.OnDispatcher().Subscribe(v => _animation.animate_working_asks_inside(v.newval)),
_day_change.OnDispatcher().Subscribe(v => _animation.animate_day_change(v.newval > v.oldval)),
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoData.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoData.cs
index acb014317..3e5f12997 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoData.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoData.cs
@@ -19,6 +19,8 @@ namespace mbts.spark {
this.key = key;
}
+ public static AlgoData empty => from_custom_def(new CustomOrderDefinitionImmutable(new CustomOrderDefinition()));
+
///
/// This is the only factory method that allows callers to explicitly specify a name.
/// It should only be used within the context of creating, or renaming, studio algos.
@@ -65,6 +67,8 @@ namespace mbts.spark {
}
struct AlgoDataVM : IEquatable {
+ public static readonly Func id_fn = vm => AlgoID.from_algo_key(vm.data.key);
+
public readonly AlgoData data;
public readonly AlgoDefinitionMetadata? meta;
diff --git a/src/client/spark/Modules/Trading/Fills/FillsVM.cs b/src/client/spark/Modules/Trading/Fills/FillsVM.cs
index 9d8aecb9f..60ef0ee70 100644
--- a/src/client/spark/Modules/Trading/Fills/FillsVM.cs
+++ b/src/client/spark/Modules/Trading/Fills/FillsVM.cs
@@ -68,13 +68,51 @@ namespace mbts.spark {
nameof(OrderBookRowVM.symbol)),
DataGridFilterKnownTemplates.DiscreteValues,
DefaultColumnWidths.Symbol);
+ // algo items view (common resources)
+ var algo_items_comp = AlgoCollectionHelper.algo_data_vm_comparer.to_non_generic();
+ var algo_items_group_desc = new PropertyGroupDescription(nameof(AlgoDataVM.group));
// order type
- var order_type_filter = dv_filter(OrderDataHelper.all_order_types, r => r.order?.order_type() ?? OrderType.None);
+ var order_type_filter = DiscreteValuesFilterVM.CreateTableUpdate(
+ ft => new AlgoDataVM(ft.algo ?? AlgoData.empty),
+ AlgoDataVM.id_fn,
+ ots => Array.ConvertAll(ots ?? Array.Empty(), ot => AlgoID.from_algo_key(AlgoKey.from_known_type(ot))),
+ ids => ids.empty_if_null().Select(AlgoID.to_algo_key).Where(k => k.mode == AlgoKey.Mode.Factory).Select(k => k.factory).ToArray(),
+ out var order_type_observer,
+ out var order_type_items_view);
+
+ order_type_items_view.CustomSort = algo_items_comp;
+ order_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
+ order_type_observer.OnNext(TableUpdate.mk_empty(AlgoDataVM.id_fn)
+ .with_added(OrderDataHelper.all_order_types
+ .Select(OrderDataHelper.Defaults.CustomOrderDefinitionImmutable)
+ .Select(AlgoData.from_custom_def)
+ .Select(d => new AlgoDataVM(d))));
+
add_col_expl(Columns.OrderType,
new OrderTypeColumn(Columns.OrderType, new Binding(nameof(Row.badge_fill)), new Binding(nameof(Row.display_name)), order_type_filter) {
id = col_id(Columns.OrderType),
sort_member_path = nameof(Row.order_type)
}, order_type_filter);
+ // root algo type
+ var root_algo_type_filter = DiscreteValuesFilterVM.CreateTableUpdate(
+ ft => new AlgoDataVM(ft.root_algo ?? AlgoData.empty),
+ AlgoDataVM.id_fn,
+ out var root_algo_type_observer,
+ out var root_algo_type_items_view);
+
+ root_algo_type_items_view.CustomSort = algo_items_comp;
+ root_algo_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
+
+ add_col_expl(Columns.RootAlgoType,
+ new OrderTypeColumn(
+ Columns.RootAlgoType,
+ new Binding(nameof(Row.root_algo_badge_color)) { Converter = new ui.converters.ColorToBrushConverter() },
+ new Binding(nameof(Row.root_algo_display_name)),
+ root_algo_type_filter,
+ DefaultColumnHeaders.RootAlgoType) {
+ id = col_id(Columns.RootAlgoType),
+ sort_member_path = nameof(Row.root_algo_order_type)
+ }, root_algo_type_filter);
// side
var side_filter = dv_filter(new[] { Side.Buy, Side.Sell }, r => r.fill.Side);
add_col_expl(Columns.Side, new SideColumn(Columns.Side, r => r.side, side_filter) { id = col_id(Columns.Side) }, side_filter);
@@ -129,6 +167,7 @@ namespace mbts.spark {
};
_rows_manager.on_settings(fs, s.sorting_criterion);
}),
+ model.subscribe_all_algos().SelectKeyValue(AlgoDataVM.from_data, d => AlgoID.from_algo_key(d.data.key)).OnDispatcher().Subscribe(root_algo_type_observer),
settings_manager == null ? Disposable.empty : settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager)
);
// local methods
@@ -176,8 +215,8 @@ namespace mbts.spark {
static IObservable> _get_observable(IBus bus, OrdersModel model, FillsSettings state) {
if (!state.orders.is_null_or_empty()) {
var orders_hash = new HashSet(state.orders);
- return model.on_fill_tuples.Filter(f => orders_hash.Contains(f.fill.OrderKey));
- } else return model.on_fill_tuples;
+ return model.on_fill_tuples_with_root.Filter(f => orders_hash.Contains(f.fill.OrderKey));
+ } else return model.on_fill_tuples_with_root;
}
static IObservable> _get_observable(IBus bus, OrdersModel model, IObservable state) =>
@@ -193,6 +232,7 @@ namespace mbts.spark {
case Columns.FillTime: return wrap(ft => ft.fill.Timestamp.to_local_time());
case Columns.OrderKey: return wrap(ft => ft.fill.OrderKey);
case Columns.OrderType: return wrap_default(ft => ft.order?.order_type() ?? OrderType.None);
+ case Columns.RootAlgoType: return wrap_default(ft => ft.root_algo.HasValue ? ft.root_algo.Value.value.CustomCase : OrderType.None);
case Columns.Price: return wrap(ft => ft.fill.LastPrice);
case Columns.Security: return wrap(ft => ft.security ?? SecurityDataHelper.Defaults.SecurityImmutable);
case Columns.SecurityKey: return wrap(ft => ft.fill.SecurityKey);
@@ -226,7 +266,10 @@ namespace mbts.spark {
readonly OrdersModel _model;
readonly FillImmutable _fill;
readonly OrderRecordImmutable _order;
+ AlgoData? _root_algo => fill_tuple.root_algo;
+ AlgoDefinitionMetadata? _root_algo_meta => fill_tuple.root_algo_meta;
Brush _badge_fill;
+ Color? _root_algo_badge_color;
OrderMetadata _order_metadata;
public Row(FillTuple fill_tuple, OrdersModel model) :
@@ -241,6 +284,7 @@ namespace mbts.spark {
public DateTime fill_time => _fill.Timestamp.to_local_time();
public TimeInForce time_in_force => _order.time_in_force();
public OrderType order_type => _order.order_type();
+ //public OrderType root_algo_type => _or
public string display_name => OrderUtils.display_name(_order, fill_tuple.algo);
public OrderMetadata order_metadata => _order_metadata ?? (_order_metadata = _model.factory.get_metadata(_order.Def.CustomDef.CustomCase));
public Brush badge_fill => _badge_fill ?? (_badge_fill = OrderUtils.badge_fill(fill_tuple.algo_meta, order_metadata));
@@ -255,6 +299,12 @@ namespace mbts.spark {
public string fill_key => _fill.FillKey;
public string order_key => _order.Key.ToString();
+ // Root Algo
+ public OrderType root_algo_order_type => _root_algo.HasValue ? _root_algo.Value.value.CustomCase : OrderType.None;
+ public OrderMetadata root_algo_order_metadata => _model.factory.get_metadata(root_algo_order_type);
+ public Color root_algo_badge_color => _root_algo_badge_color ?? (_root_algo_badge_color = OrderUtils.badge_color(_root_algo_meta, root_algo_order_metadata)).Value;
+ public string root_algo_display_name => _root_algo?.name ?? root_algo_order_type.display_name();
+
public bool Equals(Row other) => other != null && other._fill.Equals(_fill) && other._order.Equals(_order);
public override bool Equals(object obj) => Equals(obj as Row);
public override int GetHashCode() => _fill.FillKey.GetHashCode() ^ _order.Key.GetHashCode();
diff --git a/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs b/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs
index 26ef7cfbb..9e34bc3e9 100644
--- a/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs
+++ b/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs
@@ -16,6 +16,7 @@ namespace mbts.ui.spark {
Symbol,
TimeInForce,
OrderType,
+ RootAlgoType,
Side,
Price,
Size,
diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs b/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs
index 8159abe53..1f3c73ce7 100644
--- a/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs
+++ b/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs
@@ -1,19 +1,15 @@
using bts.api;
-using bts.api.orderman;
+using bts.settings;
using bts.shell.fills;
using mbts.persist;
using mbts.spark;
-using mbts.spark.filters;
using mbts.ui;
-using mbts.ui.controls;
using mbts.ui.settings;
-using ProtoBuf;
using System;
using System.Collections.Generic;
-using System.Linq;
+using System.ComponentModel.Composition;
using System.Reactive.Linq;
using System.Threading.Tasks;
-using static mbts.ui.controls.DIYGrid;
using static mbts.ui.spark.FillsView;
namespace bts.shell {
@@ -34,13 +30,15 @@ namespace bts.shell {
{ nameof(FillsVM.Row.fill_time), Columns.FillTime },
{ nameof(FillsVM.Row.order_key), Columns.OrderKey },
{ nameof(FillsVM.Row.order_type), Columns.OrderType },
+ { nameof(FillsVM.Row.root_algo_order_type), Columns.RootAlgoType },
{ nameof(FillsVM.Row.price), Columns.Price },
{ nameof(FillsVM.Row.security), Columns.Security },
{ nameof(FillsVM.Row.security_key), Columns.SecurityKey },
{ nameof(FillsVM.Row.side), Columns.Side },
{ nameof(FillsVM.Row.size), Columns.Size },
{ nameof(FillsVM.Row.time_in_force), Columns.TimeInForce },
- { nameof(FillsVM.Row.user), Columns.User }
+ { nameof(FillsVM.Row.user), Columns.User },
+ { nameof(FillsVM.Row.fill_status ), Columns.FillStatus },
};
public FillsWindowFactory(TradingShellModule module, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model)
@@ -67,8 +65,12 @@ namespace bts.shell {
set: (us, gs) => us.with(provided_fills_gridsettings: gs));
return new FillsWindow(this, _bus, _orders_model, state, settings_manager);
}
- [ProtoMember(15)]
- [DIYGridColumnID(nameof(Columns.FillStatus))]
- public Fill.Types.FillStatus[] fill_status { get; set; }
+
+ // migration rules
+ [Export(typeof(IFillsGridSettingsMigrationRule))]
+ class AddMissingColumnsMigrationRule : IFillsGridSettingsMigrationRule {
+ public bool apply(GridSettings settings, out GridSettings new_settings) =>
+ settings.add_missing_columns(FillsSettings.DefaultGridSettings.columns, out new_settings);
+ }
}
}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs b/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs
index 653393258..efa5d3aa2 100644
--- a/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs
+++ b/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs
@@ -23,6 +23,10 @@ namespace bts.shell.fills {
[DIYGridColumnID(nameof(Columns.OrderType))]
public CustomOrderDefinition.CustomOneofCase[] order_type { get; set; }
+ [ProtoMember(16)]
+ [DIYGridColumnID(nameof(Columns.RootAlgoType))]
+ public AlgoID[] root_algo_type { get; set; }
+
[ProtoMember(4)]
[DIYGridColumnID(nameof(Columns.Account))]
public string[] account { get; set; }
@@ -92,6 +96,7 @@ namespace bts.shell.fills {
pb.add_discrete_values(fs.exchange, ft => ft.exchange());
pb.add_discrete_values(fs.time_in_force, ft => ft.time_in_force());
pb.add_discrete_values(fs.order_type, ft => ft.order_type());
+ pb.add_discrete_values(fs.root_algo_type, ft => AlgoID.from_algo_key((ft.root_algo ?? AlgoData.empty).key));
pb.add_discrete_values(fs.side, ft => ft.fill.Side);
pb.add_discrete_values(fs.fill_kind, ft => ft.fill.FillKind);
pb.add_discrete_values(fs.symbol, ft => ft.security?.Symbol ?? string.Empty);
diff --git a/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs
index 63ace677e..d6a24363d 100644
--- a/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs
+++ b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs
@@ -47,6 +47,7 @@ namespace bts.shell.fills {
public static GridColumnSettings exchange => new GridColumnSettings(col_id(Columns.Exchange), DefaultColumnHeaders.Exchange, width: DefaultColumnWidths.Exchange);
public static GridColumnSettings time_in_force => new GridColumnSettings(col_id(Columns.TimeInForce), DefaultColumnHeaders.TimeInForce, width: DefaultColumnWidths.TimeInForce);
public static GridColumnSettings order_type => new GridColumnSettings(col_id(Columns.OrderType), DefaultColumnHeaders.OrderType, width: DefaultColumnWidths.OrderType);
+ public static GridColumnSettings root_algo_type => new GridColumnSettings(col_id(Columns.RootAlgoType), DefaultColumnHeaders.RootAlgoType, width: DefaultColumnWidths.OrderType);
public static GridColumnSettings side => new GridColumnSettings(col_id(Columns.Side), DefaultColumnHeaders.Side, width: DefaultColumnWidths.Side);
public static GridColumnSettings quantity => new GridColumnSettings(col_id(Columns.Size), DefaultColumnHeaders.Size, width: DefaultColumnWidths.Size, horizontal_alignment: System.Windows.HorizontalAlignment.Right);
public static GridColumnSettings price => new GridColumnSettings(col_id(Columns.Price), DefaultColumnHeaders.Price, width: DefaultColumnWidths.Price, horizontal_alignment: System.Windows.HorizontalAlignment.Right);
@@ -70,6 +71,7 @@ namespace bts.shell.fills {
yield return exchange;
yield return time_in_force;
yield return order_type;
+ yield return root_algo_type;
yield return side;
yield return quantity;
yield return price;
diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs
index 2bd48534a..f72d2cc1c 100644
--- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs
+++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs
@@ -138,7 +138,7 @@ namespace mbts.spark {
//
//_window_height = backing(nameof(window_height), settings_manager.subscribe_current().OnDispatcher().Select(s => s.zoom_factor), (scale) => scale * 600);
//_window_width = backing(nameof(window_width), settings_manager.subscribe_current().OnDispatcher().Select(s => s.zoom_factor), (scale) => scale * 420);
- position_click_command = new DelegateCommand(() => size_calculator.value = DoubleHelper.safe_convert_to_uint(Math.Abs(_show_day_position ? day_position : position)));
+ position_click_command = new DelegateCommand(() => size_calculator.value = DoubleHelper.safe_convert_to_uint(Math.Abs(_show_day_position ? day_position : (_show_raw_day_position ? _raw_day_position : position))));
send_order_command = new AsyncCommand<(double price, Side? side, MouseButton button)>(send_order_async);
cancel_command = new AsyncCommand(_model.cancel_orders, true);
show_book_command = new DelegateCommand(_show_book);
diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
index 5e041034f..b761e9b75 100644
--- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
+++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
@@ -487,6 +487,7 @@
+
diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
index efaf28cda..015680d5c 100644
--- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
+++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
@@ -18,32 +18,60 @@ namespace mbts.spark {
MaxZoomFactor = 1.5;
public static IMultiValueConverter PositionToolTipConverter =
- ValueConverter.create((account, show_day_pos, show_total_pos) => {
- const string day_pos_text = "day", total_pos_text = "total";
+ ValueConverter.create((account, show_day_pos, show_raw_day_pos, show_total_pos) => {
+ const string day_pos_text = "day", raw_day_pos_text = "raw day", total_pos_text = "total";
if (!account.HasValue)
return string.Empty;
- var sb = new StringBuilderEx(account.Value.name);
- string primary_pos;
- if (show_day_pos) {
- primary_pos = day_pos_text;
- if (show_total_pos) {
- sb.Add(" '", primary_pos, " ");
- sb.Add("(", total_pos_text, ")' ");
- } else {
- sb.Add(" ", primary_pos, " ");
- }
- } else if (show_total_pos) {
- primary_pos = total_pos_text;
- sb.Add(" ", primary_pos, " ");
+ /// Note: 'day,' and 'raw day,' are interchangeable wrt the string format, 'total' however is treated differently.
+ /// Different Formats:
+ // No parts are visible:
+ // null
+ //
+ // 1 part 'foo' is visible:
+ // " foo position
+ // click to copy to size"
+ //
+ // 2 parts 'day' and 'raw day' are visible:
+ // " 'day / raw day' position
+ // click to copy day to size"
+ //
+ // 2 parts 'day' and 'total' are visible:
+ // " 'day (total)' position
+ // click to copy day to size"
+ //
+
+ string primary_pos = null;
+ // part count is incremented in the 'add_part' method
+ int part_count = 0;
+ var sb = new StringBuilderEx();
+
+ if (show_day_pos) add_part(day_pos_text, " / ");
+ if (show_raw_day_pos) add_part(raw_day_pos_text, " / ");
+ if (show_total_pos) add_part(total_pos_text, " (", ")");
+ //
+ if (part_count > 1) {
+ // This is a complex expression (showing more than 1 value) - wrap it in single quotes.
+ // Explicitly state which value will be copied to the size input.
+ sb.Insert(0, "'");
+ sb.Add("'");
+ sb.Add(" position\n(click to copy ", primary_pos, " to size)");
} else {
- // unexpected code path (the button for which this tooltip is destined should be invisible in this case), but no need to throw an exception.
- return string.Empty;
+ // Only showing 1 value, no need for single quotes,
+ // nor an explicit statement that indicates which value will be copied to the size input.
+ sb.Add(" position\n(click to copy to size)");
}
- sb.Add("position\n(click to copy ");
- if (show_day_pos && show_total_pos)
- sb.Add(primary_pos, " position ");
- sb.Add("to size)");
return sb.ToString();
+
+ void add_part(string part_name, string separator = null, string separator_suffix = null) {
+ if (part_count++ > 0) {
+ sb.Add(separator);
+ sb.Add(part_name);
+ sb.Add(separator_suffix);
+ } else {
+ primary_pos = part_name;
+ sb.Add($"{account.Value.name} {part_name}");
+ }
+ }
});
internal LadderView(LadderVM vm) {
diff --git a/src/client/spark/Orders/FillTuple.cs b/src/client/spark/Orders/FillTuple.cs
index 40f4f65d6..02b4bc396 100644
--- a/src/client/spark/Orders/FillTuple.cs
+++ b/src/client/spark/Orders/FillTuple.cs
@@ -2,28 +2,40 @@
using bts.api.orderman;
using bts.utils;
using System;
-
using static bts.api.orderman.Fill.Types;
namespace mbts.spark {
class FillTuple : IEquatable {
public static readonly Func key_fn = ft => ft.fill.FillKey;
public readonly FillImmutable fill;
- public readonly OrderRecordImmutable? order;
public readonly SecurityImmutable? security;
- public readonly AlgoData? algo;
- public readonly AlgoDefinitionMetadata? algo_meta;
- public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderSecurity? order_tuple) {
- this.fill = fill.val;
- this.security = fill.sec;
- if (order_tuple is OrderSecurity osam) {
- order = osam.order;
- algo = osam.algo;
- algo_meta = osam.meta;
- }
+ OrderSecurityRootPair? _order_tuple;
+
+ public FillTuple(FillImmutable fill, SecurityImmutable? security, OrderSecurityRootPair? order_tuple) {
+ this.fill = fill;
+ this.security = security;
+ _order_tuple = order_tuple;
}
+ public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderSecurity? order_tuple)
+ : this(fill.val, fill.sec, OrderSecurityRootPair.from_order_security(order_tuple.Value)) { }
+
+ public AlgoData? algo =>
+ _order_tuple.HasValue ? _order_tuple.Value.order.algo : (AlgoData?)null;
+
+ public AlgoDefinitionMetadata? algo_meta =>
+ _order_tuple.HasValue ? _order_tuple.Value.order.meta : null;
+
+ public OrderRecordImmutable? order =>
+ _order_tuple.HasValue ? _order_tuple.Value.order.order : (OrderRecordImmutable?)null;
+
+ public AlgoData? root_algo =>
+ _order_tuple.HasValue ? _order_tuple.Value.root.algo : (AlgoData?)null;
+
+ public AlgoDefinitionMetadata? root_algo_meta =>
+ _order_tuple.HasValue ? _order_tuple.Value.root.meta : null;
+
public string account {
get {
var account_string = string.Empty;
@@ -33,12 +45,14 @@ namespace mbts.spark {
}
}
- public bool Equals(FillTuple other) => other != null
- && other.order.HasValue == order.HasValue
- && other.security.HasValue == security.HasValue
- && other.fill.Equals(fill);
+ public bool Equals(FillTuple other) =>
+ other != null &&
+ _order_tuple.Equals(other._order_tuple) &&
+ security.HasValue == other.security.HasValue &&
+ fill.Equals(other.fill);
- public override bool Equals(object obj) => Equals(obj as FillTuple);
+ public override bool Equals(object obj) =>
+ Equals(obj as FillTuple);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs
index 45777959f..7c9276b23 100644
--- a/src/client/spark/Orders/OrdersModel.cs
+++ b/src/client/spark/Orders/OrdersModel.cs
@@ -132,7 +132,7 @@ namespace mbts.spark {
OrderSecurityRootPair.from_order_security,
OrderSecurityHelper.root_pair_key_fn
).Cache();
- // fills
+ // fill tuples
var on_fills =
_service.subscribei_fills()
.Naggle(interval, scheduler)
@@ -148,6 +148,16 @@ namespace mbts.spark {
(f, fk, ok) => new FillTuple(f, null),
f => f.fill.FillKey);
on_fill_tuples = fill_order_tuples_join.Cache();
+ // fill tuples with root (algo)
+ var fill_order_tuples_with_root_join = on_fills.LeftJoin(
+ on_order_tuples_with_root,
+ f => f.val.FillKey,
+ OrderSecurityHelper.root_pair_key_fn,
+ f => f.val.OrderKey,
+ (f, fk, o, ok) => new FillTuple(f.val, f.sec, o),
+ (f, fk, ok) => new FillTuple(f.val, f.sec, null),
+ FillTuple.key_fn);
+ on_fill_tuples_with_root = fill_order_tuples_with_root_join.Cache();
// manual fills
on_manual_fills_securities = _position_service.subscribei_manual_fills()
.Naggle(interval, scheduler)
@@ -211,6 +221,7 @@ namespace mbts.spark {
public IObservable, uint>> on_orders_can_attach { get; }
public IObservable> on_order_securities { get; }
public IObservable> on_fill_tuples { get; }
+ public IObservable> on_fill_tuples_with_root { get; }
public IObservable> working_orders { get; }
public IObservable> on_positions { get; }
public IObservable> studio_algos_with_meta { get; }
diff --git a/src/client/spark/Predicates/IPredicate.cs b/src/client/spark/Predicates/IPredicate.cs
index c5ae09899..b1cdcbf94 100644
--- a/src/client/spark/Predicates/IPredicate.cs
+++ b/src/client/spark/Predicates/IPredicate.cs
@@ -215,7 +215,7 @@ namespace mbts {
_second.Equals(other._second);
public override bool Equals(object obj) =>
- Equals(obj is OrTrigger);
+ Equals(obj as OrTrigger);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
@@ -256,7 +256,7 @@ namespace mbts {
$"OrTrigger ({_first}, {_second})";
}
- class GreaterThanTrigger : IPredicate {
+ class GreaterThanTrigger : IPredicate, IEquatable> {
readonly T _value;
readonly IComparer _comparer;
@@ -268,6 +268,17 @@ namespace mbts {
public bool trigger(T value) =>
_comparer.Compare(value, _value) > 0;
+ public bool Equals(GreaterThanTrigger other) =>
+ other != null &&
+ _comparer.Equals(other._comparer) &&
+ _comparer.Compare(_value, other._value) == 0;
+
+ public override bool Equals(object obj) =>
+ Equals(obj as GreaterThanTrigger);
+
+ public override int GetHashCode() =>
+ _value.GetHashCode();
+
public override string ToString() =>
$"GreaterThanTrigger ({_value})";
}
diff --git a/src/client/spark/core/Collections/KeyedItemSelector.cs b/src/client/spark/core/Collections/KeyedItemSelector.cs
index cac1a32fd..e93b48697 100644
--- a/src/client/spark/core/Collections/KeyedItemSelector.cs
+++ b/src/client/spark/core/Collections/KeyedItemSelector.cs
@@ -200,17 +200,20 @@ namespace mbts.collections {
public ObservableCollectionEx selected_items { get; } = new ObservableCollectionEx();
public IEnumerable selected_keys => selected_items.Select(_key_selector);
- public bool try_select(TKey key) {
+ public bool try_select(TKey key) =>
+ try_select(key, true);
+
+ public bool try_select(TKey key, bool reattempt_on_collection_change) {
if (items.TryGetFirst(i => _key_selector(i).Equals(key), out T result)) {
selected_items.Add(result);
return true;
- } else {
+ } else if (reattempt_on_collection_change) {
if (_desired_keys.Count == 0) {
items.CollectionChanged += _on_items_CollectionChanged;
}
_desired_keys.Add(key);
- return false;
}
+ return false;
}
void _on_items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
diff --git a/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs b/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs
index 2091f8550..5429752d0 100644
--- a/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs
+++ b/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs
@@ -1,4 +1,5 @@
-using mbts.ui.settings;
+using bts.utils;
+using mbts.ui.settings;
using System;
using System.Collections.Generic;
@@ -11,8 +12,9 @@ namespace bts.settings {
// should be exposed through explicitly named interfaces that inherit ISettingsMigrationRule.
// This avoids magic const names in the MEF import/export contracts, which would otherwise be needed to
// determine the various windows to which such rules apply.
- interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule { }
+ interface IFillsGridSettingsMigrationRule : ISettingsMigrationRule { }
interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule { }
+ interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule { }
static class SettingsMigrationHelper {
public static bool apply(T settings, IEnumerable> migration_rules, out T new_settings) {
@@ -35,6 +37,9 @@ namespace bts.settings {
public static ISettingsMigrationRule merge(this IEnumerable> rules) =>
new MergeWrapper(rules);
+ public static ISettingsMigrationRule wrap(this ISettingsMigrationRule rule, IImmutableProperty propi) =>
+ new SelectorWrapper(rule, propi.get, propi.set);
+
public static ISettingsMigrationRule wrap(this ISettingsMigrationRule rule, Func get, Func set) =>
new SelectorWrapper(rule, get, set);
diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs
index 698c4c5ec..e374ff0ed 100644
--- a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs
+++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs
@@ -20,22 +20,32 @@ namespace mbts.persist {
class UserSettingsHub {
// do NOT CHANGE these consts, they represent a file path on the server
const string NAME_SPACE = "settings", DEFAULT_KEY = "default";
- IUserPersist _persist;
- UserSettings _default_settings;
- readonly BehaviorSubject _default_settings_subject = new BehaviorSubject(UserSettings.factory_defaults);
+
+ static readonly IImmutableProperty
+ _fills_propi = ImmutableProperty.create(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)),
+ _mview_propi = ImmutableProperty.create(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)),
+ _pandl_propi = ImmutableProperty.create(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs));
+
readonly object _default_settings_lock = new object();
- readonly IEnumerable _pandl_migration_rules;
+ readonly BehaviorSubject _default_settings_subject = new BehaviorSubject(UserSettings.factory_defaults);
+ readonly IEnumerable _fills_migration_rules;
readonly IEnumerable _mview_migration_rules;
+ readonly IEnumerable _pandl_migration_rules;
+ readonly IUserPersist _persist;
+
+ UserSettings _default_settings;
[ImportingConstructor]
public UserSettingsHub(
IUserPersist persist,
- [ImportMany]IEnumerable pandl_migration_rules,
- [ImportMany]IEnumerable mview_migration_rules) {
+ [ImportMany]IEnumerable fills_migration_rules,
+ [ImportMany]IEnumerable mview_migration_rules,
+ [ImportMany]IEnumerable pandl_migration_rules) {
//
_persist = persist;
- _pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty();
+ _fills_migration_rules = fills_migration_rules ?? Enumerable.Empty();
_mview_migration_rules = mview_migration_rules ?? Enumerable.Empty();
+ _pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty();
init();
async void init() {
UserSettings s;
@@ -43,8 +53,9 @@ namespace mbts.persist {
s = await _persist.get(NAME_SPACE, DEFAULT_KEY);
if (s != null) {
var wrapped_rules = new[] {
- _pandl_migration_rules.merge().wrap(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)),
- _mview_migration_rules.merge().wrap(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs))
+ _fills_migration_rules.merge().wrap(_fills_propi),
+ _mview_migration_rules.merge().wrap(_mview_propi),
+ _pandl_migration_rules.merge().wrap(_pandl_propi)
};
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
// TODO: move ladder sanitization logic into ISettingsMigrationRule
@@ -80,13 +91,6 @@ namespace mbts.persist {
}
}
- // indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
- public bool initialized { get; private set; }
-
- /// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
- /// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
- public IObservable subscribe_default_settings() => _default_settings_subject.AsObservable();
-
internal UserSettings current {
get {
lock (_default_settings_lock)
@@ -94,19 +98,30 @@ namespace mbts.persist {
}
}
- public IWindowSettingsManager create_pandl_settings_manager(GridSettings instance_settings) =>
+ // indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
+ public bool initialized { get; private set; }
+
+ /// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
+ /// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
+ public IObservable subscribe_default_settings() => _default_settings_subject.AsObservable();
+
+ public IWindowSettingsManager create_fills_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
- _pandl_migration_rules,
- us => us.pnl_grid,
- (us, gs) => us.with(provided_pnl_gridsettings: gs));
+ _fills_migration_rules,
+ _fills_propi);
public IWindowSettingsManager create_mview_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_mview_migration_rules,
- us => us.market_view_grid,
- (us, gs) => us.with(provided_market_view_gridsettings: gs));
+ _mview_propi);
+
+ public IWindowSettingsManager create_pandl_settings_manager(GridSettings instance_settings) =>
+ _create_settings_manager(
+ instance_settings,
+ _pandl_migration_rules,
+ _pandl_propi);
public async Task save_default(UserSettings value) {
// notify observers before persisting so the changes are reflected immediately in the ui
@@ -116,10 +131,10 @@ namespace mbts.persist {
await _persist_async();
}
- IWindowSettingsManager _create_settings_manager(T instance_settings, IEnumerable> migration_rules, Func get, Func set) where T : class {
+ IWindowSettingsManager _create_settings_manager(T instance_settings, IEnumerable> migration_rules, IImmutableProperty propi) where T : class {
if (instance_settings != null && migration_rules.merge().apply(instance_settings, out var new_settings))
instance_settings = new_settings;
- return new WindowSettingsManager(this, instance_settings, get, set);
+ return new WindowSettingsManager(this, instance_settings, propi.get, propi.set);
}
async Task _persist_async() {
diff --git a/src/client/spark/core/Utility/IImmutableProperty.cs b/src/client/spark/core/Utility/IImmutableProperty.cs
new file mode 100644
index 000000000..33079d110
--- /dev/null
+++ b/src/client/spark/core/Utility/IImmutableProperty.cs
@@ -0,0 +1,31 @@
+using System;
+
+namespace bts.utils {
+ ///
+ /// A property-like interface (with get/set accessors) in the immutable pattern. The 'set' method returns a new instance of , rather than mutating the original.
+ ///
+ /// The type of source, from which the value is read, and to which it is written.
+ /// The type of value read from, and written to, the source.
+ interface IImmutableProperty {
+ T get(TSource source);
+ TSource set(TSource source, T value);
+ }
+
+ static class ImmutableProperty {
+ public static IImmutableProperty create(Func get, Func set) =>
+ new Impl(get, set);
+
+ class Impl : IImmutableProperty {
+ readonly Func _get;
+ readonly Func _set;
+
+ public Impl(Func get, Func set) {
+ _get = get;
+ _set = set;
+ }
+
+ public T get(TSource source) => _get(source);
+ public TSource set(TSource source, T value) => _set(source, value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/OrderTypeColumn.cs b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/OrderTypeColumn.cs
index b06958305..1b67efb4e 100644
--- a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/OrderTypeColumn.cs
+++ b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/OrderTypeColumn.cs
@@ -16,7 +16,7 @@ namespace mbts.ui.controls {
}
public IDataGridColumnFilter filter { get; }
- public virtual string filter_template => DataGridFilterKnownTemplates.DiscreteValues;
+ public virtual string filter_template => DataGridFilterKnownTemplates.AlgoType;
public BindingBase font_weight_binding { get; set; }
public override FrameworkElement view_factory() {
diff --git a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs
index be1856777..dbe2f5666 100644
--- a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs
+++ b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs
@@ -63,8 +63,24 @@ namespace mbts.spark.filters {
) => new DynamicItemsFilter(items, get_row_val, get_state, load_state, prop_name, equality_comparer ?? EqualityComparer.Default, comparer);
public static IDataGridColumnPersistentFilter CreateTableUpdate(
- Func factory, Func key, out IObserver> items_observer, out ListCollectionView items_view) where TKey : struct, IEquatable {
- var filter = new TableUpdateItemsFilter(factory, key, keys => keys, keys => keys.ToArray());
+ Func factory,
+ Func key,
+ out IObserver> items_observer,
+ out ListCollectionView items_view)
+ where TKey : struct, IEquatable =>
+ //
+ CreateTableUpdate(factory, key, keys => keys, keys => keys.ToArray(), out items_observer, out items_view);
+
+ public static IDataGridColumnPersistentFilter CreateTableUpdate(
+ Func factory,
+ Func key,
+ Func> load_state,
+ Func, TState> get_state,
+ out IObserver> items_observer,
+ out ListCollectionView items_view)
+ where TKey : struct, IEquatable {
+ //
+ var filter = new TableUpdateItemsFilter(factory, key, load_state, get_state);
items_observer = filter;
items_view = filter.items_view;
return filter;
@@ -297,7 +313,7 @@ namespace mbts.spark.filters {
_items.Replace(_key(ch.Old), ch.New);
foreach (var v in table.added)
_items.Add(v);
- var newly_selected_keys = _desired_keys.Where(_selection_model.try_select).ToList();
+ var newly_selected_keys = _desired_keys.Where(k => _selection_model.try_select(k, false)).ToList();
if (newly_selected_keys.Count > 0) {
_selected_keys.AddRange(newly_selected_keys);
_desired_keys.removeRange(newly_selected_keys);
@@ -323,7 +339,7 @@ namespace mbts.spark.filters {
protected override bool _filter(TValue value) => _selected_keys.Contains(_key(value));
protected override void _load_state_internal(TState state) {
foreach (var k in _load_state(state).empty_if_null()) {
- if (!_selection_model.try_select(k))
+ if (!_selection_model.try_select(k, false))
_desired_keys.Add(k);
}
}
diff --git a/src/client/spark/view/Converters/AnonymousValueConverter.cs b/src/client/spark/view/Converters/AnonymousValueConverter.cs
index 6f6771ce0..8d504e873 100644
--- a/src/client/spark/view/Converters/AnonymousValueConverter.cs
+++ b/src/client/spark/view/Converters/AnonymousValueConverter.cs
@@ -16,6 +16,9 @@ namespace mbts.ui.converters {
public static IMultiValueConverter create(Func convert) =>
new AnonymousMultiValueConverter(convert);
+
+ public static IMultiValueConverter create(Func convert) =>
+ new AnonymousMultiValueConverter(convert);
}
static class ValueConverters {
@@ -92,4 +95,17 @@ namespace mbts.ui.converters {
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
+
+ class AnonymousMultiValueConverter : IMultiValueConverter {
+ readonly Func _convert;
+
+ public AnonymousMultiValueConverter(Func convert) => _convert = convert;
+
+ public TOut ErrorValue { get; set; }
+
+ public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
+ ConvertUtils.try_convert_args(values, out TIn1 a, out TIn2 b, out TIn3 c, out TIn4 d) ? _convert(a, b, c, d) : ErrorValue;
+
+ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
+ }
}
diff --git a/src/client/spark_api/md/MarketDataClient.cs b/src/client/spark_api/md/MarketDataClient.cs
index 3e5e0b4fb..e1441fb47 100644
--- a/src/client/spark_api/md/MarketDataClient.cs
+++ b/src/client/spark_api/md/MarketDataClient.cs
@@ -213,10 +213,18 @@ namespace bts.md
return _data.Values.Where(filt);
}
- public SecurityImmutable? find_security(Func filter)
+ public SecurityImmutable? find_security(Func filter, TimeSpan? timeout = null)
{
- var fnd = find(filter).TryFirst();
- return fnd?.security;
+ var deadline = DateTime.UtcNow;
+ if (timeout.HasValue) deadline += timeout.Value;
+ do {
+ var fnd = find(filter).TryFirst();
+ if (fnd.HasValue) {
+ return fnd?.security;
+ }
+ Thread.Sleep(100);
+ } while (DateTime.UtcNow < deadline);
+ return null;
}
public async Task find_security_async(Func filter, TimeSpan? timeout = null)
diff --git a/src/client/spark_sdk/samples/OrderSample.cs b/src/client/spark_sdk/samples/OrderSample.cs
index aec01460e..31f16eed3 100644
--- a/src/client/spark_sdk/samples/OrderSample.cs
+++ b/src/client/spark_sdk/samples/OrderSample.cs
@@ -36,7 +36,7 @@ namespace bts.sdk
Console.WriteLine();
}
- public async Task> send_order(string user, string account ,
+ public Response send_order(string user, string account ,
string exch, string sectype, string symbol, string security_desc, string qty, string price = null)
{
Venue ven = MarketDataSample.parse_venue(exch);
@@ -49,7 +49,7 @@ namespace bts.sdk
int quan = int.Parse(qty);
Create cr = new Create();
- await order_setup(cr, user, account);
+ order_setup(cr, user, account);
cr.Price = px;
cr.Quantity = Convert.ToUInt32(Math.Abs(quan));
cr.NewOrder.Side = quan < 0 ? Side.Sell : Side.Buy;
@@ -57,12 +57,15 @@ namespace bts.sdk
cr.NewOrder.CustomDef = new CustomOrderDefinition() { Limit = new LimitOrderDefinition() };
else
cr.NewOrder.CustomDef = new CustomOrderDefinition() { Market = new MarketOrderDefinition() };
- var sec = await _md.find_security_async(x => x.Glbx.SecurityDesc == security_desc.ToUpper());
+ Console.WriteLine("Fetching security details...");
+ var sec = _md.find_security(x => x.Glbx.SecurityDesc == security_desc.ToUpper(), TimeSpan.FromSeconds(30));
+ if (!sec.HasValue) {
+ Console.WriteLine($"Failed to find security {security_desc}.");
+ return null;
+ }
cr.NewOrder.SecurityKey = sec.Value.Id;
- Result resp = await _orders.Value.create_order_async(cr);
+ Response resp = _orders.Value.create_order(cr);
print_update(resp);
- if(resp.value != null)
- print_update(resp.value);
//subscribei_ subscribes to a stream of Immutable (in this case FillImmutable) which is nice if you know you don't want to change the fills, which you dont'
_disps.Add(_orders.Value.subscribei_fills().Subscribe(x =>
{
@@ -80,7 +83,7 @@ namespace bts.sdk
return resp;
}
- static async Task order_setup(Create cr, string username, string accountname)
+ static void order_setup(Create cr, string username, string accountname)
{
cr.NewOrder = new OrderDefinition();
cr.NewOrder.ManualOrderIndicator = ManualOrderIndicator.Yes;
@@ -88,12 +91,8 @@ namespace bts.sdk
cr.NewOrder.CustomerOrFirm = CustomerOrFirm.Firm;
cr.NewOrder.SubType = OrderSubType.None;
cr.NewOrder.TimeInForce = TimeInForce.Day;
- var admin = await _admin.Value.get_admin_data_async(new VoidMessage());
- if (!admin.success) {
- Console.Error.WriteLine(admin.error_message);
- return;
- }
- BTSUser user = admin.value.Users.FirstOrDefault( x=> username != null ? x.Name.ToLowerInvariant() == username.ToLowerInvariant() : true );
+ var admin = _admin.Value.get_admin_data(new VoidMessage());
+ BTSUser user = admin.Users.FirstOrDefault( x=> username != null ? x.Name.ToLowerInvariant() == username.ToLowerInvariant() : true );
if (user != null)
{
cr.NewOrder.UserId = (uint)user.Id;
@@ -102,11 +101,11 @@ namespace bts.sdk
{
var accid = user.UserData.AccountPermissions.AccountPermissions.FirstOrDefault();
cr.NewOrder.AccountId = (uint)accid.Key;
- cr.NewOrder.Account = admin.value.Accounts.First(x => x.Id == accid.Key).Name;
+ cr.NewOrder.Account = admin.Accounts.First(x => x.Id == accid.Key).Name;
}
else
{
- var acc = admin.value.Accounts.FirstOrDefault(x => x.Name.ToLowerInvariant() == accountname.ToLowerInvariant());
+ var acc = admin.Accounts.FirstOrDefault(x => x.Name.ToLowerInvariant() == accountname.ToLowerInvariant());
if (acc != null)
{
cr.NewOrder.Account = acc.Name;
diff --git a/src/client/spark_sdk/samples/SDKMain.cs b/src/client/spark_sdk/samples/SDKMain.cs
index f0fb158d8..9f48e2e54 100644
--- a/src/client/spark_sdk/samples/SDKMain.cs
+++ b/src/client/spark_sdk/samples/SDKMain.cs
@@ -13,28 +13,25 @@ namespace bts.sdk
public class SDKMain
{
- static async Task login(string user, string pass)
- {
- return await Locator.login(user, pass);
- }
- private static void user_test()
+ private static void user_test(ServiceContext ctx)
{
- var s = Locator.locate();
+ var s = ctx.locate();
var r = new api.user.GetUsersRequest();
var resp = s.get_users(r);
Console.WriteLine("{0}", resp);
}
- public async static Task Main(string[] args)
+ public static void Main(string[] args)
{
BTS.init();
Log.ClientSdk.info("Welcome to the BTS Client Side SDK example");
+ var ctx = new ServiceContext();
string u = args.FirstOrDefault(x => x.Contains("--user="));
string p = args.FirstOrDefault(x => x.Contains("--pass="));
u = u?.Replace("--user=", string.Empty) ?? string.Empty;
p = p?.Replace("--pass=", string.Empty) ?? string.Empty;
- var lr = await login(u, p);
+ var lr = ctx.login(u,p).Result;
if (!lr.success)
{
Console.WriteLine("Login failure: " + lr.reason);
@@ -43,7 +40,7 @@ namespace bts.sdk
if (args.FirstOrDefault() == "users")
{
- user_test();
+ user_test(ctx);
}
else
{
@@ -52,55 +49,56 @@ namespace bts.sdk
if (pu != null)
ms = uint.Parse(p.Replace("--pump=", string.Empty));
- MarketDataClient client = new MarketDataClient(ms, Locator.token);
- CompositeDisposable disp = new CompositeDisposable(client);
- if (args.Length > 0 && args.FirstOrDefault().Contains("md"))
- {
- var s = new MarketDataSample(client);
- if (args.FirstOrDefault() == "md")
+ MarketDataClient client = new MarketDataClient(ms, ctx.token);
+ using(var disp = new CompositeDisposable(client)) {
+ if (args.Length > 0 && args.FirstOrDefault().Contains("md"))
{
- if (args.Length >= 5)
+ var s = new MarketDataSample(client);
+ if (args.FirstOrDefault() == "md")
{
- s.print_security(args[1], args[2], args[3], args[4]);
- }
- else if (args.Length >= 4)
- {
- s.print_product(args[1], args[2], args[3]);
+ if (args.Length >= 5)
+ {
+ s.print_security(args[1], args[2], args[3], args[4]);
+ }
+ else if (args.Length >= 4)
+ {
+ s.print_product(args[1], args[2], args[3]);
+ }
+ else
+ md_help();
}
else
md_help();
}
+ else if (args.FirstOrDefault() == "order")
+ {
+ OrderSample os = new OrderSample(client);
+ disp.Add(os);
+ order_sample(os, u, args);
+ }
else
- md_help();
- }
- else if (args.FirstOrDefault() == "order")
- {
- OrderSample os = new OrderSample(client);
- disp.Add(os);
- order_sample(os, u, args);
- }
- else
- help();
+ help();
- wait_for_stop(disp);
+ wait_for_stop();
+ }
}
}
- static async void order_sample(OrderSample os, string user, string[] args)
+ static void order_sample(OrderSample os, string user, string[] args)
{
if (args.Length >= 10) //--user and --pass are in args[]
{
- await os.send_order(user, args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
+ os.send_order(user, args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
}
else if (args.Length >= 9)
{
- await os.send_order(user, args[1], args[2], args[3], args[4], args[5], args[6]);
+ os.send_order(user, args[1], args[2], args[3], args[4], args[5], args[6]);
}
else
order_help();
}
- static void wait_for_stop(IDisposable disp)
+ static void wait_for_stop()
{
Console.WriteLine("Hit q to stop");
ConsoleKeyInfo c;
@@ -109,7 +107,6 @@ namespace bts.sdk
c = Console.ReadKey();
Console.WriteLine();
} while (c.KeyChar != 'q');
- disp.Dispose();
}
static void help()
diff --git a/src/lib/config/defaults/logging.conf b/src/lib/config/defaults/logging.conf
index a09a08e1b..f9684cd2f 100644
--- a/src/lib/config/defaults/logging.conf
+++ b/src/lib/config/defaults/logging.conf
@@ -4,7 +4,7 @@ Logging {
console { default_level: "Error" }
syslog { default_level: "Info" }
file { default_level: "Info" }
- initial_queue_size: 128
+ initial_queue_size: 1024
max_queue_growth: 100
}
}
diff --git a/src/lib/config/defaults/position_cfg.conf b/src/lib/config/defaults/position_cfg.conf
index eb362017c..daf8983a0 100644
--- a/src/lib/config/defaults/position_cfg.conf
+++ b/src/lib/config/defaults/position_cfg.conf
@@ -6,4 +6,15 @@ GMI_SymbolMap {
sym { gmi: "05" spark: "ZS" venue: VENUE_GLBX price_multiplier: 100.0}
sym { gmi: "KW" spark: "KE" venue: VENUE_GLBX price_multiplier: 100.0}
}
-}
\ No newline at end of file
+}
+
+
+GMI_Import {
+ rule: "DeploymentType.type == 'DEV'"
+ value {
+ sftp_host: "10.96.18.41"
+ sftp_port: 22222
+ sftp_user: "PaTeACYB"
+ sftp_password: "DLXKuVK8"
+ }
+}
diff --git a/src/lib/config/protos/position_cfg.proto b/src/lib/config/protos/position_cfg.proto
index b2a4b5342..bb077e8a0 100644
--- a/src/lib/config/protos/position_cfg.proto
+++ b/src/lib/config/protos/position_cfg.proto
@@ -4,10 +4,11 @@ package bts.config;
message GMI_Import
{
- required string sftp_host = 10 [default = "10.96.18.41"];
- optional uint32 sftp_port = 11 [default = 22222];
- required string sftp_user = 12 [default = "sftp"];
- required string sftp_password = 2 [default = "sftp"];
+ required string sftp_host = 10 ;
+ optional uint32 sftp_port = 11 ;
+ required string sftp_user = 12 ;
+ required string sftp_password = 2 ;
+
required int32 pause_between_downloads_seconds = 4 [default = 30];
required int32 download_timeout_seconds = 5 [default = 35];
optional string download_window_begin = 6 [default = "22:00"];
diff --git a/src/lib/md/Diag/ShmDumper.cpp b/src/lib/md/Diag/ShmDumper.cpp
index d12f4c729..c75ac60a8 100644
--- a/src/lib/md/Diag/ShmDumper.cpp
+++ b/src/lib/md/Diag/ShmDumper.cpp
@@ -164,6 +164,7 @@ string dump_entry(const ColdEntry& entry) {
if (entry.misc.settlement_date.year > 0) res << "'settlement_date': " << dump(entry.misc.settlement_date) << ", ";
if (!(entry.misc.previous_settlement_price.is_nan())) res << "'previous_settlement_price': " << entry.misc.previous_settlement_price.price() << ", ";
if (entry.misc.previous_settlement_date.year > 0) res << "'previous_settlement_date': " << dump(entry.misc.previous_settlement_date) << ", ";
+ res << "'status': " << co2::TradingStatus_Name(entry.exchange_status) << " ";
res << "'deleted': " << std::boolalpha << entry.deleted << " ";
res << "}";
return res.str();
diff --git a/src/lib/md/MDConsumerHandle.h b/src/lib/md/MDConsumerHandle.h
index 66581f7d1..efc60cb60 100644
--- a/src/lib/md/MDConsumerHandle.h
+++ b/src/lib/md/MDConsumerHandle.h
@@ -213,6 +213,27 @@ public:
}
}
+ co2::TradingStatus trading_status() const {
+ switch(_type) {
+ case HANDLETYPE_DEPTH: return book.cdata->exchange_status;
+ case HANDLETYPE_BBO: return bbo.cdata->exchange_status;
+ case HANDLETYPE_SYNTHETIC: {
+ // Return the status if all legs match otherwise return TRADINGSTATUS_UNKNOWN
+ if (synthetic.def->legs.size() > 0) {
+ auto status = synthetic.def->legs.front().trading_status();
+ for (const auto& leg : synthetic.def->legs) {
+ if (leg.trading_status() != status) break;
+ }
+ return status;
+ }
+ return co2::TRADINGSTATUS_UNKNOWN;
+ }
+ default:
+ case HANDLETYPE_VOID:
+ return co2::TRADINGSTATUS_UNKNOWN;
+ }
+ }
+
TimeStamp last_market_update() const {
switch(_type) {
case HANDLETYPE_VOID:
diff --git a/src/lib/md/MDProducerHandle.cpp b/src/lib/md/MDProducerHandle.cpp
index 8025e604b..8ee9c09e3 100644
--- a/src/lib/md/MDProducerHandle.cpp
+++ b/src/lib/md/MDProducerHandle.cpp
@@ -148,8 +148,10 @@ void MDProducerHandle::add_rfq(TimeStamp, const co2::QuoteRequestMessage& rfq) {
}
void MDProducerHandle::update_exchange_status(TimeStamp, TradingStatus status) {
- cdata().exchange_status = status;
- cheader().exchange_status_count++;
+ if (status != TRADINGSTATUS_NO_CHANGE) {
+ cdata().exchange_status = status;
+ cheader().exchange_status_count++;
+ }
}
void MDProducerHandle::update_settlement(TimeStamp time, IntPrice price, Date date) {
diff --git a/src/lib/md/protos/co2.proto b/src/lib/md/protos/co2.proto
index 82c88df3a..c44566db6 100644
--- a/src/lib/md/protos/co2.proto
+++ b/src/lib/md/protos/co2.proto
@@ -29,6 +29,7 @@ enum TradingStatus {
TRADINGSTATUS_NO_CANCEL = 12; // CME
TRADINGSTATUS_POST_CLOSE = 13;
TRADINGSTATUS_NO_CHANGE = 14;
+ TRADINGSTATUS_NOT_AVAILABLE = 15; // CME NotAvailableForTrading
}
diff --git a/src/lib/orderman/actors/MDSource.h b/src/lib/orderman/actors/MDSource.h
index 54c0245f2..9952d2396 100644
--- a/src/lib/orderman/actors/MDSource.h
+++ b/src/lib/orderman/actors/MDSource.h
@@ -11,6 +11,7 @@
#include "lib/orderman/events/BookUpdateEvent.h"
#include "lib/orderman/events/MDRequestEvent.h"
#include "lib/orderman/events/TickerUpdateEvent.h"
+#include "lib/orderman/events/StatusUpdateEvent.h"
#include "lib/tracing/PerfLog.h"
#include "lib/tracing/bts_trace.h"
#include "lib/utils/TimeStamp.h"
@@ -30,7 +31,8 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
public:
MDSource(md::MDConsumer &consumer, metrics::MetricsContainer &stats,
trace::PerfLog &log)
- : _handles(), _md_consumer(consumer), _book_update(), _ticker_update(),
+ : _handles(), _status_subs(), _md_consumer(consumer),
+ _book_update(), _ticker_update(), _status_update(),
_perf_log(log), _stats(stats), _loop_timer() {
_trades_buffer.Reserve(1000);
@@ -65,15 +67,20 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
auto ticker_channel_cout_metric =
std::make_shared>(
"spark_mdsource_ticker_channel_count");
+ auto status_count_metric =
+ std::make_shared>(
+ "spark_mdsource_status_count");
_stats.publish(security_count_metric);
_stats.publish(synthetic_count_metric);
_stats.publish(ticker_channel_cout_metric);
+ _stats.publish(status_count_metric);
_book_update = make_stream();
_ticker_update = make_stream();
+ _status_update = make_stream();
subscribe(
[this, security_count_metric, synthetic_count_metric,
- ticker_channel_cout_metric](auto const &update) {
+ ticker_channel_cout_metric, status_count_metric](auto const &update) {
if (update.events) {
for (auto const &ev : *update.events) {
auto k = ev.security_key;
@@ -86,6 +93,10 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
case MDRequestType::TICKER:
on_ticker_sub(k, *ticker_channel_cout_metric);
break;
+ case MDRequestType::STATUS:
+ on_status_sub(k);
+ status_count_metric->set(_status_subs.size());
+ break;
}
}
}
@@ -146,6 +157,15 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
}
}
+ // Status updates
+ for (auto& s : _status_subs) {
+ auto status = s.handle.trading_status();
+ if (status != s.status) {
+ s.status = status;
+ publish(_status_update, SecurityKey { s.handle.key() }, status);
+ }
+ }
+
// Publish stats
auto stop = utils::TimeStamp::now();
_loop_timer->observe((start - stop).nanoseconds());
@@ -220,6 +240,20 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
c.securities.push_back(sk);
_channels.push_back(c);
}
+
+ void on_status_sub(SecurityKey sk) {
+ auto k = sk.value();
+ for (auto& h : _status_subs) {
+ if (h.handle.key() == k) {
+ // reset status so it get resent next on_poll
+ h.status = co2::TRADINGSTATUS_UNKNOWN;
+ return;
+ }
+ }
+ auto handle = _md_consumer.get_handle(k);
+ _status_subs.push_back(StatusRecord{ handle, co2::TRADINGSTATUS_UNKNOWN });
+ }
+
struct HandleRecord {
utils::TimeStamp last;
md::MDConsumerHandle handle;
@@ -237,9 +271,16 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
boost::container::small_vector _channels;
google::protobuf::RepeatedPtrField _trades_buffer;
+ struct StatusRecord {
+ md::MDConsumerHandle handle;
+ co2::TradingStatus status;
+ };
+ boost::container::small_vector _status_subs;
+
md::MDConsumer _md_consumer;
mercury::Stream _book_update;
mercury::Stream _ticker_update;
+ mercury::Stream _status_update;
trace::PerfLog &_perf_log;
metrics::MetricsContainer &_stats;
std::shared_ptr> _loop_timer;
diff --git a/src/lib/orderman/actors/SODPosition.cpp b/src/lib/orderman/actors/SODPosition.cpp
index f962b119e..4d3cc885e 100644
--- a/src/lib/orderman/actors/SODPosition.cpp
+++ b/src/lib/orderman/actors/SODPosition.cpp
@@ -24,14 +24,14 @@ _sod_time(sod_time){
LOG(persist, Info, "SODPosition::cons sod_time:{}", sod_time.tv_sec);
}
-// returns the timeval for today's hh,mm,ss (in local machine terms)
-// (timeval is the microseconds from epoch)
+// returns the timeval (secs/usecs from epoch) for today's hh,mm,ss
+// (in local machine time zone)
timeval SODPosition::to_timeval(uint16_t hh, uint16_t mm, uint16_t ss) {
// function does the conversion the following way:
- // 1. gets the now secs from epoch using time
- // 2. converts it into local time (so we have now local time)
- // 3. overrides the hh, mm, ss passed
- // 4. converts it back into secs from epoch using mktime
+ // 1. gets the secs from epoch (time_t)
+ // 2. converts it into local time
+ // 3. overrides the hh, mm, ss for local time with the func args
+ // 4. converts it back into timeval
bts_assert(hh < 24);
bts_assert(mm < 60);
bts_assert(ss < 60);
diff --git a/src/lib/orderman/actors/order_manager/OrderManager.cpp b/src/lib/orderman/actors/order_manager/OrderManager.cpp
index 5c51317f2..a347e157c 100644
--- a/src/lib/orderman/actors/order_manager/OrderManager.cpp
+++ b/src/lib/orderman/actors/order_manager/OrderManager.cpp
@@ -519,6 +519,9 @@ void OrderManager::init_order_services() {
std::function on_ticker_sub = [this](SecurityKey k) {
publish(me->services_data.md_request_pub, k, MDRequestType::TICKER);
};
+ std::function on_status_sub = [this](SecurityKey k) {
+ publish(me->services_data.md_request_pub, k, MDRequestType::STATUS);
+ };
std::function on_settlement_sub = [this](SecurityKey k) {
publish(me->services_data.settlement_request_pub, k);
};
@@ -537,6 +540,9 @@ void OrderManager::init_order_services() {
me->services_data.ticker_subs =
std::make_unique>(
*this, on_ticker_sub, log);
+ me->services_data.status_subs =
+ std::make_unique>(
+ *this, on_status_sub, log);
me->services_data.settlement_subs =
std::make_unique>(
*this, on_settlement_sub, log);
diff --git a/src/lib/orderman/actors/order_manager/OrderServices.cpp b/src/lib/orderman/actors/order_manager/OrderServices.cpp
index 6694524fc..cc6285e70 100644
--- a/src/lib/orderman/actors/order_manager/OrderServices.cpp
+++ b/src/lib/orderman/actors/order_manager/OrderServices.cpp
@@ -11,8 +11,8 @@ std::function OrderServices::ignore =
OrderServices::OrderServices(Order &owner)
: _busy(false), _pending_calls(), _owner(&owner), _data(), _parent(nullptr),
- _child_update_cb([](auto const &) {}), _book_updates(), _ticker_updates(),
- _settlement_updates(), _time_change(), _sessions() {
+ _child_update_cb([](auto const &) {}), _book_updates(), _ticker_updates(),
+ _status_updates(), _settlement_updates(), _time_change(), _sessions() {
_last_state_update.key = null_order_key();
}
@@ -29,6 +29,7 @@ void OrderServices::init(OrderServicesData &data) {
_data = &data;
_book_updates.init(*data.md_subs);
_ticker_updates.init(*data.ticker_subs);
+ _status_updates.init(*data.status_subs);
_settlement_updates.init(*data.settlement_subs);
_time_change.init(*data.time_subs);
if (_sessions.empty())
@@ -70,6 +71,7 @@ void OrderServices::report_state(const api::orderman::OrderState &state) {
unsubscribe_from_child_updates();
_book_updates.unsub_all();
_ticker_updates.unsub_all();
+ _status_updates.unsub_all();
_settlement_updates.unsub_all();
_time_change.unsub_all();
_create_order_reply.unsub_all();
diff --git a/src/lib/orderman/actors/order_manager/OrderServices.h b/src/lib/orderman/actors/order_manager/OrderServices.h
index aeb344f8a..2e1afdbb3 100644
--- a/src/lib/orderman/actors/order_manager/OrderServices.h
+++ b/src/lib/orderman/actors/order_manager/OrderServices.h
@@ -7,6 +7,7 @@
#include "lib/orderman/actors/order_manager/OrderServicesData.h"
#include "lib/orderman/actors/order_manager/SessionServices.h"
#include "lib/orderman/events/TickerUpdateEvent.h"
+#include "lib/orderman/events/StatusUpdateEvent.h"
#include "lib/orderman/governor/Governor.h"
#include "lib/orderman/orderman_utils/EventStream.h"
#include "lib/orderman/orders/Order.h"
@@ -96,6 +97,13 @@ class OrderServices {
k, [this, cb](auto const &ev) { this->on_external_event(ev, cb); });
}
void unsubscribe_from_ticker(TickerSubID sid) { _ticker_updates.unsub(sid); }
+ // Trading Status
+ using StatusSubID = EventStream::SubID;
+ template StatusSubID subscribe_to_status(SecurityKey k, CB&& cb) {
+ return _status_updates.sub(
+ k, [this,cb](const auto& ev) { this->on_external_event(ev,cb); });
+ }
+ void unsubscribe_from_status(StatusSubID sid) { _status_updates.unsub(sid); }
// Settlement
using SettlementSubID = EventStream::SubID;
template
@@ -106,7 +114,6 @@ class OrderServices {
void unsubscribe_from_settlements(SettlementSubID sid) {
_settlement_updates.unsub(sid);
}
- // Settlement
// Time
template void subscribe_to_time(CB &&cb) {
@@ -288,6 +295,7 @@ class OrderServices {
OrderStateUpdateEvent _last_state_update;
EventStream _book_updates;
EventStream _ticker_updates;
+ EventStream _status_updates;
EventStream _settlement_updates;
EventStream _time_change;
boost::container::small_vector _sessions;
diff --git a/src/lib/orderman/actors/order_manager/OrderServicesData.h b/src/lib/orderman/actors/order_manager/OrderServicesData.h
index 11c0257ae..bf1124406 100644
--- a/src/lib/orderman/actors/order_manager/OrderServicesData.h
+++ b/src/lib/orderman/actors/order_manager/OrderServicesData.h
@@ -13,6 +13,7 @@
#include "lib/orderman/events/ActivateOrderEvent.h"
#include "lib/orderman/events/BookUpdateEvent.h"
#include "lib/orderman/events/TickerUpdateEvent.h"
+#include "lib/orderman/events/StatusUpdateEvent.h"
#include "lib/orderman/events/CancelOrderEvent.h"
#include "lib/orderman/events/CancelRejectEvent.h"
#include "lib/orderman/events/DetachOrderEvent.h"
@@ -91,6 +92,7 @@ class OrderServicesData {
OrderFactory order_factory;
std::unique_ptr> md_subs;
std::unique_ptr> ticker_subs;
+ std::unique_ptr> status_subs;
trace::CorID cor_id;
std::unique_ptr>
settlement_subs;
diff --git a/src/lib/orderman/events/MDRequestEvent.h b/src/lib/orderman/events/MDRequestEvent.h
index f8d244502..f04da5631 100644
--- a/src/lib/orderman/events/MDRequestEvent.h
+++ b/src/lib/orderman/events/MDRequestEvent.h
@@ -8,7 +8,7 @@
namespace bts {
namespace orderman {
-enum class MDRequestType { BOOK, TICKER };
+enum class MDRequestType { BOOK, TICKER, STATUS };
class MDRequestEvent : public mercury::Event {
public:
diff --git a/src/lib/orderman/events/StatusUpdateEvent.h b/src/lib/orderman/events/StatusUpdateEvent.h
new file mode 100644
index 000000000..64c6c69f3
--- /dev/null
+++ b/src/lib/orderman/events/StatusUpdateEvent.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include
+#include "lib/mercury/events/Event.h"
+#include "lib/orderman/orderman_utils/Book.h"
+#include "lib/orderman/orderman_utils/orderman_common.h"
+#include "lib/tracing/PerfLog.h"
+
+namespace bts {
+namespace orderman {
+
+class StatusUpdateEvent : public mercury::Event {
+ SecurityKey _key;
+ public:
+ using SynopsisPolicy = mercury::NoSynopsis;
+ co2::TradingStatus status;
+ trace::CorID trace;
+ SecurityKey key() const { return _key; }
+ StatusUpdateEvent(SecurityKey key, co2::TradingStatus status) :
+ _key(key), status(status), trace() { }
+};
+
+}}
diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp
index f7a41e77c..683c04ee5 100644
--- a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp
+++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp
@@ -57,6 +57,7 @@ struct AlgoWrapperOrder::PImpl {
Map book_subs;
Map ticker_subs;
+ Map status_subs;
Map children;
bool has_timer_sub = false;
@@ -434,6 +435,26 @@ void AlgoWrapperOrder::unsubscribe_ticker(SecurityKey k) {
if (auto it = me->ticker_subs.find(k); it != me->ticker_subs.end())
me->services->unsubscribe_from_ticker(it->second);
}
+
+void AlgoWrapperOrder::subscribe_status(SecurityKey k) {
+ if (!is_working()) return;
+ bts_assert(me->status_subs.find(k) == me->status_subs.end());
+
+ me->status_subs[k] =
+ me->services->subscribe_to_status(k, [this,k](const auto& ev) {
+ ReportStateGuard _(*this);
+ me->algo->on_status(k, ev.status);
+ });
+}
+
+void AlgoWrapperOrder::unsubscribe_status(SecurityKey k) {
+ if (!is_working()) return;
+ bts_assert(me->status_subs.find(k) != me->status_subs.end());
+ auto it = me->status_subs.find(k);
+ if (it != me->status_subs.end()) {
+ me->services->unsubscribe_from_status(it->second);
+ }
+}
void AlgoWrapperOrder::subscribe_child_change(OrderKey k) {
if (!is_working())
diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.h b/src/lib/orderman/orders/algo/AlgoWrapperOrder.h
index a2b2b1daa..9cdc1d263 100644
--- a/src/lib/orderman/orders/algo/AlgoWrapperOrder.h
+++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.h
@@ -49,6 +49,9 @@ class AlgoWrapperOrder : public Order,
void unsubscribe_timer() override;
void subscribe_ticker(SecurityKey) override;
void unsubscribe_ticker(SecurityKey) override;
+ void subscribe_status(SecurityKey) override;
+ void unsubscribe_status(SecurityKey) override;
+
OrderKey launch_child(ChildTemplate &, Price, Quantity,
bool subscribe = true) override;
OrderKey launch_child(api::orderman::OrderDefinition const &, Price,
diff --git a/src/lib/orderman/orders/algo/IAlgoOrder.h b/src/lib/orderman/orders/algo/IAlgoOrder.h
index b1a871034..7ddfee02d 100644
--- a/src/lib/orderman/orders/algo/IAlgoOrder.h
+++ b/src/lib/orderman/orders/algo/IAlgoOrder.h
@@ -41,6 +41,9 @@ class IAlgoOrder {
// Trades stream for the specified security
virtual void on_ticker(SecurityKey, TradeVector const&) {};
+ // The trading status for the specified security has changed
+ virtual void on_status(SecurityKey, co2::TradingStatus) {};
+
// A periodic timer has fired
virtual void on_timer() {}
diff --git a/src/lib/orderman/orders/algo/IAlgoServices.h b/src/lib/orderman/orders/algo/IAlgoServices.h
index e6e2acf3f..2222c90e1 100644
--- a/src/lib/orderman/orders/algo/IAlgoServices.h
+++ b/src/lib/orderman/orders/algo/IAlgoServices.h
@@ -48,6 +48,10 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
virtual void subscribe_ticker(SecurityKey) = 0;
virtual void unsubscribe_ticker(SecurityKey) = 0;
+ // Subscribe to security trading status
+ virtual void subscribe_status(SecurityKey) = 0;
+ virtual void unsubscribe_status(SecurityKey) = 0;
+
// --------------------------------------------------------------
// Child management
// --------------------------------------------------------------
diff --git a/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp b/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp
index 5ca3f517b..475758a4a 100644
--- a/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp
+++ b/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp
@@ -64,6 +64,7 @@ struct AlgoTestDriverBase::Impl : public RecursionCounter {
std::map books;
std::map book_subs;
std::map ticker_subs;
+ std::map status_subs;
bool sub_timer = false;
// Callbacks
@@ -163,6 +164,12 @@ void AlgoTestDriverBase::update_ticker(SecurityKey key, const TradeVector& data)
me->algo.on_ticker(key, data);
}
}
+void AlgoTestDriverBase::update_status(SecurityKey key, co2::TradingStatus status) {
+ auto iter = me->status_subs.find(key);
+ if (iter != me->ticker_subs.end() && iter->second) {
+ me->algo.on_status(key,status);
+ }
+}
void AlgoTestDriverBase::advance_time(Duration d, uint32_t steps) {
Duration dprime = d / steps;
for (uint32_t s = 0; s < steps; ++s) {
@@ -332,6 +339,13 @@ void AlgoTestDriverBase::unsubscribe_ticker(SecurityKey key) {
me->ticker_subs.erase(key);
}
+void AlgoTestDriverBase::subscribe_status(SecurityKey key) {
+ me->status_subs[key] = true;
+}
+void AlgoTestDriverBase::unsubscribe_status(SecurityKey key) {
+ me->status_subs.erase(key);
+}
+
void AlgoTestDriverBase::subscribe_child_change(OrderKey k) {
for (auto& child : me->orders) {
if (child.key == k) {
diff --git a/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h b/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h
index c4ad79b17..2556bc223 100644
--- a/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h
+++ b/src/lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h
@@ -71,6 +71,7 @@ class AlgoTestDriverBase : private IAlgoServices {
void update_book(const Book&);
void update_ticker(SecurityKey, const TradeVector&);
+ void update_status(SecurityKey, co2::TradingStatus);
void advance_time(Duration, uint32_t steps=1);
IAlgoOrder::OnCancelResponse cancel();
@@ -117,6 +118,8 @@ private:
void unsubscribe_timer() override;
void subscribe_ticker(SecurityKey) override;
void unsubscribe_ticker(SecurityKey) override;
+ void subscribe_status(SecurityKey) override;
+ void unsubscribe_status(SecurityKey) override;
OrderKey launch_child(ChildTemplate &, Price, Quantity, bool) override;
OrderKey launch_child(api::orderman::OrderDefinition const &, Price,
diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp
index 7276310a3..90684219c 100644
--- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp
+++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp
@@ -242,12 +242,14 @@ void MDP3Listener::heartbeat() {
//
// Private functions
-void MDP3Listener::add_security(const FixedSecurity& security) {
+void MDP3Listener::add_security(const FixedSecurity& security, co2::TradingStatus status) {
+ bts_assert(security.numeric_id != 0);
// Set up the shared memory for this security
auto handle = _producer.add_security(security);
- bts_assert(security.numeric_id != 0);
// Add it to the index so it can receive messages
_index.add_security(security.numeric_id, handle);
+
+ handle.update_exchange_status( utils::TimeStamp::now(), status);
}
void MDP3Listener::flush_books() {
diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h
index 1fdb93393..f2d5d5e8a 100644
--- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h
+++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h
@@ -64,6 +64,43 @@ inline inc::UpdateAction mbo_update_action(onixs::UpdateAction::Enum a) {
}
}
+inline co2::TradingStatus map_status(onixs::SecurityTradingStatus::Enum ts) {
+ switch(ts) {
+ case onixs::SecurityTradingStatus::TradingHalt:
+ return co2::TRADINGSTATUS_HALTED;
+ case onixs::SecurityTradingStatus::Close:
+ return co2::TRADINGSTATUS_CLOSED;
+ case onixs::SecurityTradingStatus::NewPriceIndication:
+ return co2::TRADINGSTATUS_PRICE_INDICATION;
+ case onixs::SecurityTradingStatus::ReadyToTrade:
+ return co2::TRADINGSTATUS_NORMAL;
+ case onixs::SecurityTradingStatus::NotAvailableForTrading:
+ return co2::TRADINGSTATUS_NOT_AVAILABLE;
+ case onixs::SecurityTradingStatus::UnknownorInvalid:
+ return co2::TRADINGSTATUS_UNKNOWN;
+ case onixs::SecurityTradingStatus::PreOpen:
+ return co2::TRADINGSTATUS_PRE_OPEN;
+ case onixs::SecurityTradingStatus::PreCross:
+ return co2::TRADINGSTATUS_PRE_CROSS;
+ case onixs::SecurityTradingStatus::Cross:
+ return co2::TRADINGSTATUS_CROSS;
+ case onixs::SecurityTradingStatus::PostClose:
+ return co2::TRADINGSTATUS_POST_CLOSE;
+ case onixs::SecurityTradingStatus::NoChange:
+ return co2::TRADINGSTATUS_NO_CHANGE;
+ }
+ return co2::TRADINGSTATUS_UNKNOWN;
+}
+
+template
+std::optional security_trading_status(const T& t) {
+ onixs::SecurityTradingStatus::Enum status;
+ if (t.securityTradingStatus(status)) {
+ return { map_status(status) };
+ }
+ else return std::nullopt;
+}
+
class MDP3Listener :
public onixs::HandlerListener,
@@ -153,6 +190,21 @@ public:
}
}
+ void onMessage(onixs::Handler&, const onixs::SecurityStatus30Args& args) override {
+ int exchange_id;
+ if (args.message().securityId(exchange_id)) {
+ auto data = _index.get_security(exchange_id);
+ if (data) {
+ auto status = security_trading_status(args.message());
+ if (status) {
+ data->handle.update_exchange_status(
+ utils::TimeStamp::now(),
+ status.value());
+ }
+ }
+ }
+ }
+
void onMessage(onixs::Handler&, const onixs::IncrementalRefreshOrderBook43Args& args) override {
onIncrementalRefreshOrderBook(args);
}
@@ -233,6 +285,24 @@ public:
}
+ void onMessage(onixs::Handler&, const onixs::SnapshotFullRefresh38Args& args) override {
+ onSnapshotFullRefresh(args.message());
+ }
+ void onMessage(onixs::Handler&, const onixs::SnapshotFullRefresh52Args& args) override {
+ onSnapshotFullRefresh(args.message());
+ }
+ template
+ void onSnapshotFullRefresh(const SnapshotFullRefresh& message) {
+ auto data = _index.get_security(message.securityId());
+ if (data) {
+ auto status = security_trading_status(message);
+ if (status) {
+ data->handle.update_exchange_status(
+ utils::TimeStamp::now(),
+ status.value());
+ }
+ }
+ }
//
// Security discovery
@@ -338,7 +408,7 @@ public:
void heartbeat();
// Add a new security to the index
- void add_security(const FixedSecurity& security);
+ void add_security(const FixedSecurity& security, co2::TradingStatus);
private:
enum SecurityFilterAction { ADD, SKIP, DELETE };
@@ -429,7 +499,9 @@ void MDP3Listener::onFuture(onixs::Handler&, const onixs::Security& osec, const
fsec.expiration_year = expiration.year;
fsec.expiration_month = expiration.month;
fsec.expiration_day = expiration.day;
- add_security(fsec);
+
+ auto status = security_trading_status(def.message()).value_or(co2::TRADINGSTATUS_UNKNOWN);
+ add_security(fsec, status);
}
template
@@ -463,7 +535,8 @@ void MDP3Listener::onOption(onixs::Handler&, const onixs::Security&, const Instr
fsec.call_put = sec.putOrCall() == onixs::PutOrCall::Call ? api::PUTORCALL_CALL : api::PUTORCALL_PUT;
- add_security(fsec);
+ auto status = security_trading_status(def.message()).value_or(co2::TRADINGSTATUS_UNKNOWN);
+ add_security(fsec, status);
}
// min_tick specializations
@@ -520,7 +593,8 @@ void MDP3Listener::onSpread(onixs::Handler&, const onixs::Security&, const Instr
fsec.legs[x].exchange_key = ExchangeKey(leg.legSecurityId());
fsec.legs[x].key = invalid_security_key;
}
- add_security(fsec);
+ auto status = security_trading_status(sec).value_or(co2::TRADINGSTATUS_UNKNOWN);
+ add_security(fsec, status);
}
template