refactor: Replace OrderSecurity refs w/ OrderRecordTuple

The latter type was introduced to support the websocket server. Unlike
the old 'OrderSecurity' types, it has no wpf deps, and can thus be built
on Linux
This commit is contained in:
John Colvin committed 2023-02-04 00:04:43 -05:00
1 parent 1aa283fc8c
commit ecf3f922df
32 files changed
+361 -280

No files matched your search

+17 -11
View File
@@ -33,7 +33,7 @@ namespace bts.shell {
readonly bool _close_on_send;
IReadOnlyDictionary<uint, AccountTuple> _accounts = new Dictionary<uint, AccountTuple>(0);
IReadOnlyDictionary<uint, SecurityMD> _md_map;
TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> _orders;
TableUpdate<OrderRecordTuple, uint> _orders;
IDisposable _dispose;
[ImportingConstructor]
@@ -106,17 +106,23 @@ namespace bts.shell {
}
void _show_modify_order(uint order_key) {
if (_orders.state.TryGetValue(order_key, out var ori) && ori.sec.HasValue
&& (ori.order.HasDef && ori.order.Def.HasCustomDef && !(ori.order.Def.CustomDef.HasStop || ori.order.Def.CustomDef.HasStopLimit))) {
var md = _md_map.TryGetValue(ori.order.security_key());
_show_order_window(new OrderModificationDialog {
DataContext = new ExistingOrderTicketVM(_model,
Observable.Return((md, ori.order)),
_bus.subscribe(SparkTags.AccountsTag),
Observable.Return(LadderSettings.Default.calculator_buttons)
)
});
if (!_orders.state.TryGetValue(order_key, out var ori) || !ori.security.HasValue) {
return;
}
switch (ori.order.order_type()) {
case CustomOrderDefinition.CustomOneofCase.Stop:
case CustomOrderDefinition.CustomOneofCase.StopLimit:
case CustomOrderDefinition.CustomOneofCase.None:
return;
}
var md = _md_map.TryGetValue(ori.order.security_key());
_show_order_window(new OrderModificationDialog {
DataContext = new ExistingOrderTicketVM(_model,
Observable.Return((md, ori.order)),
_bus.subscribe(SparkTags.AccountsTag),
Observable.Return(LadderSettings.Default.calculator_buttons)
)
});
}
LadderSettings _get_settings(SecurityImmutable sec) {
@@ -41,34 +41,34 @@ namespace Spark.Model.Trading {
.Naggle(interval, scheduler),
o => o.account_id())
.join(sec_resolver, o => o.security_key())
.Select(o => new OrderRecordTuple(o.val, o.sec), o => o.key)
.Table()
.Cache();
working_orders = orders.Filter(tup => tup.order.is_active()).Cache();
security_orders = orders
.SelectKeyValue(tup => new OrderSecurity(tup), OrderSecurityHelper.key_fn)
.GroupTable(OrderSecurityHelper.key_fn, tup => tup.order.Def.SecurityKey)
.GroupTable(o => o.key, o => o.security_id)
.Cache();
account_security_orders = orders.GroupTable(
t => t.order.Key,
t => new AccountSecurityKey(t.order.account_id(), t.order.security_key()))
o => o.key,
o => new AccountSecurityKey(o.account_id, o.security_id))
.Cache();
working_account_security_orders = working_orders
.Filter(o => o.order.is_exchange_order())
.GroupTable(
t => t.order.Key,
t => new AccountSecurityKey(t.order.account_id(), t.order.security_key()))
o => o.key,
o => new AccountSecurityKey(o.account_id, o.security_id))
.Cache();
}
public IObservable<TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint>> orders { get; }
public IObservable<TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint>> working_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<OrderSecurity, uint, uint>, uint>> security_orders { get; }
public IObservable<TableUpdate<OrderRecordTuple, uint>> orders { get; }
public IObservable<TableUpdate<OrderRecordTuple, uint>> working_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<OrderRecordTuple, uint, uint>, uint>> security_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<(SecurityImmutable? sec, OrderRecordImmutable order), uint, AccountSecurityKey>, AccountSecurityKey>> account_security_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<(SecurityImmutable? sec, OrderRecordImmutable order), uint, AccountSecurityKey>, AccountSecurityKey>> working_account_security_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<OrderRecordTuple, uint, AccountSecurityKey>, AccountSecurityKey>> account_security_orders { get; }
public IObservable<TableUpdate<TableUpdateGrouping<OrderRecordTuple, uint, AccountSecurityKey>, AccountSecurityKey>> working_account_security_orders { get; }
}
}
@@ -84,7 +84,7 @@ namespace Spark.Trading {
(acc_orders, pnl_id) => {
var (security, account_id, account) =
acc_orders.table.state.Values.TryGetFirst(out var tup) ?
(tup.sec, tup.order.account_id(), tup.order.account()) :
(tup.security, tup.account_id, tup.account_name) :
(null, 0, null);
return new PNLRowData(pnl_id,
security: security,
@@ -17,6 +17,7 @@ namespace mbts.spark {
using mbts.ui.utility;
using mbts.utils;
using Spark.Api.Orders;
using Spark.Core;
using Spark.Core.Collections;
using Spark.Core.Data;
@@ -639,7 +640,10 @@ namespace mbts.spark {
}
OrderBookVM _mk_orderbook_vm_common(
bts.shell.orderbook.FilterStates filters, IEnumerable<OrderBookGridView.ColumnKeys> hide_cols, IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source = null) {
bts.shell.orderbook.FilterStates filters,
IEnumerable<OrderBookGridView.ColumnKeys> hide_cols,
IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> orders_source = null
) {
var state = new bts.shell.orderbook.OrderBookStartupData(filters, bts.shell.orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false);
state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_cols);
var settings_man = new WindowSettingsManager<bts.shell.orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
@@ -8,6 +8,7 @@ using bts.md;
using mbts.analytics;
using mbts.co2;
using Spark.Api.Orders;
using Spark.Core.Data;
using Spark.Trading;
@@ -28,13 +29,14 @@ namespace mbts.spark {
IObservable<GreeksTuple> greeks,
ISecurityMetadataStore sec_meta_store,
MBOService mbo,
Func<OrderSecurity, bool> order_filter = null) {
Func<OrderRecordTuple, bool> order_filter = null) {
security_md = source;
_order_gateway = ordergw;
this.position_model = position_model;
this.fair_value_model = fair_value_model;
this.sec_meta_store = sec_meta_store;
orders = ordergw.on_security_working_orders_with_piq(source.security.Id);
orders = ordergw.on_security_working_orders_with_piq(source.security.Id)
.Select(o => new OrderRecordTuple(o.order, o.security, o.piq, o.algo), o => o.key);
this.greeks = greeks;
this.mbo_service = mbo;
if (order_filter != null) {
@@ -51,7 +53,7 @@ namespace mbts.spark {
public IPositionModel position_model { get; }
public FairValueModel fair_value_model { get; }
public ISecurityMetadataStore sec_meta_store { get; }
public IObservable<TableUpdate<OrderSecurity, uint>> orders { get; }
public IObservable<TableUpdate<OrderRecordTuple, uint>> orders { get; }
public IObservable<GreeksTuple> greeks { get; }
public MBOService mbo_service { get; }
@@ -63,7 +65,7 @@ namespace mbts.spark {
IBus bus,
ISecurityMetadataStore sec_meta_store,
MBOService mbo,
Func<OrderSecurity, bool> order_filter = null) {
Func<OrderRecordTuple, bool> order_filter = null) {
var all_sec_greeks = bus.subscribe(SparkTags.Greeks);
var sec_greeks = all_sec_greeks
.Select(gs => gs.TryGetValue(source.security.Id) ?? GreeksTuple.empty)
@@ -47,8 +47,8 @@ namespace mbts.spark {
readonly DelegateProperty<IReadOnlyList<string>> _text_lines;
readonly DeferrableAction _clear_phantom_price;
ImmutableDictionary<uint, OrderSecurity> _orders =
ImmutableDictionary<uint, OrderSecurity>.Empty;
ImmutableDictionary<uint, OrderRecordTuple> _orders =
ImmutableDictionary<uint, OrderRecordTuple>.Empty;
LadderSettings.BadgeStyle _current_badge_style;
double _phantom_price = double.NaN;
double _filled;
@@ -57,7 +57,7 @@ namespace mbts.spark {
uint? _min_piq = uint.MaxValue;
public LadderOrderVM(
ImmutableDictionary<uint, OrderSecurity> orders,
ImmutableDictionary<uint, OrderRecordTuple> orders,
double real_price,
LadderVM owner,
IObservable<LadderSettings.BadgeStyle> badge_style
@@ -182,11 +182,11 @@ namespace mbts.spark {
public ICommand cancel_cmd => new Command(_cancel);
IEnumerable<OrderRecordImmutable> _root_nodes =>
_orders.Values.Select(_owner.get_root_at_price).DistinctOn(OrderUtils.RecordKeySelector);
_orders.Values.Select(_owner.get_root_at_price).DistinctOn(o => o.Key);
LadderModel _model => _owner.model;
public void sync_orders(ImmutableDictionary<uint, OrderSecurity> new_orders) {
public void sync_orders(ImmutableDictionary<uint, OrderRecordTuple> new_orders) {
_orders = new_orders;
min_piq = new_orders.Count == 0 ? null : new_orders.Values.Select(o => o.piq).Min();
}
@@ -286,7 +286,7 @@ namespace mbts.spark {
obvm.load_from(state);
return obvm;
bool order_price_filter(OrderSecurityRootPair o) =>
bool order_price_filter(OrderRecordTupleWithRoot o) =>
o.order.order.ui_price().is_within_range(
min_price - MathUtils.EPSILON, max_price + MathUtils.EPSILON);
}
@@ -97,7 +97,7 @@ namespace mbts.spark {
bool _show_raw_day_position;
ulong _misc_time = 0;
ulong _last_trade_time = 0;
IReadOnlyDictionary<uint, OrderSecurity> _cache = DictionaryHelper.empty<uint, OrderSecurity>();
IReadOnlyDictionary<uint, OrderRecordTuple> _cache = DictionaryHelper.empty<uint, OrderRecordTuple>();
ImmutableDictionary<AlgoKey, LadderFavoriteAlgoMetadata> _favorite_algo_metadata_map =
ImmutableDictionary<AlgoKey, LadderFavoriteAlgoMetadata>.Empty;
ContractSpecificationImmutable? _spec;
@@ -747,7 +747,7 @@ namespace mbts.spark {
}
}
internal OrderRecordImmutable get_root_at_price(OrderSecurity op) {
internal OrderRecordImmutable get_root_at_price(OrderRecordTuple op) {
double p = _normalize_price(op.order.ui_price());
return lineage(op.order.ParentKey)
.Where(o => _equality.Equals(p, _normalize_price(o.ui_price())))
@@ -761,13 +761,13 @@ namespace mbts.spark {
}
}
static IObservable<(ImmutableSortedDictionary<double, ImmutableDictionary<uint, OrderSecurity>> price_index, IReadOnlyDictionary<uint, OrderSecurity> map)> _order_price_source(
IObservable<TableUpdate<OrderSecurity, uint>> source,
static IObservable<(ImmutableSortedDictionary<double, ImmutableDictionary<uint, OrderRecordTuple>> price_index, IReadOnlyDictionary<uint, OrderRecordTuple> map)> _order_price_source(
IObservable<TableUpdate<OrderRecordTuple, uint>> source,
IComparer<double> price_comp,
Func<double, double> normalize_price
) {
return Observable.Create<(ImmutableSortedDictionary<double, ImmutableDictionary<uint, OrderSecurity>>, IReadOnlyDictionary<uint, OrderSecurity>)>(o => {
var state = ImmutableSortedDictionary.Create<double, ImmutableDictionary<uint, OrderSecurity>>(price_comp);
return Observable.Create<(ImmutableSortedDictionary<double, ImmutableDictionary<uint, OrderRecordTuple>>, IReadOnlyDictionary<uint, OrderRecordTuple>)>(o => {
var state = ImmutableSortedDictionary.Create<double, ImmutableDictionary<uint, OrderRecordTuple>>(price_comp);
var sub = source.Subscribe(table => {
var bd = state.ToBuilder();
@@ -800,7 +800,7 @@ namespace mbts.spark {
bd[price] = index.Add(new_order.order.Key, new_order);
} else {
bd[price] = ImmutableDictionary.CreateRange(new[] {
new KeyValuePair<uint, OrderSecurity>(new_order.order.Key, new_order)
new KeyValuePair<uint, OrderRecordTuple>(new_order.order.Key, new_order)
});
}
}
@@ -809,10 +809,10 @@ namespace mbts.spark {
return sub;
});
bool price_changed(Change<OrderSecurity> ch) =>
bool price_changed(Change<OrderRecordTuple> ch) =>
price_comp.Compare(ch.New.order.ui_price(), ch.Old.order.ui_price()) != 0;
double get_price(OrderSecurity order) {
double get_price(OrderRecordTuple order) {
var p = order.order.ui_price();
if (!(normalize_price is null))
p = normalize_price(p);
@@ -7,6 +7,7 @@ namespace mbts.spark {
using mbts.ui;
using mbts.ui.shell;
using Spark.Api.Orders;
using Spark.Core.Data;
using Spark.Core.Disposables;
using Spark.Trading;
@@ -112,8 +113,8 @@ namespace mbts.spark {
var settings_src = Observable.Return(LadderSettings.sanitize(LadderSettings.Default));
_value = LadderVM.create_readonly(_bus, model, settings_src);
bool order_filter(OrderSecurity osec) =>
_selected_order_tree.Contains(osec.order.Key);
bool order_filter(OrderRecordTuple o) =>
_selected_order_tree.Contains(o.order.Key);
}
}
}
@@ -40,7 +40,7 @@ namespace mbts.spark {
// This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup.
interface ICVOrderBookColumn : IKeyedColumn<Columns>, IGridColumn {
ListSortDirection? SortDirection { get; set; }
IDataGridColumnFilter<OrderSecurityRootPair> filter { get; }
IDataGridColumnFilter<OrderRecordTupleWithRoot> filter { get; }
IComparer<OrderBookRowVM> comparer { get; }
}
@@ -76,7 +76,7 @@ namespace mbts.spark {
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
// security
Add(security_column = new SecurityColumn(
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, SecurityImmutable, SecurityCriteria>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, SecurityImmutable, SecurityCriteria>(
order_securities,
ort => ort.order.security ?? Security.Defaults.SecurityImmutable,
SecurityCriteria.from_securities,
@@ -91,7 +91,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Symbol,
r => r.symbol,
DefaultColumnWidths.Symbol,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, string>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, string>(
mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(),
ort => ort.order.security?.Symbol ?? string.Empty,
nameof(OrderBookRowVM.symbol)
@@ -104,7 +104,7 @@ namespace mbts.spark {
"Time",
r => r.time_created_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderSecurityRootPair>(
new TimeFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.created(),
nameof(OrderBookRowVM.time_created)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -115,7 +115,7 @@ namespace mbts.spark {
"Last Change",
r => r.last_change_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderSecurityRootPair>(
new TimeFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.last_change(),
nameof(OrderBookRowVM.last_change)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -126,7 +126,7 @@ namespace mbts.spark {
DefaultColumnHeaders.User,
r => r.user,
DefaultColumnWidths.User,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, string>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, string>(
bus.subscribe(SparkTags.Users)
.Select(d => d.Values.Select(ut => ut.name).Distinct().Ordered()),
ort => ort.order.order.user(),
@@ -139,7 +139,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Account,
r => r.account,
DefaultColumnWidths.Account,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, string, string[]>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, string, string[]>(
bus.subscribe(SparkTags.AccountsTag)
.Select(d => d.Values.Select(ut => ut.name).Distinct().Ordered()),
ort => ort.order.order.account(),
@@ -154,7 +154,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Exchange,
r => r.exchange.ToString(),
DefaultColumnWidths.Exchange,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, Venue>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, Venue>(
EnumHelper.get_values_except(Venue.Unset).ToList(),
ort => ort.order.security.exchange_or_default(),
nameof(OrderBookRowVM.exchange)),
@@ -166,7 +166,7 @@ namespace mbts.spark {
DefaultColumnHeaders.TimeInForce,
r => r.time_in_force.ToString(),
DefaultColumnWidths.TimeInForce,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, TimeInForce>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, TimeInForce>(
EnumHelper.get_values<TimeInForce>().ToList(),
ort => ort.order.order.time_in_force(),
nameof(OrderBookRowVM.time_in_force)),
@@ -182,8 +182,8 @@ namespace mbts.spark {
nameof(OrderBookRowVM.badge_fill),
nameof(OrderBookRowVM.display_name),
_wrap_comparer(r => r.order_type),
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurityRootPair, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.order.algo),
DiscreteValuesFilterVM.CreateTableUpdate<OrderRecordTupleWithRoot, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.order.algo ?? AlgoData.empty),
vm => AlgoID.from_algo_key(vm.data.key), out var order_type_filter_observer, out var order_type_items_view)));
_resources.Add(algo_items_source.Subscribe(order_type_filter_observer));
order_type_items_view.CustomSort = algo_items_comp;
@@ -193,9 +193,9 @@ namespace mbts.spark {
Columns.RootAlgoType,
nameof(OrderBookRowVM.root_algo_badge_fill),
nameof(OrderBookRowVM.root_algo_display_name),
_wrap_comparer(r => r.order_tuple.root.algo.value.CustomCase),
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurityRootPair, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.root.algo),
_wrap_comparer(r => r.order_tuple.root.algo_type),
DiscreteValuesFilterVM.CreateTableUpdate<OrderRecordTupleWithRoot, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.root.algo ?? AlgoData.empty),
vm => AlgoID.from_algo_key(vm.data.key), out var root_algo_type_observer, out var root_algo_type_items_view),
DefaultColumnHeaders.RootAlgoType));
_resources.Add(algo_items_source.Subscribe(root_algo_type_observer));
@@ -207,7 +207,7 @@ namespace mbts.spark {
"Sub Type",
r => r.order_sub_type_text,
80,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, OrderSubType>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, OrderSubType>(
EnumHelper.get_values<OrderSubType>().ToList(),
ort => ort.order.order.sub_type(),
nameof(OrderBookRowVM.order_sub_type)),
@@ -215,13 +215,13 @@ namespace mbts.spark {
_wrap_comparer(r => r.order_sub_type)));
// side
Add(side_column = new SideColumn(
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, Side>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, Side>(
new[] { Side.Buy, Side.Sell },
ort => ort.order.order.side(),
nameof(OrderBookRowVM.side))));
// quantity
Add(qty_column = new SizeColumn(
new DoubleMinMax<OrderSecurityRootPair>(
new DoubleMinMax<OrderRecordTupleWithRoot>(
ort => ort.order.order.quantity(), nameof(OrderBookRowVM.quantity))));
// edit quantity column
// not usually part of the main order book, but it's useful to add it
@@ -229,7 +229,7 @@ namespace mbts.spark {
//Add(edit_qty_column = new EditableQtyColumn());
// filled quantity
Add(filled_qty_column = new FilledColumn(
new DoubleMinMax<OrderSecurityRootPair>(
new DoubleMinMax<OrderRecordTupleWithRoot>(
ort => ort.order.order.filled_quantity(),
nameof(OrderBookRowVM.filled_quantity))));
// price
@@ -238,7 +238,7 @@ namespace mbts.spark {
"Price",
r => r.price_text,
DefaultColumnWidths.Price,
new PriceMinMax<OrderSecurityRootPair>(
new PriceMinMax<OrderRecordTupleWithRoot>(
ort => ort.order.order.price(),
nameof(OrderBookRowVM.price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -254,7 +254,7 @@ namespace mbts.spark {
"Avg Price",
r => r.avg_price_text,
DefaultColumnWidths.Price,
new PriceMinMax<OrderSecurityRootPair>(
new PriceMinMax<OrderRecordTupleWithRoot>(
ort => ort.order.order.avg_price(),
nameof(OrderBookRowVM.avg_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -265,21 +265,21 @@ namespace mbts.spark {
"Last Filled",
r => r.last_price_text,
DefaultColumnWidths.Price,
new PriceMinMax<OrderSecurityRootPair>(
new PriceMinMax<OrderRecordTupleWithRoot>(
ort => ort.order.order.last_price(),
nameof(OrderBookRowVM.last_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
_wrap_comparer(r => r.last_price)));
// piq
Add(piq_column = new PiqColumn(
new UIntMinMax<OrderSecurityRootPair>(ort => ort.order.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq))));
new UIntMinMax<OrderRecordTupleWithRoot>(ort => ort.order.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq))));
// status
Add(status_column = new SimpleTextColumn<OrderStatus[]>(
Columns.Status,
"Status",
r => r.status.ToString(),
80,
DiscreteValuesFilterVM.Create<OrderSecurityRootPair, OrderStatus>(
DiscreteValuesFilterVM.Create<OrderRecordTupleWithRoot, OrderStatus>(
EnumHelper.get_values<OrderStatus>().ToList(),
ort => ort.order.order.status(),
nameof(OrderBookRowVM.status)),
@@ -287,7 +287,7 @@ namespace mbts.spark {
_wrap_comparer(r => r.status)));
// last message
Add(last_message_column = new OrderBookLastMessageColumn(
new RegexFilterVM<OrderSecurityRootPair>(
new RegexFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.last_msg(),
nameof(OrderBookRowVM.last_msg))));
// security key
@@ -296,7 +296,7 @@ namespace mbts.spark {
DefaultColumnHeaders.SecurityKey,
r => r.security_key.ToString(),
DefaultColumnWidths.SecurityKey,
new RegexFilterVM<OrderSecurityRootPair>(
new RegexFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.security_key().ToString(),
nameof(OrderBookRowVM.security_key)),
DataGridFilterKnownTemplates.Regex,
@@ -307,7 +307,7 @@ namespace mbts.spark {
DefaultColumnHeaders.OrderKey,
r => r.order_key.ToString(),
DefaultColumnWidths.OrderKey,
new RegexFilterVM<OrderSecurityRootPair>(
new RegexFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.Key.ToString(),
nameof(OrderBookRowVM.order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -318,7 +318,7 @@ namespace mbts.spark {
"Parent Key",
r => r.parent_order_key.ToString(),
DefaultColumnWidths.ParentKey,
new RegexFilterVM<OrderSecurityRootPair>(
new RegexFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.ParentKey.ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -329,7 +329,7 @@ namespace mbts.spark {
DefaultColumnHeaders.AttachedTargetOrderKey,
r => r.order.attached_target_order_key().ToString(),
DefaultColumnWidths.AttachedTargetOrderKey,
new RegexFilterVM<OrderSecurityRootPair>(
new RegexFilterVM<OrderRecordTupleWithRoot>(
ort => ort.order.order.attached_target_order_key().ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -451,9 +451,9 @@ namespace mbts.spark {
}
}
public Func<OrderSecurityRootPair, bool> get_filter() {
public Func<OrderRecordTupleWithRoot, bool> get_filter() {
var active_filters = this.OfType<ICVOrderBookColumn>().Where(c => c.filter.active.GetValueOrDefault()).Select(c => c.filter).ToArray();
return active_filters.Length == 0 ? null : new Func<OrderSecurityRootPair, bool>(r => active_filters.All(f => f.filter(r)));
return active_filters.Length == 0 ? null : new Func<OrderRecordTupleWithRoot, bool>(r => active_filters.All(f => f.filter(r)));
}
public OrderBookSortingData get_sorting_data() {
@@ -554,7 +554,7 @@ namespace mbts.spark {
GlyphContext _root_glyph_context, _child_glyph_context;
protected OrderbookColumnBase(Columns col_key, string header, Func<OrderBookRowVM, string> get_text, double width,
IDataGridColumnPersistentFilter<OrderSecurityRootPair, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
id = key.ToString();
Width = width;
Header = header;
@@ -571,10 +571,10 @@ namespace mbts.spark {
}
}
public IDataGridColumnPersistentFilter<OrderSecurityRootPair, T> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, T> filter { get; }
public IComparer<OrderBookRowVM> comparer { get; }
IDataGridColumnFilter<OrderSecurityRootPair> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTupleWithRoot> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter_model => filter;
string IFilterableColumn.filter_template => _filter_template;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -588,7 +588,7 @@ namespace mbts.spark {
public class SimpleTextColumn<TFilterState> : OrderbookColumnBase<TFilterState>, IRenderColumn<OrderBookRowVM> {
public SimpleTextColumn(Columns key, string header, Func<OrderBookRowVM, string> get_text, double width,
IDataGridColumnPersistentFilter<OrderSecurityRootPair, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
: base(key, header, get_text, width, filter, filter_template, comparer) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -608,7 +608,7 @@ namespace mbts.spark {
#region Explicit Column Defs
public class SideColumn : OrderbookColumnBase<Side[]>, IRenderColumn<OrderBookRowVM> {
public SideColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, Side[]> filter)
public SideColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, Side[]> filter)
: base(Columns.Side, "B/S", r => r.side.ToString(), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues, _wrap_comparer(r => r.side)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -627,7 +627,7 @@ namespace mbts.spark {
}
public class SizeColumn : OrderbookColumnBase<DoubleMinMaxState>, IRenderColumn<OrderBookRowVM> {
public SizeColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, DoubleMinMaxState> filter)
public SizeColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, DoubleMinMaxState> filter)
: base(Columns.Size, "Qty", r => r.display_quantity_text, DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.quantity)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -646,7 +646,7 @@ namespace mbts.spark {
}
public class FilledColumn : OrderbookColumnBase<DoubleMinMaxState>, IRenderColumn<OrderBookRowVM> {
public FilledColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, DoubleMinMaxState> filter)
public FilledColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, DoubleMinMaxState> filter)
: base(Columns.Filled, "Filled Qty", r => r.display_filled_quantity.ToString(), DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.DoubleMinMax, _wrap_comparer(r => r.filled_quantity)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -668,7 +668,7 @@ namespace mbts.spark {
readonly BindingBase _foreground_binding;
ListSortDirection? _cached_sort_direction;
public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer<OrderBookRowVM> row_comparer, IDataGridColumnPersistentFilter<OrderSecurityRootPair, AlgoID[]> filter, string header = DefaultColumnHeaders.OrderType)
public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer<OrderBookRowVM> row_comparer, IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, AlgoID[]> filter, string header = DefaultColumnHeaders.OrderType)
: base(key, new Binding(badge_fill_binding_path), new Binding(display_name_binding_path), filter, header) {
id = key.ToString();
this.filter = filter;
@@ -678,11 +678,11 @@ namespace mbts.spark {
this.comparer = row_comparer;
}
public IDataGridColumnPersistentFilter<OrderSecurityRootPair, AlgoID[]> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, AlgoID[]> filter { get; }
public override string filter_template => DataGridFilterKnownTemplates.AlgoType;
public IComparer<OrderBookRowVM> comparer { get; }
IDataGridColumnFilter<OrderSecurityRootPair> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTupleWithRoot> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
public override FrameworkElement view_factory() {
@@ -700,7 +700,7 @@ namespace mbts.spark {
public class OrderBookLastMessageColumn : TextColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter)
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, string> filter)
: base(Columns.LastMessage, filter, DataGridFilterKnownTemplates.Regex) {
id = key.ToString();
this.filter = filter;
@@ -710,10 +710,10 @@ namespace mbts.spark {
ToolTipBinding = new Binding(nameof(OrderBookRowVM.last_msg));
}
public IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, string> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.last_msg);
IDataGridColumnFilter<OrderSecurityRootPair> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTupleWithRoot> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
@@ -723,7 +723,7 @@ namespace mbts.spark {
}
public class PiqColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
public PiqColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, UIntMinMaxState> filter)
public PiqColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, UIntMinMaxState> filter)
: base(Columns.Piq, "PIQ", r => r.piq_text, DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.piq)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -748,7 +748,7 @@ namespace mbts.spark {
ListSortDirection? _cached_sort_direction;
public SecurityColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, SecurityCriteria> filter) : base(Columns.Security) {
public SecurityColumn(IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, SecurityCriteria> filter) : base(Columns.Security) {
id = key.ToString();
this.filter = filter;
_foreground_binding = RenderUtils.get_foreground_binding(this);
@@ -757,13 +757,13 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
public IDataGridColumnPersistentFilter<OrderSecurityRootPair, SecurityCriteria> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTupleWithRoot, SecurityCriteria> filter { get; }
public IComparer<OrderBookRowVM> comparer =>
ComparerWrapper<OrderBookRowVM>.wrap(
r => r.security, Comparer<SecurityImmutable?>.Default);
IDataGridColumnFilter<OrderSecurityRootPair> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTupleWithRoot> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter_model => filter;
string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -24,7 +24,7 @@ using Columns = mbts.spark.OrderBookGridView.ColumnKeys;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
namespace mbts.spark {
partial class OrderBookRowVM : IEquatable<OrderBookRowVM>, DIYGrid.IRowVM, IHierarchicalRow<OrderSecurityRootPair>, INotifyPropertyChanged {
partial class OrderBookRowVM : IEquatable<OrderBookRowVM>, DIYGrid.IRowVM, IHierarchicalRow<OrderRecordTupleWithRoot>, INotifyPropertyChanged {
public static readonly IComparer<OrderBookRowVM> key_comparer = Comparer<uint>.Default.wrap<uint, OrderBookRowVM>(r => r.order_key).to_safe();
const string _unknown_security_price_format_string = "0.#########";
@@ -45,7 +45,7 @@ namespace mbts.spark {
double _prospective_price;
Action<bool> _on_selection_changed;
public OrderBookRowVM(OrderBookVM owner, OrderSecurityRootPair order_tuple, bool is_expanded, Action<bool> on_selection_changed) {
public OrderBookRowVM(OrderBookVM owner, OrderRecordTupleWithRoot order_tuple, bool is_expanded, Action<bool> on_selection_changed) {
_owner = owner;
this.order_tuple = order_tuple;
_is_expanded = is_expanded;
@@ -59,19 +59,19 @@ namespace mbts.spark {
//// when the OrderBookVM.selected_order_changes, this emulates the selected
//// order changing since the current_row setter invokes the selected_order_changed
//// handler
public IObservable<OrderSecurityRootPair> subscribe_data() {
return Observable.FromEvent<Action, OrderSecurityRootPair>(
public IObservable<OrderRecordTupleWithRoot> subscribe_data() {
return Observable.FromEvent<Action, OrderRecordTupleWithRoot>(
cb => () => cb(order_tuple),
cb => invalidated += cb,
cb => invalidated -= cb);
}
public event Action invalidated;
public event Action<(OrderSecurityRootPair oldval, OrderSecurityRootPair newval)> updated;
public event Action<(OrderRecordTupleWithRoot oldval, OrderRecordTupleWithRoot newval)> updated;
public event PropertyChangedEventHandler PropertyChanged;
// Core
public OrderSecurityRootPair order_tuple { get; private set; }
public OrderRecordTupleWithRoot order_tuple { get; private set; }
public OrderRecordImmutable order => order_tuple.order.order;
public OrderMetadata order_metadata => _owner.get_metadata(this);
public Brush badge_fill => _badge_fill ?? (_badge_fill = OrderUtils.badge_fill(order_tuple.order.meta, order_metadata));
@@ -140,7 +140,7 @@ namespace mbts.spark {
order.filled_status_description(security.spec_or_default(), _quantity_display_settings);
// Root Algo
public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo.value.CustomCase;
public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo_type;
public OrderMetadata root_algo_order_metadata => _owner.get_metadata(root_algo_order_type);
public Brush root_algo_badge_fill => _root_algo_badge_fill ?? (_root_algo_badge_fill = new SolidColorBrush(_root_algo_badge_color));
public string root_algo_display_name => order_tuple.root.display_name();
@@ -289,7 +289,7 @@ namespace mbts.spark {
bool IHierarchicalRow.is_parent => is_parent;
bool IHierarchicalRow.is_expanded => is_expanded;
int IHierarchicalRow.depth_level => depth_level;
OrderSecurityRootPair IHierarchicalRow<OrderSecurityRootPair>.value => order_tuple;
OrderRecordTupleWithRoot IHierarchicalRow<OrderRecordTupleWithRoot>.value => order_tuple;
void IHierarchicalRow.on_is_parent_changed(bool is_parent) => this.is_parent = is_parent;
/// Do NOT actually call the <see cref="is_expanded"/> setter (it has side effects) - the row collection calls this method when the row is expanded/collapsed by some **external means, outside of this class.
@@ -301,7 +301,7 @@ namespace mbts.spark {
/// <see cref="OperableHierarchicalCollection{TRow, T, TKey}.collapse_row(TKey)"/>
void IHierarchicalRow.on_is_expanded_changed(bool is_expanded) => Set(ref _is_expanded, is_expanded, nameof(is_expanded));
void IHierarchicalRow.on_depth_level_changed(int depth_level) => this.depth_level = depth_level;
void IHierarchicalRow<OrderSecurityRootPair>.on_value_changed(OrderSecurityRootPair value) => update(value);
void IHierarchicalRow<OrderRecordTupleWithRoot>.on_value_changed(OrderRecordTupleWithRoot value) => update(value);
#endregion
private void _unselect_me() {
@@ -317,7 +317,7 @@ namespace mbts.spark {
internal void expand_internal() => Set(ref _is_expanded, true, nameof(is_expanded));
internal void collapse_internal() => Set(ref _is_expanded, false, nameof(is_expanded));
public void update(OrderSecurityRootPair order_tuple) {
public void update(OrderRecordTupleWithRoot order_tuple) {
Log.assert(order_tuple.order.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key.");
// _show_order_modify_cmd is lazy (instantiated in the default_command getter); it might be null, don't not force instantiation
bool? could_modify_execute = _show_order_modify_cmd?.CanExecute(null);
@@ -365,7 +365,7 @@ namespace mbts.spark {
RaisePropertyChanged(nameof(badge_fill));
}
// display name
if (old_order_tuple.order.algo.name != order_tuple.order.algo.name)
if (old_order_tuple.order.algo?.name != order_tuple.order.algo_name)
RaisePropertyChanged(nameof(display_name));
// root badge fill
if (_root_algo_badge_color_backing.HasValue) {
@@ -374,10 +374,10 @@ namespace mbts.spark {
RaisePropertyChanged(nameof(root_algo_badge_fill));
}
// root display name
if (old_order_tuple.root.algo.name != order_tuple.root.algo.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) {
if (old_order_tuple.root.algo_type != order_tuple.root.algo_type) {
RaisePropertyChanged(nameof(root_algo_order_type));
}
// status
@@ -493,7 +493,8 @@ namespace mbts.spark {
Columns.AvgFilled |
Columns.Status;
public static Columns get_dirty_cells(OrderSecurityRootPair oldval, OrderSecurityRootPair newval) {
public static Columns get_dirty_cells(
OrderRecordTupleWithRoot oldval, OrderRecordTupleWithRoot newval) {
var dirty = (Columns)0;
if (oldval.order.security != newval.order.security)
dirty |= Columns.Security;
@@ -56,7 +56,7 @@ namespace mbts.spark {
readonly Property<OrderBookRowVM> _current_row;
readonly ObservableSortedCollection<OrderBookRowVM> _selected_rows = new ObservableSortedCollection<OrderBookRowVM>(OrderBookRowVM.key_comparer);
readonly DelegateProperty<bool> _show_order_params, _show_ladder, _show_fills, _can_attach_selected_orders, _can_detach_selected_orders;
readonly OperableHierarchicalCollection<OrderBookRowVM, OrderSecurityRootPair, uint> _row_collection;
readonly OperableHierarchicalCollection<OrderBookRowVM, OrderRecordTupleWithRoot, uint> _row_collection;
readonly OrderBookColumnCollection _columns;
readonly IWindowSettingsManager<OrderBookGridSettings> _settings_manager;
readonly IWindowSettingsManager<GridSettings> _fills_settings_manager = new WindowSettingsManager<GridSettings>.DisconnectedImpl(FillsSettings.MiniGridSettings, FillsSettings.MiniGridSettings);
@@ -64,7 +64,7 @@ namespace mbts.spark {
readonly CommonValueMonitor<SecurityImmutable?> _selected_security_mon = new CommonValueMonitor<SecurityImmutable?>();
readonly RightPanelModel _right_panel = new RightPanelModel();
readonly CustomStateSynchronizer _custom_state_sync;
readonly Func<OrderSecurityRootPair, bool> _global_filter;
readonly Func<OrderRecordTupleWithRoot, bool> _global_filter;
OrderBookFillsGridSettings _cached_fills_settings = OrderBookStartupData.DefaultFillsGrid;
double
_raw_right_panel_width = OrderBookStartupData.Default.right_panel_width,
@@ -79,7 +79,7 @@ namespace mbts.spark {
_is_attaching_orders,
_is_row_collection_populated,
_all_rows_selected;
IReadOnlyDictionary<uint, OrderSecurityRootPair> _cached_orders = DictionaryHelper.empty<uint, OrderSecurityRootPair>();
IReadOnlyDictionary<uint, OrderRecordTupleWithRoot> _cached_orders = DictionaryHelper.empty<uint, OrderRecordTupleWithRoot>();
IReadOnlyDictionary<uint, bool> _cached_attachable = DictionaryHelper.empty<uint, bool>(), _cached_detachable = DictionaryHelper.empty<uint, bool>();
IReadOnlyDictionary<uint, SecurityMD> _cached_securities = new Dictionary<uint, SecurityMD>(0);
HashSet<uint>
@@ -95,7 +95,7 @@ namespace mbts.spark {
ISecurityMetadataStore sec_meta_store,
IWindowSettingsManager<OrderBookGridSettings> settings_manager,
bool rows_are_initially_expanded = false,
Func<OrderSecurityRootPair, bool> global_filter = null)
Func<OrderRecordTupleWithRoot, bool> global_filter = null)
: this(
bus,
notification_service,
@@ -113,10 +113,10 @@ namespace mbts.spark {
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source,
IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> orders_source,
IWindowSettingsManager<OrderBookGridSettings> settings_manager,
bool rows_are_initially_expanded = false,
Func<OrderSecurityRootPair, bool> global_filter = null) {
Func<OrderRecordTupleWithRoot, bool> global_filter = null) {
_bus = bus;
_model = model;
@@ -157,7 +157,7 @@ namespace mbts.spark {
_columns = new OrderBookColumnCollection(bus, model, model.on_order_securities.Select(x => (x.added.Values, x.removed.Values)));
// we use an ObservableAppendCollection b/c the mini-ob needs a cancel column at the front
columns = new ObservableAppendCollection<DIYGrid.ColumnBase>(_columns);
_row_collection = new OperableHierarchicalCollection<OrderBookRowVM, OrderSecurityRootPair, uint>(
_row_collection = new OperableHierarchicalCollection<OrderBookRowVM, OrderRecordTupleWithRoot, uint>(
row_factory,
r => r.order.order.Key,
r => r.order.order.ParentKey,
@@ -362,7 +362,7 @@ namespace mbts.spark {
}
});
OrderBookRowVM row_factory(OrderSecurityRootPair o) {
OrderBookRowVM row_factory(OrderRecordTupleWithRoot o) {
var row = new OrderBookRowVM(this, o, rows_are_initially_expanded, on_is_selected_changed) {
is_attachable = _cached_attachable.TryGetValue(o.order.order.Key, out bool ia) && ia,
is_detachable = _cached_detachable.TryGetValue(o.order.order.Key, out bool id)
@@ -595,16 +595,16 @@ namespace mbts.spark {
public IObservable<bool> subscribe_show_fills() => _show_fills.observe_current(true);
public IObservable<bool> subscribe_show_ladder() => _show_ladder.observe_current(true);
public IObservable<bool> subscribe_show_order_params() => _show_order_params.observe_current(true);
public IObservable<OrderSecurityAlgo?> subscribe_single_selected_order() =>
Observable.Create<OrderSecurityAlgo?>(o => {
OrderSecurityAlgo? last_fired = null;
public IObservable<OrderRecordTuple?> subscribe_single_selected_order() =>
Observable.Create<OrderRecordTuple?>(o => {
OrderRecordTuple? last_fired = null;
orders_changed += notify;
_current_row.Changed += on_current_row_changed;
notify();
return Disposable.Create(dispose);
// local methods
void notify() {
var next = current_row == null ? (OrderSecurityAlgo?)null : current_row.order_tuple.order;
var next = current_row == null ? (OrderRecordTuple?)null : current_row.order_tuple.order;
if (next != last_fired)
o.OnNext(last_fired = next);
}
@@ -846,7 +846,7 @@ namespace mbts.spark {
// ----
var update_params = selected_rows.Select(r => update_params_factory(r.order_tuple.root)).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(OrderSecurityAlgo order_tuple) {
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderRecordTuple 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);
@@ -940,25 +940,25 @@ namespace mbts.spark {
struct FilterData : IEquatable<FilterData> {
public readonly AlgoTreeDisplayMode algo_tree_display_mode;
public readonly FilterStates column_filters;
public readonly Func<OrderSecurityRootPair, bool> global_filter;
public readonly Func<OrderRecordTupleWithRoot, bool> global_filter;
public FilterData(AlgoTreeDisplayMode algo_tree_display_mode, FilterStates column_filters, Func<OrderSecurityRootPair, bool> global_filter) {
public FilterData(AlgoTreeDisplayMode algo_tree_display_mode, FilterStates column_filters, Func<OrderRecordTupleWithRoot, bool> global_filter) {
this.algo_tree_display_mode = algo_tree_display_mode;
this.column_filters = column_filters;
this.global_filter = global_filter;
}
public Func<OrderSecurityRootPair, bool> build_predicate() {
public Func<OrderRecordTupleWithRoot, bool> build_predicate() {
if (global_filter == null)
return _build_predicate_core();
var core_pred = _build_predicate_core();
if (core_pred == null)
return global_filter;
var glbf = global_filter;
return new Func<OrderSecurityRootPair, bool>(o => glbf(o) && core_pred(o));
return new Func<OrderRecordTupleWithRoot, bool>(o => glbf(o) && core_pred(o));
}
Func<OrderSecurityRootPair, bool> _build_predicate_core() {
Func<OrderRecordTupleWithRoot, bool> _build_predicate_core() {
var pred = column_filters.build_predicate();
if (algo_tree_display_mode == AlgoTreeDisplayMode.RootAndLeafNodes) {
if (pred == null) {
@@ -967,7 +967,7 @@ namespace mbts.spark {
var col_pred = pred;
pred = o => tree_disp_pred(o) && col_pred(o);
}
bool tree_disp_pred(OrderSecurityRootPair o) =>
bool tree_disp_pred(OrderRecordTupleWithRoot o) =>
!o.order.order.has_parent() ||
o.order.order.is_exchange_order() ||
o.order.order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader;
@@ -124,8 +124,8 @@ namespace bts.shell.orderbook {
}
static class FilterStatesExtensions {
public static Func<OrderSecurityRootPair, bool> build_predicate(this FilterStates fs) {
var pb = new ColumnPredicateBuilder<OrderSecurityRootPair>();
public static Func<OrderRecordTupleWithRoot, bool> build_predicate(this FilterStates fs) {
var pb = new ColumnPredicateBuilder<OrderRecordTupleWithRoot>();
// security
pb.add_security_criteria(fs.security_criteria, o => o.order.security);
// regex
@@ -142,7 +142,7 @@ namespace bts.shell.orderbook {
pb.add_discrete_values(fs.exchanges, o => o.order.security?.Exchange ?? Venue.Unset);
pb.add_discrete_values(fs.tifs, o => o.order.order.time_in_force());
pb.add_discrete_values(fs.order_types, o => AlgoID.from_custom_def(o.order.order.Def.CustomDef));
pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root.algo.key));
pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root.algo?.key ?? default));
pb.add_discrete_values(fs.order_sub_types, o => o.order.order.sub_type());
pb.add_discrete_values(fs.sides, o => o.order.order.side());
pb.add_discrete_values(fs.statuses, o => o.order.order.status());
@@ -7,6 +7,8 @@ using mbts.ui;
using ProtoBuf;
using Spark.Api.Orders;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -20,7 +22,7 @@ namespace bts.shell.orderbook {
}
[ProtoContract]
class OrderBookGridSettings : IGridSettingsWithNotifications<OrderSecurity, OrderRecordTuplePredicate>, IEquatable<OrderBookGridSettings> {
class OrderBookGridSettings : IGridSettingsWithNotifications<OrderRecordTuple, OrderRecordTuplePredicate>, IEquatable<OrderBookGridSettings> {
const AlgoTreeDisplayMode _default_algo_tree_display_mode = AlgoTreeDisplayMode.FullTree;
// general
[ProtoMember(1)]
@@ -44,7 +46,7 @@ namespace bts.shell.orderbook {
}
public IReadOnlyList<OrderRecordTuplePredicateAnimations> predicate_animations => _predicate_animations ?? (_predicate_animations = new List<OrderRecordTuplePredicateAnimations>());
IEnumerable<IPredicateAnimationsData<OrderSecurity, OrderRecordTuplePredicate>> IGridSettingsWithNotifications<OrderSecurity, OrderRecordTuplePredicate>.predicate_animations => predicate_animations;
IEnumerable<IPredicateAnimationsData<OrderRecordTuple, OrderRecordTuplePredicate>> IGridSettingsWithNotifications<OrderRecordTuple, OrderRecordTuplePredicate>.predicate_animations => predicate_animations;
public OrderBookGridSettings with(GridSettings general) =>
new OrderBookGridSettings(general ?? this.general, predicate_animations) {
@@ -8,6 +8,7 @@ using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.utility;
using Spark.Api.Orders;
using Spark.Core.Data;
using Spark.Core.Disposables;
@@ -46,17 +47,17 @@ namespace bts.shell.orderbook {
ISecurityMetadataStore sec_meta_store,
IEnumerable<OrderBookRowVM> rows,
ObservableCollection<DIYGrid.ColumnBase> columns) {
core_manager = new GridSettingsManager<OrderBookRowVM, OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings>(
core_manager = new GridSettingsManager<OrderBookRowVM, OrderRecordTuple, OrderRecordTuplePredicate, OrderBookGridSettings>(
bus, model, rows, columns,
() => new OrderRecordTuplePredicate(),
() => {
var pvm = PredicateVMWrapper.create<OrderSecurity, OrderRecordTuplePredicate, OrderRecordTuplePredicate.PredicateTypeOneofCase>(
var pvm = PredicateVMWrapper.create<OrderRecordTuple, OrderRecordTuplePredicate, OrderRecordTuplePredicate.PredicateTypeOneofCase>(
OrderRecordTuplePredicateVMFactory.get_oneofs(bus, model), rp => rp.predicate_type_case);
pvm.selected_predicate_type = pvm.predicate_types.FirstOrDefault();
return pvm;
},
col_id => {
var pvm = PredicateVMWrapper.create<OrderSecurity, OrderRecordTuplePredicate, OrderRecordTuplePredicate.PredicateTypeOneofCase>(
var pvm = PredicateVMWrapper.create<OrderRecordTuple, OrderRecordTuplePredicate, OrderRecordTuplePredicate.PredicateTypeOneofCase>(
OrderRecordTuplePredicateVMFactory.get_oneofs(bus, model), rp => rp.predicate_type_case);
pvm.selected_predicate_type = _corresponding_predicate_type(EnumHelper.parse_or_default<Columns>(col_id));
return pvm;
@@ -64,15 +65,15 @@ namespace bts.shell.orderbook {
(gen, anims) => new OrderBookGridSettings(gen, anims.empty_if_null().Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_data, a.cell_animations, a.row_animations, a.sound_notifications))) { algo_tree_display_mode = _algo_tree_display_mode },
p => p.create_predicate(notification_service.data_cache, sec_meta_store),
p => p.create_notification_predicate(notification_service.data_cache, sec_meta_store),
notification_service == null ? new Func<IPredicate<OrderSecurity>, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order,
notification_service == null ? new Func<INotificationPredicate<OrderSecurity>, IDisposable>(t => Disposable.empty) : notification_service.link_to_order,
notification_service == null ? new Func<IPredicate<OrderRecordTuple>, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order,
notification_service == null ? new Func<INotificationPredicate<OrderRecordTuple>, IDisposable>(t => Disposable.empty) : notification_service.link_to_order,
hard_column_flags);
_core_man_as_observer = core_manager;
}
public event Action algo_tree_display_mode_changed;
public GridSettingsManager<OrderBookRowVM, OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings> core_manager { get; }
public GridSettingsManager<OrderBookRowVM, OrderRecordTuple, OrderRecordTuplePredicate, OrderBookGridSettings> core_manager { get; }
public AlgoTreeDisplayMode algo_tree_display_mode {
get => _algo_tree_display_mode;
@@ -8,6 +8,8 @@ using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.spark;
using Spark.Api.Orders;
using System;
using System.Collections.Generic;
@@ -15,23 +17,23 @@ namespace bts.shell.orderbook {
class OrderBookSettingsVM : DisposableViewModelBase, IWindowSettingsVM<OrderBookGridSettings>, ITemplateSelectorKey {
AlgoTreeDisplayMode _algo_tree_display_mode;
public OrderBookSettingsVM(GridSettingsVM<OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings> core_settings_vm) =>
public OrderBookSettingsVM(GridSettingsVM<OrderRecordTuple, OrderRecordTuplePredicate, OrderBookGridSettings> core_settings_vm) =>
this.core_settings_vm = core_settings_vm;
public OrderBookSettingsVM(
IBus bus,
OrdersModel orders_model,
Func<OrderRecordTuplePredicate> predicate_data_factory,
Func<OrderRecordTuplePredicate, INotificationPredicate<OrderSecurity>> notification_predicate_factory,
Func<OrderRecordTuplePredicate, INotificationPredicate<OrderRecordTuple>> notification_predicate_factory,
Func<IPropertyWrapperVM<OrderRecordTuplePredicate>> create_predicate_vm,
Func<string, IPropertyWrapperVM<OrderRecordTuplePredicate>> create_column_predicate_vm,
Func<GridSettings, IEnumerable<IPredicateAnimationsData<OrderSecurity, OrderRecordTuplePredicate>>, OrderBookGridSettings> create_settings_obj,
Func<GridSettings, IEnumerable<IPredicateAnimationsData<OrderRecordTuple, OrderRecordTuplePredicate>>, OrderBookGridSettings> create_settings_obj,
IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> column_flags = null) {
core_settings_vm = new GridSettingsVM<OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings>(
core_settings_vm = new GridSettingsVM<OrderRecordTuple, OrderRecordTuplePredicate, OrderBookGridSettings>(
bus, orders_model, predicate_data_factory, notification_predicate_factory, create_predicate_vm, create_column_predicate_vm, create_settings_obj, column_flags);
}
public GridSettingsVM<OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings> core_settings_vm { get; }
public GridSettingsVM<OrderRecordTuple, OrderRecordTuplePredicate, OrderBookGridSettings> core_settings_vm { get; }
public AlgoTreeDisplayMode algo_tree_display_mode { get => _algo_tree_display_mode; set => Set(ref _algo_tree_display_mode, value); }
string ITemplateSelectorKey.key => GridSettingsTemplateKeys.OrderBook;
@@ -48,7 +48,7 @@ namespace bts.shell.pnl {
static readonly TimeSpan _auxiliary_grid_update_throttle = TimeSpan.FromSeconds(0.2);
// delegates
static readonly Func<OrderSecurityRootPair, PNLKey> _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key());
static readonly Func<OrderRecordTupleWithRoot, PNLKey> _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key());
static readonly Func<FillTuple, PNLKey> _fill_pnl_key_fn = f => new PNLKey(f.account_id, f.fill.SecurityKey);
readonly IBus _bus;
@@ -503,7 +503,7 @@ namespace bts.shell.pnl {
switch (header) {
case PNLHeaderRowDisplay.SelectedTotal:
// throttle selection changes (they have a potentially high frequency)
var filter_src = System.Reactive.Linq.ObservableExtensions.FromEventThrottle<SelectionChangedEventArgs, Func<OrderSecurityRootPair, bool>>(
var filter_src = System.Reactive.Linq.ObservableExtensions.FromEventThrottle<SelectionChangedEventArgs, Func<OrderRecordTupleWithRoot, bool>>(
cb => _selection_changed += cb,
cb => _selection_changed -= cb,
_ => _mk_selected_items_filter(_order_pnl_key_fn),
@@ -791,7 +791,11 @@ namespace bts.shell.pnl {
Func<T, bool> _mk_selected_items_filter<T>(Func<T, PNLKey> key_selector) =>
_mk_items_filter(_selected_rows.Select(r => r.key), key_selector);
OrderBookVM _mk_orderbook_vm_common(orderbook.FilterStates filters, IEnumerable<ColumnKeys> hide_counterparts, IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source = null) {
OrderBookVM _mk_orderbook_vm_common(
orderbook.FilterStates filters,
IEnumerable<ColumnKeys> hide_counterparts,
IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> orders_source = null
) {
var state = new orderbook.OrderBookStartupData(filters, orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false);
state.orderbook_grid.general = GridSettingsHelper.hide_cols(state.orderbook_grid.general, hide_counterparts);
var settings_man = new WindowSettingsManager<orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
@@ -807,9 +811,9 @@ namespace bts.shell.pnl {
IObservable<TableUpdate<FillTuple, string>> _visible_fills_source() =>
_orders_model.on_fill_tuples.Filter(_visible_items_filter_source(_fill_pnl_key_fn), FillTuple.key_fn);
IObservable<TableUpdate<OrderSecurityRootPair, uint>> _visible_orders_source() =>
_orders_model.on_order_tuples_with_root_and_piq.Filter(
_visible_items_filter_source(_order_pnl_key_fn), o => o.order.order.Key);
IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> _visible_orders_source() =>
_orders_model.on_order_tuples_with_root_and_piq
.Filter(_visible_items_filter_source(_order_pnl_key_fn), o => o.order.order.Key);
IObservable<Func<T, bool>> _visible_items_filter_source<T>(Func<T, PNLKey> key_selector) =>
Observable.Create<Func<T, bool>>(o => {
@@ -11,6 +11,7 @@ using mbts.spark;
using mbts.ui;
using mbts.utils;
using Spark.Api.Orders;
using Spark.Core.Disposables;
using System;
@@ -26,8 +27,8 @@ namespace bts.shell {
INotificationServiceDataCache data_cache { get; }
IDisposable link_to_activity(IPredicate<Activity> predicate, SoundNotification sound);
IDisposable link_to_activity(INotificationPredicate<Activity> toast_notification_predicate);
IDisposable link_to_order(IPredicate<OrderSecurity> predicate, SoundNotification sound);
IDisposable link_to_order(INotificationPredicate<OrderSecurity> toast_notification_predicate);
IDisposable link_to_order(IPredicate<OrderRecordTuple> predicate, SoundNotification sound);
IDisposable link_to_order(INotificationPredicate<OrderRecordTuple> toast_notification_predicate);
// Note: security criteria should not be incorporated in the predicate's 'trigger' impl.
// It is easier/cleaner if the INotificationService incorporates the criteria internally.
IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate<TradeInfo> predicate, SoundNotification sound);
@@ -38,7 +39,7 @@ namespace bts.shell {
// activity notifications
readonly NotificationProcessor<Activity> _activity_notifications;
// order notifications
readonly NotificationProcessor<OrderSecurity> _order_notifications;
readonly NotificationProcessor<OrderRecordTuple> _order_notifications;
// trade notifications
readonly NotificationProcessor<TradeInfo> _trade_notifications;
readonly MDConsumer _consumer;
@@ -55,7 +56,7 @@ namespace bts.shell {
public NotificationService(IBus bus, INotifier notifier, OrdersModel orders_model, MDConsumer consumer) {
this.notifier = notifier;
_activity_notifications = new NotificationProcessor<Activity>(notifier);
_order_notifications = new NotificationProcessor<OrderSecurity>(notifier);
_order_notifications = new NotificationProcessor<OrderRecordTuple>(notifier);
_trade_notifications = new NotificationProcessor<TradeInfo>(notifier);
_consumer = consumer;
_dispose = Disposable.Create(
@@ -78,8 +79,9 @@ namespace bts.shell {
public IDisposable link_to_activity(IPredicate<Activity> predicate, SoundNotification sound) => _activity_notifications.link(predicate, sound);
public IDisposable link_to_activity(INotificationPredicate<Activity> toast_notification_predicate) => _activity_notifications.link(toast_notification_predicate);
public IDisposable link_to_order(IPredicate<OrderSecurity> predicate, SoundNotification sound) => _order_notifications.link(predicate, sound);
public IDisposable link_to_order(INotificationPredicate<OrderSecurity> toast_notification_predicate) => _order_notifications.link(toast_notification_predicate);
public IDisposable link_to_order(IPredicate<OrderRecordTuple> predicate, SoundNotification sound) => _order_notifications.link(predicate, sound);
public IDisposable link_to_order(INotificationPredicate<OrderRecordTuple> notification_predicate) =>
_order_notifications.link(notification_predicate);
public IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate<TradeInfo> predicate, SoundNotification sound) {
if (predicate == null) {
@@ -119,7 +121,7 @@ namespace bts.shell {
void _on_activity(Activity activity) =>
_activity_notifications.process_item(activity);
void _on_orders(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) {
void _on_orders(TableUpdate<OrderRecordTuple, uint> update) {
// must update notification_service_data_cache first, some of the predicate/triggers (esp. ToastNotifications) will use the notification_service_data_cache to lookup order-history
_data_cache.update(update.as_iincremental());
foreach (var o in update.added.Concat(update.changed))
@@ -4,6 +4,8 @@ using bts.api.orderman;
using mbts.spark;
using mbts.utils;
using Spark.Api.Orders;
using System;
using System.Collections.Generic;
@@ -17,12 +19,12 @@ namespace bts.shell {
interface INotificationServiceDataCache {
DateTime last_order_reset_time { get; }
bool is_first_order_update { get; }
IReadOnlyDictionary<uint, List<TimeStampedData<OrderSecurity>>> order_history { get; }
IReadOnlyDictionary<uint, List<TimeStampedData<OrderRecordTuple>>> order_history { get; }
}
static class NotificationServiceDataCacheExtensions {
public static OrderSecurity? get_previous_order_state(this INotificationServiceDataCache notification_service_data_cache, uint key) {
if (notification_service_data_cache.order_history.TryGetValue(key, out List<TimeStampedData<OrderSecurity>> l)) {
public static OrderRecordTuple? get_previous_order_state(this INotificationServiceDataCache notification_service_data_cache, uint key) {
if (notification_service_data_cache.order_history.TryGetValue(key, out List<TimeStampedData<OrderRecordTuple>> l)) {
if (l.Count > 1) {
return l[l.Count - 2].data;
}
@@ -44,15 +46,15 @@ namespace bts.shell {
partial class NotificationService : INotificationService, IDisposable {
class DataCache : INotificationServiceDataCache {
const int _buffer_size = 10;
readonly Dictionary<uint, OrderSecurity> _order_cache = new Dictionary<uint, OrderSecurity>();
readonly Dictionary<uint, List<TimeStampedData<OrderSecurity>>> _order_history = new Dictionary<uint, List<TimeStampedData<OrderSecurity>>>();
readonly Dictionary<uint, OrderRecordTuple> _order_cache = new();
readonly Dictionary<uint, List<TimeStampedData<OrderRecordTuple>>> _order_history = new();
public IReadOnlyDictionary<uint, List<TimeStampedData<OrderSecurity>>> order_history => _order_history;
public IReadOnlyDictionary<uint, List<TimeStampedData<OrderRecordTuple>>> order_history => _order_history;
public DateTime last_order_reset_time { get; private set; }
public bool is_first_order_update { get; private set; }
internal void update(IIncrementalUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> data) {
internal void update(IIncrementalUpdate<OrderRecordTuple, uint> data) {
DateTime now = DateTime.Now;
if (data.removed.Count == _order_cache.Count) {
last_order_reset_time = now;
@@ -62,7 +64,7 @@ namespace bts.shell {
foreach (var kv in data.removed) {
if (data.added.ContainsKey(kv.Key)) {
_order_cache[kv.Key] = kv.Value;
_order_history[kv.Key].Add(new TimeStampedData<OrderSecurity>(kv.Value, now));
_order_history[kv.Key].Add(new TimeStampedData<OrderRecordTuple>(kv.Value, now));
} else {
_order_cache.Remove(kv.Key);
// TODO: maybe these shouldn't be removed?
@@ -76,9 +78,9 @@ namespace bts.shell {
continue;
_order_cache.Add(kv.Key, kv.Value);
_order_history.AddOrUpdate(kv.Key,
k => new List<TimeStampedData<OrderSecurity>> { new TimeStampedData<OrderSecurity>(kv.Value, now) },
k => new List<TimeStampedData<OrderRecordTuple>> { new(kv.Value, now) },
(k, l) => {
l.Add(new TimeStampedData<OrderSecurity>(kv.Value, now));
l.Add(new TimeStampedData<OrderRecordTuple>(kv.Value, now));
if (l.Count >= 10)
l.RemoveAt(0);
});
@@ -65,7 +65,7 @@ namespace bts.shell {
public static IToastNotification order_filled(OrderRecordImmutable oldval, OrderRecordImmutable newval, SecurityImmutable? security) =>
new OrderFilledToastNotification(oldval, newval, security);
public static IToastNotification order_filled(OrderSecurity oldval, OrderSecurity newval) =>
public static IToastNotification order_filled(OrderRecordTuple oldval, OrderRecordTuple newval) =>
new OrderFilledToastNotification(oldval.order, newval.order, newval.security);
public static IToastNotification order_completed(
@@ -75,7 +75,7 @@ namespace bts.shell {
new OrderCompletedToastNotification(order, security, qty_display);
public static IToastNotification order_completed(
OrderSecurity order, TickDisplaySettingsImmutable qty_display) =>
OrderRecordTuple order, TickDisplaySettingsImmutable qty_display) =>
new OrderCompletedToastNotification(order.order, order.security, qty_display);
public static IToastNotification order_status_changed(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) =>
+8 -5
View File
@@ -15,16 +15,19 @@ namespace mbts.spark {
public readonly FillImmutable fill;
public readonly SecurityImmutable? security;
OrderSecurityRootPair? _order_tuple;
OrderRecordTupleWithRoot? _order_tuple;
public FillTuple(FillImmutable fill, SecurityImmutable? security, OrderSecurityRootPair? order_tuple) {
public FillTuple(
FillImmutable fill,
SecurityImmutable? security,
OrderRecordTupleWithRoot? 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, order_tuple.HasValue ? OrderSecurityRootPair.from_order_security(order_tuple.Value) : (OrderSecurityRootPair?)null) { }
public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderRecordTuple? order_tuple)
: this(fill.val, fill.sec, order_tuple.HasValue ? new(order_tuple.Value) : null) { }
public AlgoData? algo =>
_order_tuple.HasValue ? _order_tuple.Value.order.algo : (AlgoData?)null;
@@ -41,7 +44,7 @@ namespace mbts.spark {
public AlgoDefinitionMetadata? root_algo_meta =>
_order_tuple.HasValue ? _order_tuple.Value.root.meta : null;
public OrderSecurityAlgo? root_order_security => _order_tuple?.root;
public OrderRecordTuple? root_order_security => _order_tuple?.root;
public AccountTuple account_tuple => new(account_id, account);
@@ -36,12 +36,11 @@ namespace bts.spark {
static readonly IEqualityComparer<OrderRecordImmutable> _id_comparer =
bts.utils.EqualityComparer.Create<OrderRecordImmutable, uint>(a => a.Key);
public OrderActivitySummarizer(IBus bus, IObservable<TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint>> orders) {
public OrderActivitySummarizer(IBus bus, IObservable<TableUpdate<OrderRecordTuple, uint>> orders) {
_bus = bus;
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec => _security = sec),
orders.Subscribe(orders_updated)
);
orders.Subscribe(orders_updated));
}
public void Dispose() => Disposable.dispose(ref _dispose);
@@ -143,12 +142,12 @@ namespace bts.spark {
#endregion
void orders_updated(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) {
void orders_updated(TableUpdate<OrderRecordTuple, uint> update) {
foreach (var o in update.added) {
if (!string.IsNullOrEmpty(o.order.State.LastMsg) && o.order.State.Created.ToDateTime().Date == DateTime.Today) {
if (o.sec.HasValue) {
log_status(ActivityLogCategory.warn, o.sec.Value, o.order.State.LastMsg);
if (o.security.HasValue) {
log_status(ActivityLogCategory.warn, o.security.Value, o.order.State.LastMsg);
}
}
}
@@ -156,7 +155,7 @@ namespace bts.spark {
foreach (var order in update.changes) {
var neworder = order.New.order;
var oldorder = order.Old.order;
var security = order.New.sec ?? order.Old.sec;
var security = order.New.security ?? order.Old.security;
//
// description
var mod_desc = modified_description(oldorder, neworder, security?.ContractSpec);
@@ -32,10 +32,10 @@ namespace mbts.spark {
readonly CommonValueMonitor<double> _size_mon = new();
readonly CommonValueMonitor<AccountTuple> _account_mon = new CommonValueMonitor<AccountTuple>();
readonly CommonValueMonitor<bool> _all_active_mon = new CommonValueMonitor<bool>();
readonly CommonValueMonitorMultiplexor<OrderSecurityAlgo> _group_mon = new CommonValueMonitorMultiplexor<OrderSecurityAlgo>();
readonly Func<uint, OrderSecurityAlgo?> _lookup_order;
readonly CommonValueMonitorMultiplexor<OrderRecordTuple> _group_mon = new();
readonly Func<uint, OrderRecordTuple?> _lookup_order;
public OrderParamsAggregator(TimeSpan throttle, Func<uint, OrderSecurityAlgo?> lookup_order) {
public OrderParamsAggregator(TimeSpan throttle, Func<uint, OrderRecordTuple?> lookup_order) {
_throttle = throttle;
_lookup_order = lookup_order;
_group_mon.add_member_mon(_algo_def_mon, _build_algo_tree);
@@ -88,21 +88,21 @@ namespace mbts.spark {
public IDisposable defer_updates() =>
_group_mon.defer_updates();
public void Add(OrderSecurityAlgo order_tuple) =>
public void Add(OrderRecordTuple order_tuple) =>
_group_mon.add(order_tuple);
public void Remove(OrderSecurityAlgo order_tuple) =>
public void Remove(OrderRecordTuple order_tuple) =>
_group_mon.remove(order_tuple);
public void Clear() =>
_group_mon.clear();
static SecurityImmutable? _get_spreader_sec(OrderSecurityAlgo osam) =>
static SecurityImmutable? _get_spreader_sec(OrderRecordTuple osam) =>
OrderDataHelper.enumerate_algo_hierarchy(osam.order.Def.CustomDef.CloneToMutable())
.Any(algo => algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Spreader) ?
osam.security : null;
CustomOrderDefinitionImmutable _build_algo_tree(OrderSecurityAlgo root) =>
CustomOrderDefinitionImmutable _build_algo_tree(OrderRecordTuple root) =>
root.order.Def.AttachTargetOrderKey == 0 ?
root.order.Def.CustomDef :
new CustomOrderDefinitionImmutable(_add_attached_targets(root.order.Def.CustomDef.CloneToMutable(), root.order.Key, root.order.Def.AttachTargetOrderKey));
@@ -124,7 +124,7 @@ namespace mbts.spark {
return mroot;
}
Stack<OrderSecurityAlgo> _lineage(uint root, uint target) {
Stack<OrderRecordTuple> _lineage(uint root, uint target) {
// check args/preconditions
if (root == 0) throw new ArgumentException("Cannot be zero.", nameof(root));
if (target == 0) throw new ArgumentException("Cannot be zero.", nameof(target));
@@ -138,8 +138,8 @@ namespace mbts.spark {
// **If the lineage is disjointed, and we never reach the root, return null**
var ival = inner.Value;
var lin_stack = ival.order.attached_target_order_key() != 0 ?
_lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack<OrderSecurityAlgo>() :
new Stack<OrderSecurityAlgo>();
_lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack<OrderRecordTuple>() :
new Stack<OrderRecordTuple>();
lin_stack.Push(ival);
target = ival.order.ParentKey;
while (target != root) {
+9
View File
@@ -39,6 +39,9 @@ namespace bts.api.orderman {
public AlgoData? algo { get; }
public AlgoDefinitionMetadata? meta { get; }
public OrderRecordTuple to_record_tuple() =>
new(order, security, piq, algo, meta);
public bool Equals(OrderSecurity other) =>
order == other.order &&
security == other.security &&
@@ -88,6 +91,9 @@ namespace bts.api.orderman {
public string display_name() =>
order.display_name(algo, security);
public OrderRecordTuple to_record_tuple() =>
new(order, security, piq, algo, meta);
public bool Equals(OrderSecurityAlgo other) =>
order == other.order &&
piq == other.piq &&
@@ -134,6 +140,9 @@ namespace bts.api.orderman {
OrderSecurityAlgo.from_order_security(order),
OrderSecurityAlgo.from_order_security(root));
public OrderRecordTupleWithRoot to_record_tuple() =>
new(order.to_record_tuple(), _root?.to_record_tuple());
public bool Equals(OrderSecurityRootPair other) =>
order == other.order &&
_root == other._root;
+23 -48
View File
@@ -34,8 +34,8 @@
using System.Reactive.Linq;
using System.Threading.Tasks;
using OrderUpdate = bts.api.core.TableUpdate<(bts.api.SecurityImmutable? sec, bts.api.orderman.OrderRecordImmutable order), uint>;
using OrderUpdatePiq = bts.api.core.TableUpdate<bts.api.orderman.OrderSecurity, uint>;
using OrderUpdate = bts.api.core.TableUpdate<Spark.Api.Orders.OrderRecordTuple, uint>;
using OrderUpdatePiq = bts.api.core.TableUpdate<Spark.Api.Orders.OrderRecordTuple, uint>;
[Export]
class OrdersModel : IDisposable {
@@ -53,7 +53,7 @@
readonly ErrorReporter _error;
readonly OrderActivitySummarizer _activity;
readonly TableUpdateDemuxer<OrderRecordImmutable, uint, uint> _security_orders_demuxer;
readonly TableUpdateDemuxer<OrderSecurity, uint, uint> _security_working_orders_with_piq_demuxer;
readonly TableUpdateDemuxer<OrderRecordTuple, uint, uint> _security_working_orders_with_piq_demuxer;
readonly OrderDataSource _data_source;
/// <see cref="_securities"/> is updated atomically from multiple threads (use a local copy to
@@ -98,12 +98,13 @@
on_order_securities =
on_orders
.as_iincremental()
.filter(t => t.sec.HasValue)
.Select(t => t.sec.Value);
.filter(t => t.security.HasValue)
.Select(t => t.security.Value);
_activity = new OrderActivitySummarizer(bus, on_orders);
_security_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_working_orders_with_piq_demuxer = new TableUpdateDemuxer<OrderSecurity, uint, uint>(o => o.order.Key, o => o.order.security_key());
_security_working_orders_with_piq_demuxer = new(
o => o.order.Key, o => o.order.security_key());
studio_algos_with_meta = algo_model.definitions.LeftJoin<AlgoData, AlgoDefinitionMetadata, (AlgoData algo, AlgoDefinitionMetadata? meta), AlgoKey>(
algo_model.metadata_service.subscribe_metadata().Table(m => m.id),
d => d.key,
@@ -118,21 +119,17 @@
t => t.order.Key,
am => am.algo.key,
t => AlgoKey.from_composite_key(t.order.algo_template_key()),
(os, okey, am, mkey) => new OrderSecurity(os.sec, os.order, null, am.algo, am.meta),
(os, okey, mkey) => new OrderSecurity(os.sec, os.order, null, null, null),
(os, okey, am, mkey) => new OrderRecordTuple(os.order, os.security, null, am.algo, am.meta),
(os, okey, mkey) => new OrderRecordTuple(os.order, os.security, null, null, null),
ot => ot.order.Key)
.Cache();
on_order_tuples_with_piq = on_order_tuples.LeftJoin<
OrderSecurity,
OrderPIQImmutable,
OrderSecurity,
uint>(
on_order_tuples_with_piq = on_order_tuples.LeftJoin(
mbo_service.subscribei_piq().Table(),
o => o.order.Key,
piq => piq.OrderId,
(osam, _, p) => new OrderSecurity(osam.security, osam.order, p.Position, osam.algo, osam.meta),
(osam, _) => new OrderSecurity(osam.security, osam.order, null, osam.algo, osam.meta),
(osam, _, p) => new OrderRecordTuple(osam.order, osam.security, p.Position, osam.algo, osam.meta),
(osam, _) => new OrderRecordTuple(osam.order, osam.security, null, osam.algo, osam.meta),
osp => osp.order.Key
).Cache();
@@ -140,16 +137,16 @@
on_order_tuples_with_root = on_order_tuples.RootDependent(
o => o.order.Key,
o => o.order.ParentKey,
OrderSecurityRootPair.from_order_security,
OrderSecurityRootPair.from_order_security,
(o, r) => new OrderRecordTupleWithRoot(o, r),
o => new OrderRecordTupleWithRoot(o),
o => o.root.order.Key)
.Cache();
// order tuples with root and piq
on_order_tuples_with_root_and_piq = on_order_tuples_with_piq.RootDependent(
o => o.order.Key,
o => o.order.ParentKey,
OrderSecurityRootPair.from_order_security,
OrderSecurityRootPair.from_order_security,
(o, r) => new OrderRecordTupleWithRoot(o, r),
o => new OrderRecordTupleWithRoot(o),
o => o.root.order.Key)
.Cache();
@@ -252,9 +249,9 @@
public SpreaderModel spreader => _spreader;
public IObservable<OrderUpdate> on_orders => _data_source.orders;
public IObservable<OrderUpdatePiq> on_order_tuples_with_piq { get; }
public IObservable<TableUpdate<OrderSecurity, uint>> on_order_tuples { get; }
public IObservable<TableUpdate<OrderSecurityRootPair, uint>> on_order_tuples_with_root { get; }
public IObservable<TableUpdate<OrderSecurityRootPair, uint>> on_order_tuples_with_root_and_piq { get; }
public IObservable<TableUpdate<OrderRecordTuple, uint>> on_order_tuples { get; }
public IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> on_order_tuples_with_root { get; }
public IObservable<TableUpdate<OrderRecordTupleWithRoot, uint>> on_order_tuples_with_root_and_piq { get; }
public IObservable<TableUpdate<KeyValuePair<uint, bool>, uint>> on_orders_can_detach { get; }
public IObservable<TableUpdate<KeyValuePair<uint, bool>, uint>> on_orders_can_attach { get; }
public IObservable<IIncrementalUpdate<SecurityImmutable, uint>> on_order_securities { get; }
@@ -264,7 +261,7 @@
public IObservable<TableUpdate<(AlgoData algo, AlgoDefinitionMetadata? meta), AlgoKey>> studio_algos_with_meta { get; }
public IObservable<TableUpdate<(SecurityImmutable?, ManualFillImmutable), int>> on_manual_fills_securities { get; }
public IObservable<TableUpdate<ManualFillTuple, int>> on_manual_fill_tuples { get; }
public IObservable<TableUpdate<TableUpdateGrouping<OrderSecurity, uint, uint>, uint>> security_orders => _data_source.security_orders;
public IObservable<TableUpdate<TableUpdateGrouping<OrderRecordTuple, uint, uint>, uint>> security_orders => _data_source.security_orders;
public AdminModel admin_model { get; }
public MBOService mbo_service => _mbo_service;
@@ -273,7 +270,7 @@
public AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security) =>
_algo_provider.get_permitted_algos(security);
public IObservable<TableUpdate<OrderSecurity, uint>> on_security_working_orders_with_piq(uint security) =>
public IObservable<TableUpdate<OrderRecordTuple, uint>> on_security_working_orders_with_piq(uint security) =>
_security_working_orders_with_piq_demuxer.subscribe(security);
public IObservable<TableUpdate<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
@@ -471,30 +468,8 @@
public void Dispose() =>
Disposable.dispose(ref _dispose);
static ImmutableDictionary<uint, OrderSecurity> _update_working_orders(ImmutableDictionary<uint, OrderSecurity> target, OrderUpdate table) {
var clone = target.ToBuilder();
foreach (var o in table.removed) {
if (o.order.is_active()) {
clone.Remove(o.order.Key);
}
}
foreach (var o in table.changes) {
if (o.Old.order.is_active()) {
clone.Remove(o.Old.order.Key);
}
if (o.New.order.is_active()) {
clone.Add(o.New.order.Key, o.New);
}
}
foreach (var o in table.added) {
if (o.order.is_active()) {
clone.Add(o.order.Key, o);
}
}
return clone.ToImmutableDictionary();
}
static ImmutableDictionary<uint, OrderSecurity> _update_working_orders(ImmutableDictionary<uint, OrderSecurity> target, OrderUpdatePiq table) {
static ImmutableDictionary<uint, OrderRecordTuple> _update_working_orders(
ImmutableDictionary<uint, OrderRecordTuple> target, OrderUpdate table) {
var clone = target.ToBuilder();
foreach (var o in table.removed) {
if (o.order.is_active()) {
@@ -8,6 +8,8 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Api.Orders;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -47,13 +49,13 @@ namespace mbts {
}
}
public IPredicate<OrderSecurity> create(object obj) =>
public IPredicate<OrderRecordTuple> create(object obj) =>
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) =>
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Canceled, security, data_cache);
public INotificationPredicate<OrderSecurity> create_toast(INotificationServiceDataCache data_cache) =>
public INotificationPredicate<OrderRecordTuple> create_toast(INotificationServiceDataCache data_cache) =>
new MyToaster(security?.create(), data_cache);
public bool Equals(OrderCanceledEventPredicate other) => other != null && other.security.safe_equals(other.security);
@@ -63,7 +65,7 @@ namespace mbts {
static bool _is_canceled(OrderRecordImmutable o) =>
o.HasState && o.State.Status == OrderStatus.Canceled;
class MyToaster : INotificationPredicate<OrderSecurity>, IEquatable<MyToaster> {
class MyToaster : INotificationPredicate<OrderRecordTuple>, IEquatable<MyToaster> {
readonly IPredicate<SecurityImmutable?> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
@@ -72,13 +74,13 @@ namespace mbts {
_data_cache = data_cache;
}
public IToastNotification trigger(OrderSecurity order) =>
public IToastNotification trigger(OrderRecordTuple order) =>
OrderEventPredicateHelper.check_order_transition_trigger(order, _is_canceled, _security_predicate, _data_cache, out var oldval) ?
ToastNotifications.order_status_changed(order.order.Key,
OrderEventPredicateHelper.get_nullable_status(oldval), OrderStatus.Canceled, order.security) :
ToastNotifications.empty;
bool IPredicate<OrderSecurity>.trigger(OrderSecurity order) =>
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_canceled, _security_predicate, _data_cache);
public bool Equals(MyToaster other) =>
@@ -8,6 +8,7 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Api.Orders;
using Spark.Core.Data;
using System;
@@ -52,13 +53,13 @@ namespace mbts {
}
}
public IPredicate<OrderSecurity> create(object obj) =>
public IPredicate<OrderRecordTuple> create(object obj) =>
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) =>
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Completed, security, data_cache);
public INotificationPredicate<OrderSecurity> create_toast(
public INotificationPredicate<OrderRecordTuple> create_toast(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) =>
new MyToaster(security?.create(), data_cache, sec_meta_store);
@@ -69,7 +70,7 @@ namespace mbts {
static bool _is_completed(OrderRecordImmutable o) =>
o.HasState && o.State.Status == OrderStatus.Completed;
class MyToaster : INotificationPredicate<OrderSecurity>, IEquatable<MyToaster> {
class MyToaster : INotificationPredicate<OrderRecordTuple>, IEquatable<MyToaster> {
readonly IPredicate<SecurityImmutable?> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
readonly ISecurityMetadataStore _sec_meta_store;
@@ -83,7 +84,7 @@ namespace mbts {
_sec_meta_store = sec_meta_store;
}
public IToastNotification trigger(OrderSecurity order) {
public IToastNotification trigger(OrderRecordTuple order) {
if (!OrderEventPredicateHelper.check_order_transition_predicate(
order, _is_completed, _security_predicate, _data_cache)) {
return ToastNotifications.empty;
@@ -95,7 +96,7 @@ namespace mbts {
return ToastNotifications.order_completed(order, qty_display);
}
bool IPredicate<OrderSecurity>.trigger(OrderSecurity order) =>
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache);
public bool Equals(MyToaster other) =>
@@ -3,6 +3,8 @@ using bts.api.orderman;
using bts.shell;
using bts.utils;
using Spark.Api.Orders;
using System;
namespace mbts {
@@ -10,13 +12,23 @@ namespace mbts {
/// <summary>
/// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.'
/// </summary>
public static bool check_order_transition_predicate(OrderSecurity order, Func<OrderRecordImmutable, bool> order_predicate_core, IPredicate<SecurityImmutable?> security_predicate, INotificationServiceDataCache data_cache) =>
public static bool check_order_transition_predicate(
OrderRecordTuple order,
Func<OrderRecordImmutable, bool> order_predicate_core,
IPredicate<SecurityImmutable?> security_predicate,
INotificationServiceDataCache data_cache) =>
check_order_transition_trigger(order, order_predicate_core, security_predicate, data_cache, out var _);
/// <summary>
/// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.' Oldval will be null if the order did not previously exist, or does not currently pass the predicate.
/// </summary>
public static bool check_order_transition_trigger(OrderSecurity order, Func<OrderRecordImmutable, bool> order_predicate_core, IPredicate<SecurityImmutable?> security_predicate, INotificationServiceDataCache data_cache, out OrderSecurity? oldval) {
public static bool check_order_transition_trigger(
OrderRecordTuple order,
Func<OrderRecordImmutable, bool> order_predicate_core,
IPredicate<SecurityImmutable?> security_predicate,
INotificationServiceDataCache data_cache,
out OrderRecordTuple? oldval
) {
if (check_security_predicate(order, security_predicate) && order_predicate_core(order.order)) {
oldval = data_cache.get_previous_order_state(order.order.Key);
return oldval == null ? !data_cache.is_first_order_update : !order_predicate_core(oldval.Value.order);
@@ -28,19 +40,23 @@ namespace mbts {
/// <summary>
/// Checks if the 'security predicate is null,' or 'it is not null, and the order has a non-null security which passes.'
/// </summary>
public static bool check_security_predicate(OrderSecurity order, IPredicate<SecurityImmutable?> security_predicate) =>
public static bool check_security_predicate(
OrderRecordTuple order, IPredicate<SecurityImmutable?> security_predicate) =>
security_predicate == null || (order.security.HasValue && security_predicate.trigger(order.security.Value));
public static OrderStatus? get_nullable_status(OrderSecurity? order) {
public static OrderStatus? get_nullable_status(OrderRecordTuple? order) {
if (order?.order.HasState == true)
return order?.order.State.Status;
return null;
}
public static IPredicate<OrderSecurity> create_status_transition_predicate(OrderStatus status, SecurityPredicate security_predicate, INotificationServiceDataCache data_cache) =>
public static IPredicate<OrderRecordTuple> create_status_transition_predicate(
OrderStatus status,
SecurityPredicate security_predicate,
INotificationServiceDataCache data_cache) =>
new OrderStatusTransitionPredicate(status, security_predicate?.create(), data_cache);
class OrderStatusTransitionPredicate : IPredicate<OrderSecurity>, IEquatable<OrderStatusTransitionPredicate> {
class OrderStatusTransitionPredicate : IPredicate<OrderRecordTuple>, IEquatable<OrderStatusTransitionPredicate> {
readonly IPredicate<SecurityImmutable?> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
readonly OrderStatus _status;
@@ -51,7 +67,7 @@ namespace mbts {
_data_cache = data_cache;
}
public bool trigger(OrderSecurity value) =>
public bool trigger(OrderRecordTuple value) =>
check_order_transition_predicate(value, o => o.HasState && o.State.Status == _status, _security_predicate, _data_cache);
public bool Equals(OrderStatusTransitionPredicate other) =>
@@ -14,8 +14,6 @@
using System;
using System.Collections.Generic;
using OrderSecurity = bts.api.orderman.OrderSecurity;
static class OrderFilledEventPredicateVMFactory {
public static Dictionary<OrderFilledEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderFilledEventPredicate>> get_oneofs(IBus bus) =>
new Dictionary<OrderFilledEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderFilledEventPredicate>> {
@@ -53,13 +51,13 @@
}
}
public IPredicate<OrderSecurity> create(object obj) =>
public IPredicate<OrderRecordTuple> create(object obj) =>
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache notification_service_data_cache) =>
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache notification_service_data_cache) =>
new FillTrigger(_create_model(notification_service_data_cache));
public INotificationPredicate<OrderSecurity> create_toast(INotificationServiceDataCache notification_service_data_cache) =>
public INotificationPredicate<OrderRecordTuple> create_toast(INotificationServiceDataCache notification_service_data_cache) =>
new FillToastNotificationTrigger(_create_model(notification_service_data_cache));
public bool Equals(OrderFilledEventPredicate other) => other != null && other.security.safe_equals(other.security);
@@ -79,7 +77,7 @@
}
// Please review carfully
public (OrderSecurity oldval, OrderSecurity newval)? get_filled_order_args(OrderSecurity ort) {
public (OrderRecordTuple oldval, OrderRecordTuple newval)? get_filled_order_args(OrderRecordTuple ort) {
if (ort.order.is_exchange_order() && OrderEventPredicateHelper.check_security_predicate(ort, _security_predicate)) {
if (_data_cache.get_previous_order_state(ort.order.Key) is var oldval && oldval.HasValue) {
if (ort.order.filled_quantity() > oldval?.order.filled_quantity()) {
@@ -89,25 +87,25 @@
// old order will be a copy of new order, except with filledQuantity set to 0
var old_state = ort.order.State.CloneToMutable();
old_state.FilledQuantity = 0;
return (new OrderSecurity(ort.security, ort.order.with(state: old_state), ort.piq), ort);
return (new(ort.order.with(state: old_state), ort.security, ort.piq), ort);
}
}
return null;
}
}
class FillTrigger : IPredicate<OrderSecurity> {
class FillTrigger : IPredicate<OrderRecordTuple> {
protected readonly FillTriggerModel _model;
public FillTrigger(FillTriggerModel model) => _model = model;
public bool trigger(OrderSecurity order) => _model.get_filled_order_args(order).HasValue;
public bool trigger(OrderRecordTuple order) => _model.get_filled_order_args(order).HasValue;
}
class FillToastNotificationTrigger : FillTrigger, INotificationPredicate<OrderSecurity> {
class FillToastNotificationTrigger : FillTrigger, INotificationPredicate<OrderRecordTuple> {
public FillToastNotificationTrigger(FillTriggerModel model) : base(model) { }
public new IToastNotification trigger(OrderSecurity value) {
public new IToastNotification trigger(OrderRecordTuple value) {
var args = _model.get_filled_order_args(value);
if (args.HasValue) {
return ToastNotifications.order_filled(args.Value.oldval, args.Value.newval);
@@ -15,8 +15,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using OrderSecurity = bts.api.orderman.OrderSecurity;
static class OrderSentEventPredicateVMFactory {
public static Dictionary<OrderSentEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderSentEventPredicate>> get_oneofs(IBus bus) =>
new Dictionary<OrderSentEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderSentEventPredicate>> {
@@ -56,12 +54,12 @@
}
}
public IPredicate<OrderSecurity> create(object obj) =>
public IPredicate<OrderRecordTuple> create(object obj) =>
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) {
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) {
var sec_pred = security?.create();
return PredicateBuilder.create<OrderSecurity>(os =>
return PredicateBuilder.create<OrderRecordTuple>(os =>
// verify security
(sec_pred == null || (os.security.HasValue && sec_pred.trigger(os.security.Value))) &&
// verify not stale
@@ -72,7 +70,7 @@
(data_cache.order_history.TryGetValue(os.order.Key, out var hist) && hist.Count == 1));
}
public INotificationPredicate<OrderSecurity> create_toast(INotificationServiceDataCache data_cache) =>
public INotificationPredicate<OrderRecordTuple> create_toast(INotificationServiceDataCache data_cache) =>
throw new NotImplementedException();
public bool Equals(OrderSentEventPredicate other) =>
@@ -15,7 +15,6 @@ using Spark.Core.Data;
using System;
using System.Collections.Generic;
using OrderSecurity = bts.api.orderman.OrderSecurity;
using PTOC = mbts.OrderRecordTuplePredicate.PredicateTypeOneofCase;
namespace mbts {
@@ -225,7 +224,7 @@ namespace mbts {
}
}
public IPredicate<OrderSecurity> create_predicate(
public IPredicate<OrderRecordTuple> create_predicate(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) {
switch (predicate_type_case) {
case PTOC.Security: return wrap(_security.create(), r => r.security);
@@ -256,11 +255,11 @@ namespace mbts {
default: return null;
}
//
IPredicate<OrderSecurity> wrap<T>(IPredicate<T> trigger, Func<OrderSecurity, T> select) =>
trigger.wrap<OrderSecurity, T>(select);
IPredicate<OrderRecordTuple> wrap<T>(IPredicate<T> trigger, Func<OrderRecordTuple, T> select) =>
trigger.wrap<OrderRecordTuple, T>(select);
}
public INotificationPredicate<OrderSecurity> create_notification_predicate(
public INotificationPredicate<OrderRecordTuple> create_notification_predicate(
INotificationServiceDataCache notification_service_data_cache,
ISecurityMetadataStore sec_meta_store) {
if (!is_toast_enabled)
@@ -381,7 +380,7 @@ namespace mbts {
}
[ProtoContract]
class OrderRecordTuplePredicateAnimations : IPredicateAnimationsData<OrderSecurity, OrderRecordTuplePredicate> {
class OrderRecordTuplePredicateAnimations : IPredicateAnimationsData<OrderRecordTuple, OrderRecordTuplePredicate> {
[ProtoMember(1)]
OrderRecordTuplePredicate _predicate;
[ProtoMember(2)]
@@ -2,20 +2,39 @@
namespace Spark.Api.Orders {
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.spark;
using System;
public readonly struct OrderRecordTuple : IEquatable<OrderRecordTuple> {
public OrderRecordTuple(OrderRecordImmutable order, SecurityImmutable? security = null) {
public OrderRecordTuple(
OrderRecordImmutable order,
SecurityImmutable? security = null,
uint? piq = null,
AlgoData? algo = null,
AlgoDefinitionMetadata? algo_meta = null
) {
this.order = order;
this.security = security;
this.piq = piq;
this.algo = algo;
this.meta = algo_meta;
}
public OrderRecordImmutable order { get; }
public SecurityImmutable? security { get; }
public uint? piq { get; }
public AlgoData? algo { get; }
public AlgoDefinitionMetadata? meta { get; }
public CustomOrderDefinition.CustomOneofCase algo_type =>
(algo?.value)?.CustomCase ?? order.order_type();
public string? algo_name => algo?.name;
public uint key => order.Key;
public uint account_id => order.account_id();
public string account_name => order.account();
public uint security_id => order.security_key();
public bool Equals(OrderRecordTuple other) =>
@@ -34,4 +53,35 @@ namespace Spark.Api.Orders {
public static bool operator !=(OrderRecordTuple left, OrderRecordTuple right) =>
!(left == right);
}
public readonly struct OrderRecordTupleWithRoot : IEquatable<OrderRecordTupleWithRoot> {
readonly OrderRecordTuple? _root;
public OrderRecordTupleWithRoot(OrderRecordTuple order, OrderRecordTuple? root = null) {
this.order = order;
_root = root;
}
public OrderRecordTuple order { get; }
public OrderRecordTuple root => _root ?? order;
public uint key => order.key;
public uint security_id => order.security_id;
public bool Equals(OrderRecordTupleWithRoot other) =>
order.Equals(other.order) &&
EqualityComparer.nullable_equals(_root, other._root);
public override bool Equals(object? obj) =>
obj is OrderRecordTupleWithRoot other && Equals(other);
public override int GetHashCode() =>
HashCode.Combine(order, _root);
public static bool operator ==(OrderRecordTupleWithRoot left, OrderRecordTupleWithRoot right) =>
left.Equals(right);
public static bool operator !=(OrderRecordTupleWithRoot left, OrderRecordTupleWithRoot right) =>
!(left == right);
}
}
@@ -196,6 +196,10 @@ namespace Spark.Api.Orders {
public static bool can_detach(this OrderRecordImmutable order) =>
order.attached_target_order_key() == 0 && order.has_parent();
public static string display_name(this OrderRecordTuple order) =>
order.order.display_name(order.algo, order.security);
public static string display_name(
this OrderRecordImmutable order, AlgoData? algo, SecurityImmutable? security = null) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader && security.HasValue)