SPARK-1791 / SPARK-1792 Improve OB performance

This commit is contained in:
John Colvin committed 2018-10-21 18:20:53 -05:00
1 parent ba9bd53c1e
commit 5218b748e8
12 files changed
+878 -1033

No files matched your search

@@ -1,168 +1,168 @@
using bts.utils;
using mbts.ui;
using mbts.ui.controls;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
//using bts.utils;
//using mbts.ui;
//using mbts.ui.controls;
//using mbts.utils;
//using System;
//using System.Collections.Generic;
//using System.Collections.ObjectModel;
//using System.ComponentModel;
namespace mbts.spark {
partial class OrderBookRowVM {
public interface IOrderBookCell : DIYGrid.IGridCell, IComparable { }
//namespace mbts.spark {
// partial class OrderBookRowVM {
// public interface IOrderBookCell : DIYGrid.IGridCell, IComparable { }
public interface IOrderBookCell<T> : IOrderBookCell {
T value { get; }
IOrderBookCellStore<T> store { get; }
}
// public interface IOrderBookCell<T> : IOrderBookCell {
// T value { get; }
// IOrderBookCellStore<T> store { get; }
// }
public interface IOrderBookCellStore : DIYGrid.IGridCellStore {
OrderBookRowVM row { get; }
new ICVOrderBookColumn column { get; }
string prop_name { get; }
new IOrderBookCell current { get; }
//
IOrderBookCellStore select_other(OrderBookRowVM row);
}
// public interface IOrderBookCellStore : DIYGrid.IGridCellStore {
// OrderBookRowVM row { get; }
// new ICVOrderBookColumn column { get; }
// string prop_name { get; }
// new IOrderBookCell current { get; }
// //
// IOrderBookCellStore select_other(OrderBookRowVM row);
// }
public interface IOrderBookCellStore<T> : IOrderBookCellStore, IComparer<T>, IEqualityComparer<T> {
new IOrderBookCell<T> current { get; }
new IOrderBookCellStore<T> select_other(OrderBookRowVM row);
//
T get_value(OrderBookRowVM row);
string format(T value);
}
// public interface IOrderBookCellStore<T> : IOrderBookCellStore, IComparer<T>, IEqualityComparer<T> {
// new IOrderBookCell<T> current { get; }
// new IOrderBookCellStore<T> select_other(OrderBookRowVM row);
// //
// T get_value(OrderBookRowVM row);
// string format(T value);
// }
public static class CellFactory {
public static IOrderBookCellStore<T> create<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other, Func<T, string> format = null) =>
new OrderBookCellStore<T>(row, column, prop_name, get_value, select_other, format, new Comparison<T>(Comparer<T>.Default.Compare), EqualityComparer<T>.Default);
// public static class CellFactory {
// public static IOrderBookCellStore<T> create<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other, Func<T, string> format = null) =>
// new OrderBookCellStore<T>(row, column, prop_name, get_value, select_other, format, new Comparison<T>(Comparer<T>.Default.Compare), EqualityComparer<T>.Default);
public static IOrderBookCellStore<T> create<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other, Comparison<T> comparison, Func<T, string> format = null) =>
new OrderBookCellStore<T>(row, column, prop_name, get_value, select_other, format, comparison, EqualityComparer<T>.Default);
// public static IOrderBookCellStore<T> create<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other, Comparison<T> comparison, Func<T, string> format = null) =>
// new OrderBookCellStore<T>(row, column, prop_name, get_value, select_other, format, comparison, EqualityComparer<T>.Default);
public static IOrderBookCellStore<T?> create_nullable<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T?> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T?>> select_other, Func<T?, string> format = null)
where T : struct => new OrderBookCellStore<T?>(row, column, prop_name, get_value, select_other, format, CompareUtils.nullable_comparison<T>(Comparer<T>.Default.Compare), EqualityComparer.CreateNullable<T>(EqualityComparer<T>.Default.Equals));
// public static IOrderBookCellStore<T?> create_nullable<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T?> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T?>> select_other, Func<T?, string> format = null)
// where T : struct => new OrderBookCellStore<T?>(row, column, prop_name, get_value, select_other, format, CompareUtils.nullable_comparison<T>(Comparer<T>.Default.Compare), EqualityComparer.CreateNullable<T>(EqualityComparer<T>.Default.Equals));
public static IOrderBookCellStore<T?> create_nullable<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T?> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T?>> select_other, Func<T, T, int> compare, Func<T?, string> format = null)
where T : struct =>
new OrderBookCellStore<T?>(row, column, prop_name, get_value, select_other, format, CompareUtils.nullable_comparison(compare), EqualityComparer.CreateNullable<T>(EqualityComparer<T>.Default.Equals));
// public static IOrderBookCellStore<T?> create_nullable<T>(OrderBookRowVM row, ICVOrderBookColumn column, string prop_name, Func<OrderBookRowVM, T?> get_value, Func<OrderBookRowVM, IOrderBookCellStore<T?>> select_other, Func<T, T, int> compare, Func<T?, string> format = null)
// where T : struct =>
// new OrderBookCellStore<T?>(row, column, prop_name, get_value, select_other, format, CompareUtils.nullable_comparison(compare), EqualityComparer.CreateNullable<T>(EqualityComparer<T>.Default.Equals));
class OrderBookCellStore<T> : IOrderBookCellStore<T>, INotifyPropertyChanged {
readonly OrderBookRowVM _row;
readonly ICVOrderBookColumn _column;
readonly string _prop_name;
readonly Func<OrderBookRowVM, T> _get_value;
readonly Func<OrderBookRowVM, IOrderBookCellStore<T>> _select_other;
readonly Func<T, string> _format;
readonly Comparison<T> _comparison;
readonly IEqualityComparer<T> _eq_comparer;
OrderBookCell<T> _current;
// class OrderBookCellStore<T> : IOrderBookCellStore<T>, INotifyPropertyChanged {
// readonly OrderBookRowVM _row;
// readonly ICVOrderBookColumn _column;
// readonly string _prop_name;
// readonly Func<OrderBookRowVM, T> _get_value;
// readonly Func<OrderBookRowVM, IOrderBookCellStore<T>> _select_other;
// readonly Func<T, string> _format;
// readonly Comparison<T> _comparison;
// readonly IEqualityComparer<T> _eq_comparer;
// OrderBookCell<T> _current;
// Property changed handler to avoid WPF binding leak
// https://blog.jetbrains.com/dotnet/2014/09/04/fighting-common-wpf-memory-leaks-with-dotmemory/
public event PropertyChangedEventHandler PropertyChanged = (_,__) => { };
// // Property changed handler to avoid WPF binding leak
// // https://blog.jetbrains.com/dotnet/2014/09/04/fighting-common-wpf-memory-leaks-with-dotmemory/
// public event PropertyChangedEventHandler PropertyChanged = (_,__) => { };
public OrderBookCellStore(
OrderBookRowVM row,
ICVOrderBookColumn column,
string prop_name,
Func<OrderBookRowVM, T> get_value,
Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other,
Func<T, string> format,
Comparison<T> comparison,
IEqualityComparer<T> eq_comparer) {
//
_row = row;
_column = column;
_prop_name = prop_name;
_get_value = get_value;
_select_other = select_other;
_format = format ?? new Func<T, string>(v => v?.ToString() ?? string.Empty);
_comparison = comparison;
_eq_comparer = eq_comparer;
_current = new OrderBookCell<T>(this, _get_value(_row));
}
// public OrderBookCellStore(
// OrderBookRowVM row,
// ICVOrderBookColumn column,
// string prop_name,
// Func<OrderBookRowVM, T> get_value,
// Func<OrderBookRowVM, IOrderBookCellStore<T>> select_other,
// Func<T, string> format,
// Comparison<T> comparison,
// IEqualityComparer<T> eq_comparer) {
// //
// _row = row;
// _column = column;
// _prop_name = prop_name;
// _get_value = get_value;
// _select_other = select_other;
// _format = format ?? new Func<T, string>(v => v?.ToString() ?? string.Empty);
// _comparison = comparison;
// _eq_comparer = eq_comparer;
// _current = new OrderBookCell<T>(this, _get_value(_row));
// }
public OrderBookRowVM row => _row;
public ICVOrderBookColumn column => _column;
public string prop_name => _prop_name;
public IOrderBookCell<T> current => _current;
// public OrderBookRowVM row => _row;
// public ICVOrderBookColumn column => _column;
// public string prop_name => _prop_name;
// public IOrderBookCell<T> current => _current;
IOrderBookCell IOrderBookCellStore.current => _current;
DIYGrid.IGridColumn DIYGrid.IGridCellStore.column => _column;
DIYGrid.IGridCell DIYGrid.IGridCellStore.current => _current;
// IOrderBookCell IOrderBookCellStore.current => _current;
// DIYGrid.IGridColumn DIYGrid.IGridCellStore.column => _column;
// DIYGrid.IGridCell DIYGrid.IGridCellStore.current => _current;
public ObservableCollection<CellAnimation> animations { get; } = new ObservableCollection<CellAnimation>();
// public ObservableCollection<CellAnimation> animations { get; } = new ObservableCollection<CellAnimation>();
public int Compare(T x, T y) => _comparison(x, y);
public bool Equals(T x, T y) => _eq_comparer.Equals(x, y);
public string format(T value) => _format(value);
public int GetHashCode(T obj) => _eq_comparer.GetHashCode(obj);
public T get_value(OrderBookRowVM row) => _get_value(row);
public IOrderBookCellStore<T> select_other(OrderBookRowVM row) => _select_other(row);
IOrderBookCellStore IOrderBookCellStore.select_other(OrderBookRowVM row) => select_other(row);
// public int Compare(T x, T y) => _comparison(x, y);
// public bool Equals(T x, T y) => _eq_comparer.Equals(x, y);
// public string format(T value) => _format(value);
// public int GetHashCode(T obj) => _eq_comparer.GetHashCode(obj);
// public T get_value(OrderBookRowVM row) => _get_value(row);
// public IOrderBookCellStore<T> select_other(OrderBookRowVM row) => _select_other(row);
// IOrderBookCellStore IOrderBookCellStore.select_other(OrderBookRowVM row) => select_other(row);
public bool refresh() {
T v = _get_value(_row);
if (!_eq_comparer.Equals(v, _current.value)) {
_current = new OrderBookCell<T>(this, v);
_row.RaisePropertyChanged(_prop_name);
return true;
} else return false;
}
// public bool refresh() {
// T v = _get_value(_row);
// if (!_eq_comparer.Equals(v, _current.value)) {
// _current = new OrderBookCell<T>(this, v);
// _row.RaisePropertyChanged(_prop_name);
// return true;
// } else return false;
// }
public void regenerate_cell() {
_current = new OrderBookCell<T>(this, _current.value);
_row.RaisePropertyChanged(_prop_name);
}
// public void regenerate_cell() {
// _current = new OrderBookCell<T>(this, _current.value);
// _row.RaisePropertyChanged(_prop_name);
// }
public void invalidate_text() => regenerate_cell();
}
// public void invalidate_text() => regenerate_cell();
// }
class OrderBookCell<T> : IOrderBookCell<T> {
string _text;
// class OrderBookCell<T> : IOrderBookCell<T> {
// string _text;
public OrderBookCell(OrderBookCellStore<T> store, T value) {
this.store = store;
this.value = value;
}
// public OrderBookCell(OrderBookCellStore<T> store, T value) {
// this.store = store;
// this.value = value;
// }
public string text => _text ?? (_text = store.format(value));
public T value { get; }
public IOrderBookCellStore<T> store { get; }
// public string text => _text ?? (_text = store.format(value));
// public T value { get; }
// public IOrderBookCellStore<T> store { get; }
public int CompareTo(OrderBookCell<T> other) {
if (other == null)
return 1;
var lin = lineage(store.row);
var olin = lineage(other.store.row);
int c = 0;
using (var en = lin.GetEnumerator())
using (var oen = olin.GetEnumerator()) {
while (en.MoveNext() && oen.MoveNext()) {
if (en.Current.order_key.value != oen.Current.order_key.value) {
c = store.Compare(
store.select_other(en.Current).current.value,
store.select_other(oen.Current).current.value);
if (c != 0)
return c;
else {
c = en.Current.order_key.value.CompareTo(
oen.Current.order_key.value);
return store.column.SortDirection.HasValue && store.column.SortDirection.Value == ListSortDirection.Ascending ? c : -c;
}
}
}
}
return store.column.SortDirection.HasValue && store.column.SortDirection.Value == ListSortDirection.Ascending ?
lin.Count.CompareTo(olin.Count) :
olin.Count.CompareTo(lin.Count);
}
// public int CompareTo(OrderBookCell<T> other) {
// if (other == null)
// return 1;
// var lin = lineage(store.row);
// var olin = lineage(other.store.row);
// int c = 0;
// using (var en = lin.GetEnumerator())
// using (var oen = olin.GetEnumerator()) {
// while (en.MoveNext() && oen.MoveNext()) {
// if (en.Current.order_key.value != oen.Current.order_key.value) {
// c = store.Compare(
// store.select_other(en.Current).current.value,
// store.select_other(oen.Current).current.value);
// if (c != 0)
// return c;
// else {
// c = en.Current.order_key.value.CompareTo(
// oen.Current.order_key.value);
// return store.column.SortDirection.HasValue && store.column.SortDirection.Value == ListSortDirection.Ascending ? c : -c;
// }
// }
// }
// }
// return store.column.SortDirection.HasValue && store.column.SortDirection.Value == ListSortDirection.Ascending ?
// lin.Count.CompareTo(olin.Count) :
// olin.Count.CompareTo(lin.Count);
// }
public int CompareTo(object obj) => CompareTo(obj as OrderBookCell<T>);
// public int CompareTo(object obj) => CompareTo(obj as OrderBookCell<T>);
public override string ToString() => text;
}
}
}
}
// public override string ToString() => text;
// }
// }
// }
//}
@@ -1,4 +1,5 @@
using bts.api;
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.spark.filters;
@@ -6,6 +7,7 @@ using mbts.ui;
using mbts.ui.converters;
using mbts.ui.utility;
using mbts.ui.utility.text;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -18,7 +20,6 @@ using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using static bts.shell.OrderBookWindowFactory;
using static mbts.spark.OrderBookRowVM;
using static mbts.spark.OrderBookView;
using static mbts.ui.controls.DIYGrid;
using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
@@ -35,20 +36,23 @@ namespace mbts.spark {
// TODO: Maybe binding to the SortDirection would be less smelly?
// - initially, I tried to bind to the SortDirection of each column, unfortunately, the binding target was not updated before the ICollectionView sorting took place.
// I decided it was not worth changing the DIYGrid.Sorting function to force the SortDirection binding targets to update immediately, before the ICollectionView sorting.
interface ICVOrderBookColumn : IKeyedColumn<Columns>, IGridColumn<OrderBookRowVM> {
interface ICVOrderBookColumn : IKeyedColumn<Columns>, IGridColumn {
string sort_member_path { get; }
ListSortDirection? SortDirection { get; }
IDataGridColumnFilter<OrderBookRowVM> filter { get; }
ListSortDirection? SortDirection { get; set; }
IDataGridColumnFilter<OrderRecordTuple> filter { get; }
IComparer<OrderBookRowVM> comparer { get; }
}
partial class OrderBookVM {
public class OrderBookColumnCollection : ObservableCollection<ColumnBase>, IValueFactory<FilterStates>, IDisposable {
readonly List<ICVOrderBookColumn> _active_comparers = new List<ICVOrderBookColumn>();
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
// security
Add(security_column = new SecurityColumn(
DiscreteValuesFilterVM.Create<OrderBookRowVM, SecurityImmutable, SecurityCriteria>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, SecurityImmutable, SecurityCriteria>(
order_securities,
r => r.security.value.GetValueOrDefault(SecurityDataHelper.Defaults.SecurityImmutable),
ort => ort.security_md.HasValue ? ort.security_md.Value.security : SecurityDataHelper.Defaults.SecurityImmutable,
SecurityCriteria.from_securities,
SecurityCriteria.get_to_securities(bus),
nameof(OrderBookRowVM.security),
@@ -60,172 +64,222 @@ namespace mbts.spark {
Columns.Symbol,
DefaultColumnHeaders.Symbol,
nameof(OrderBookRowVM.symbol),
r => r.symbol.store,
r => r.symbol,
DefaultColumnWidths.Symbol,
DiscreteValuesFilterVM.Create<OrderBookRowVM, string>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, string>(
mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(),
r => r.symbol.value,
value_path(nameof(OrderBookRowVM.symbol))
ort => ort.security_md.HasValue ? ort.security_md.Value.security.Symbol : string.Empty,
nameof(OrderBookRowVM.symbol)
),
DataGridFilterKnownTemplates.DiscreteValues));
DataGridFilterKnownTemplates.DiscreteValues,
_wrap_comparer(r => r.symbol)));
// time_created
Add(time_created_column = new TimeCreatedColumn(
new TimeFilterVM<OrderBookRowVM>(r => r.time_created.value, value_path(nameof(OrderBookRowVM.time_created)))));
Add(time_created_column = new SimpleTextColumn<TimeFilterTuple>(
Columns.Time,
"Time",
nameof(OrderBookRowVM.time_created),
r => r.time_created_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderRecordTuple>(
ort => ort.order.created(),
nameof(OrderBookRowVM.time_created)),
DataGridFilterKnownTemplates.TimeFilter,
_wrap_comparer(r => r.time_created)));
// last_change
Add(last_change_column = new LastChangeTimeColumn(
new TimeFilterVM<OrderBookRowVM>(r => r.last_change.value, value_path(nameof(OrderBookRowVM.last_change)))));
Add(last_change_column = new SimpleTextColumn<TimeFilterTuple>(
Columns.LastChange,
"Last Change",
nameof(OrderBookRowVM.last_change),
r => r.last_change_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderRecordTuple>(
ort => ort.order.last_change(),
nameof(OrderBookRowVM.last_change)),
DataGridFilterKnownTemplates.TimeFilter,
_wrap_comparer(r => r.last_change)));
// user
Add(user_column = new SimpleTextColumn<string[]>(
Columns.User,
DefaultColumnHeaders.User,
nameof(OrderBookRowVM.user),
r => r.user.store,
r => r.user,
DefaultColumnWidths.User,
DiscreteValuesFilterVM.Create<OrderBookRowVM, string>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, string>(
model.factory.subscribe_users().Select(d => d.Values),
r => r.user.value,
value_path(nameof(OrderBookRowVM.user))),
DataGridFilterKnownTemplates.DiscreteValues));
ort => ort.order.user(),
nameof(OrderBookRowVM.user)),
DataGridFilterKnownTemplates.DiscreteValues,
_wrap_comparer(r => r.user)));
// account
Add(account_column = new SimpleTextColumn<string[]>(
Columns.Account,
DefaultColumnHeaders.Account,
nameof(OrderBookRowVM.account),
r => r.account.store,
r => r.account,
DefaultColumnWidths.Account,
DiscreteValuesFilterVM.Create<OrderBookRowVM, string, string[]>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, string, string[]>(
model.factory.subscribe_accounts().Select(d => d.Values),
r => r.account.value,
ort => ort.order.account(),
vals => vals.ToArray(),
vals => Observable.Return(vals),
value_path(nameof(OrderBookRowVM.account))),
DataGridFilterKnownTemplates.DiscreteValues));
nameof(OrderBookRowVM.account)),
DataGridFilterKnownTemplates.DiscreteValues,
_wrap_comparer(r => r.account)));
// exchange
Add(exchange_column = new SimpleTextColumn<Venue[]>(
Columns.Exchange,
DefaultColumnHeaders.Exchange,
nameof(OrderBookRowVM.exchange),
r => r.exchange.store,
r => r.exchange.ToString(),
DefaultColumnWidths.Exchange,
DiscreteValuesFilterVM.Create<OrderBookRowVM, Venue>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, Venue>(
EnumHelper.get_values_except(Venue.Unset).ToList(),
r => r.exchange.value,
value_path(nameof(OrderBookRowVM.exchange))),
DataGridFilterKnownTemplates.EnumValues));
ort => ort.security_md.HasValue ? ort.security_md.Value.security.Exchange : Venue.Unset,
nameof(OrderBookRowVM.exchange)),
DataGridFilterKnownTemplates.EnumValues,
_wrap_comparer(r => r.exchange)));
// time in force
Add(time_in_force_column = new SimpleTextColumn<TimeInForce[]>(
Columns.TimeInForce,
DefaultColumnHeaders.TimeInForce,
nameof(OrderBookRowVM.time_in_force),
r => r.time_in_force.store,
r => r.time_in_force.ToString(),
DefaultColumnWidths.TimeInForce,
DiscreteValuesFilterVM.Create<OrderBookRowVM, TimeInForce>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, TimeInForce>(
EnumHelper.get_values<TimeInForce>().ToList(),
r => r.time_in_force.value,
value_path(nameof(OrderBookRowVM.time_in_force))),
DataGridFilterKnownTemplates.EnumValues));
ort => ort.order.time_in_force(),
nameof(OrderBookRowVM.time_in_force)),
DataGridFilterKnownTemplates.EnumValues,
_wrap_comparer(r => r.time_in_force)));
// order type
Add(order_type_column = new OrderBookOrderTypeColumn(
DiscreteValuesFilterVM.Create<OrderBookRowVM, OrderType>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, OrderType>(
utilities.OrderFactory.all_order_types,
r => r.order_type.value,
value_path(nameof(OrderBookRowVM.order_type)))));
ort => ort.order.order_type(),
nameof(OrderBookRowVM.order_type))));
// order sub type
Add(sub_type_column = new SimpleTextColumn<OrderSubType[]>(
Columns.SubType,
"Sub Type",
nameof(OrderBookRowVM.order_sub_type),
r => r.order_sub_type.store,
r => r.order_sub_type_text,
80,
DiscreteValuesFilterVM.Create<OrderBookRowVM, OrderSubType>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, OrderSubType>(
EnumHelper.get_values<OrderSubType>().ToList(),
r => r.order_sub_type.value,
value_path(nameof(OrderBookRowVM.order_sub_type))),
SubTypeFilterTemplateKey));
ort => ort.order.sub_type(),
nameof(OrderBookRowVM.order_sub_type)),
SubTypeFilterTemplateKey,
_wrap_comparer(r => r.order_sub_type)));
// side
Add(side_column = new SideColumn(
DiscreteValuesFilterVM.Create<OrderBookRowVM, Side>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, Side>(
new[] { Side.Buy, Side.Sell },
r => r.side.value,
value_path(nameof(OrderBookRowVM.side)))));
ort=> ort.order.side(),
nameof(OrderBookRowVM.side))));
// quantity
Add(qty_column = new SizeColumn(
new UIntMinMax<OrderBookRowVM>(r => r.quantity.value, value_path(nameof(OrderBookRowVM.quantity)))));
// price
Add(price_column = new PriceColumn(
new DoubleMinMax<OrderBookRowVM>(r => r.price.value, value_path(nameof(OrderBookRowVM.price)))));
new UIntMinMax<OrderRecordTuple>(ort => ort.order.quantity(), nameof(OrderBookRowVM.quantity))));
// filled quantity
Add(filled_qty_column = new FilledColumn(
new UIntMinMax<OrderBookRowVM>(r => r.filled_quantity.value, value_path(nameof(OrderBookRowVM.filled_quantity)))));
new UIntMinMax<OrderRecordTuple>(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
// price
Add(price_column = new SimpleTextColumn<DoubleMinMaxState>(
Columns.Price,
"Price",
nameof(OrderBookRowVM.price),
r => r.price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderRecordTuple>(
ort => ort.order.price(),
nameof(OrderBookRowVM.price)),
DataGridFilterKnownTemplates.DoubleMinMax,
_wrap_comparer(r => r.price)));
// avg filled price
Add(avg_price_column = new AvgFilledColumn(
new DoubleMinMax<OrderBookRowVM>(r => r.avg_price.value, value_path(nameof(OrderBookRowVM.avg_price)))));
Add(avg_price_column = new SimpleTextColumn<DoubleMinMaxState>(
Columns.AvgFilled,
"Avg Price",
nameof(OrderBookRowVM.avg_price),
r => r.avg_price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderRecordTuple>(
ort => ort.order.avg_price(),
nameof(OrderBookRowVM.avg_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
_wrap_comparer(r => r.avg_price)));
// last filled price
Add(last_price_column = new LastFilledColumn(
new DoubleMinMax<OrderBookRowVM>(r => r.last_price.value, value_path(nameof(OrderBookRowVM.last_price)))));
Add(last_price_column = new SimpleTextColumn<DoubleMinMaxState>(
Columns.LastPrice,
"Last Filled",
nameof(OrderBookRowVM.last_price),
r => r.last_price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderRecordTuple>(
ort => ort.order.last_price(),
nameof(OrderBookRowVM.last_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
_wrap_comparer(r => r.last_price)));
// status
Add(status_column = new SimpleTextColumn<OrderStatus[]>(
Columns.Status,
"Status",
nameof(OrderBookRowVM.status),
r => r.status.store,
r => r.status.ToString(),
80,
DiscreteValuesFilterVM.Create<OrderBookRowVM, OrderStatus>(
DiscreteValuesFilterVM.Create<OrderRecordTuple, OrderStatus>(
EnumHelper.get_values<OrderStatus>().ToList(),
r => r.status.value,
value_path(nameof(OrderBookRowVM.status))),
DataGridFilterKnownTemplates.EnumValues));
ort => ort.order.status(),
nameof(OrderBookRowVM.status)),
DataGridFilterKnownTemplates.EnumValues,
_wrap_comparer(r => r.status)));
// last message
Add(last_message_column = new OrderBookLastMessageColumn(
new RegexFilterVM<OrderBookRowVM>(
r => r.last_msg.value,
value_path(nameof(OrderBookRowVM.last_msg)))));
new RegexFilterVM<OrderRecordTuple>(
ort => ort.order.last_msg(),
nameof(OrderBookRowVM.last_msg))));
// security key
Add(security_key_column = new SimpleTextColumn<string>(
Columns.SecurityKey,
DefaultColumnHeaders.SecurityKey,
nameof(OrderBookRowVM.security_key),
r => r.security_key.store,
r => r.security_key.ToString(),
DefaultColumnWidths.SecurityKey,
new RegexFilterVM<OrderBookRowVM>(
r => r.security_key.text,
value_path(nameof(OrderBookRowVM.security_key))),
DataGridFilterKnownTemplates.Regex));
new RegexFilterVM<OrderRecordTuple>(
ort => ort.order.security_key().ToString(),
nameof(OrderBookRowVM.security_key)),
DataGridFilterKnownTemplates.Regex,
_wrap_comparer(r => r.security_key)));
// order key
Add(order_key_column = new SimpleTextColumn<string>(
Columns.OrderKey,
DefaultColumnHeaders.OrderKey,
nameof(OrderBookRowVM.order_key),
r => r.order_key.store,
r => r.order_key.ToString(),
DefaultColumnWidths.OrderKey,
new RegexFilterVM<OrderBookRowVM>(
r => r.order_key.text,
value_path(nameof(OrderBookRowVM.order_key))),
DataGridFilterKnownTemplates.Regex));
new RegexFilterVM<OrderRecordTuple>(
ort => ort.order.Key.ToString(),
nameof(OrderBookRowVM.order_key)),
DataGridFilterKnownTemplates.Regex,
_wrap_comparer(r => r.order_key)));
// parent key (this is for diagnostic purposes, remove this column once OrderBook seems stable again)
Add(parent_key_column = new SimpleTextColumn<string>(
Columns.ParentKey,
"Parent Key",
nameof(OrderBookRowVM.parent_order_key),
r => r.parent_order_key.store,
r => r.parent_order_key.ToString(),
80,
new RegexFilterVM<OrderBookRowVM>(
r => r.parent_order_key.text,
value_path(nameof(OrderBookRowVM.parent_order_key))),
DataGridFilterKnownTemplates.Regex));
string value_path(string cell_name) =>
string.Join(".", cell_name, nameof(OrderBookRowVM.IOrderBookCell<uint>.value)); //uint is an arbitrary 'T', just want to get compile check on 'value' path.
new RegexFilterVM<OrderRecordTuple>(
ort => ort.order.ParentKey.ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
_wrap_comparer(r => r.parent_order_key)));
}
List<IDataGridColumnFilter<OrderBookRowVM>> _active_filters = new List<IDataGridColumnFilter<OrderBookRowVM>>(0);
public event Action filter_changed;
public SecurityColumn security_column { get; }
public SimpleTextColumn<string[]> symbol_column { get; }
public TimeCreatedColumn time_created_column { get; }
public LastChangeTimeColumn last_change_column { get; }
public SimpleTextColumn<TimeFilterTuple> time_created_column { get; }
public SimpleTextColumn<TimeFilterTuple> last_change_column { get; }
public SimpleTextColumn<string[]> user_column { get; }
public SimpleTextColumn<string[]> account_column { get; }
public SimpleTextColumn<Venue[]> exchange_column { get; }
@@ -234,18 +288,16 @@ namespace mbts.spark {
public SimpleTextColumn<OrderSubType[]> sub_type_column { get; }
public SideColumn side_column { get; }
public SizeColumn qty_column { get; }
public PriceColumn price_column { get; }
public SimpleTextColumn<DoubleMinMaxState> price_column { get; }
public FilledColumn filled_qty_column { get; }
public LastFilledColumn last_price_column { get; }
public AvgFilledColumn avg_price_column { get; }
public SimpleTextColumn<DoubleMinMaxState> last_price_column { get; }
public SimpleTextColumn<DoubleMinMaxState> avg_price_column { get; }
public SimpleTextColumn<OrderStatus[]> status_column { get; }
public OrderBookLastMessageColumn last_message_column { get; }
public SimpleTextColumn<string> security_key_column { get; }
public SimpleTextColumn<string> order_key_column { get; }
public SimpleTextColumn<string> parent_key_column { get; }
public bool filter(OrderBookRowVM row) => _active_filters.All(f => f.filter(row));
public FilterStates create() =>
new FilterStates {
order_key_regex = order_key_column.filter.get_state(),
@@ -271,9 +323,6 @@ namespace mbts.spark {
public void load_from(FilterStates fs) {
if (fs != null) {
foreach (var c in this.Cast<ICVOrderBookColumn>())
c.filter.filter_changed -= _set_active_filters;
//
security_column.filter.load_state(fs.security_criteria);
symbol_column.filter.load_state(fs.symbols);
time_created_column.filter.load_state(fs.time_created);
@@ -293,54 +342,121 @@ namespace mbts.spark {
status_column.filter.load_state(fs.statuses);
last_message_column.filter.load_state(fs.exchange_message_regex);
last_change_column.filter.load_state(fs.last_change);
//
_set_active_filters();
foreach (var c in this.Cast<ICVOrderBookColumn>())
c.filter.filter_changed += _set_active_filters;
}
}
public Func<OrderRecordTuple, 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<OrderRecordTuple, bool>(r => active_filters.All(f => f.filter(r)));
}
public (IComparer<OrderBookRowVM> comp, string desc) get_comparer_data() {
var desc_parts = new List<string>();
var comp_builder = new ComparerBuilder<OrderBookRowVM>();
// this should be unneccesary, safe_active_comparers is just an extra guard against unexpected results from future code changes
// (get_comparer_data() should NEVER return a null/non-deterministic IComparer, fallback to sorting by Time Created in descending order if necessary)
var safe_active_comparers = _active_comparers.Where(c => c.SortDirection.HasValue).ToList();
if (safe_active_comparers.Count == 0) {
time_created_column.SortDirection = ListSortDirection.Descending;
_active_comparers.Clear();
_active_comparers.Add(time_created_column);
safe_active_comparers = _active_comparers;
}
foreach (var col in safe_active_comparers) {
desc_parts.Add($"{col.id}:{col.SortDirection.Value}");
comp_builder.add(col.SortDirection.Value == ListSortDirection.Ascending ? col.comparer : col.comparer.reverse());
}
return (comp_builder.to_comparer(), string.Join(", ", desc_parts));
}
public void on_sorting(ICVOrderBookColumn col, bool clear_current_sort) {
col.SortDirection = col.SortDirection.HasValue && col.SortDirection.Value == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
if (_active_comparers.Contains(col, EqualityComparer.Create<ICVOrderBookColumn, Columns>(r => r.key))) {
if (clear_current_sort) _reset_active_comparer(col);
} else {
if (clear_current_sort) _reset_active_comparer(col);
else _active_comparers.Add(col);
}
}
public void Dispose() {
foreach (var c in this.Cast<ICVOrderBookColumn>()) {
c.filter.filter_changed -= _set_active_filters;
(c.filter as IDisposable)?.Dispose();
foreach (var col in this.OfType<ICVOrderBookColumn>())
(col.filter as IDisposable)?.Dispose();
Clear();
}
protected override void InsertItem(int index, ColumnBase item) {
if (item is ICVOrderBookColumn col) {
try {
_hook(col);
base.InsertItem(index, item);
} catch {
_unhook(col);
throw;
}
} else {
Log.Ui.warn($"{nameof(OrderBookColumnCollection)} added a column that is not of type {nameof(ICVOrderBookColumn)}");
base.InsertItem(index, item);
}
}
void _set_active_filters() {
_active_filters = this
.Cast<ICVOrderBookColumn>()
.Select(c => c.filter)
.Where(f => f.active.GetValueOrDefault())
.ToList();
filter_changed?.Invoke();
protected override void RemoveItem(int index) {
if (Count > index && this[index] is ICVOrderBookColumn col)
_unhook(col);
base.RemoveItem(index);
}
protected override void ClearItems() {
var ob_columns = this.OfType<ICVOrderBookColumn>().ToList();
Log.Ui.info($"{nameof(OrderBookColumnCollection)} is unhooking all columns of type {nameof(ICVOrderBookColumn)} ({ob_columns.Count}/{Count}).");
foreach (var col in ob_columns)
_unhook(col);
base.ClearItems();
}
void _hook(ICVOrderBookColumn new_item) => new_item.filter.filter_changed += _on_column_filter_changed;
void _unhook(ICVOrderBookColumn old_item) => old_item.filter.filter_changed -= _on_column_filter_changed;
void _on_column_filter_changed() => filter_changed?.Invoke();
void _reset_active_comparer(ICVOrderBookColumn column) {
foreach (var col in _active_comparers) {
if (!col.Equals(column)) col.SortDirection = null;
}
_active_comparers.Clear();
_active_comparers.Add(column);
}
}
static IComparer<OrderBookRowVM> _wrap_comparer<T>(Func<OrderBookRowVM, T> get) =>
Comparer<T>.Default.wrap(get);
static IComparer<OrderBookRowVM> _wrap_comparer<T>(Func<OrderBookRowVM, T> get, IComparer<T> comparer) =>
comparer.wrap(get);
public abstract class OrderbookColumnBase<T> : ColumnBase<Columns>, IKeyedColumn<Columns>, IFilterableColumn, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
readonly string _filter_template;
protected readonly Func<OrderBookRowVM, IOrderBookCellStore> _get_cell_store;
protected readonly Func<OrderBookRowVM, string> _get_text;
protected OrderbookColumnBase(Columns col_key, string header, Func<OrderBookRowVM, IOrderBookCellStore> get_cell_store, string sort_prop, double width, IDataGridColumnPersistentFilter<OrderBookRowVM, T> filter, string filter_template) : base(col_key) {
protected OrderbookColumnBase(Columns col_key, string header, Func<OrderBookRowVM, string> get_text, string sort_prop, double width,
IDataGridColumnPersistentFilter<OrderRecordTuple, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
id = key.ToString();
Width = width;
Header = header;
_get_cell_store = get_cell_store;
_get_text = get_text;
sort_member_path = sort_prop;
this.filter = filter;
_filter_template = filter_template;
_cached_sort_direction = SortDirection;
this.comparer = comparer;
}
public IDataGridColumnPersistentFilter<OrderBookRowVM, T> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTuple, T> filter { get; }
public IComparer<OrderBookRowVM> comparer { get; }
IDataGridColumnFilter<OrderBookRowVM> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTuple> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => _filter_template;
ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction;
public IGridCellStore get_cell_store(OrderBookRowVM row) => _get_cell_store(row);
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
_cached_sort_direction = new_value;
@@ -349,99 +465,51 @@ namespace mbts.spark {
}
public class SimpleTextColumn<TFilterState> : OrderbookColumnBase<TFilterState>, IRenderColumn<OrderBookRowVM> {
public SimpleTextColumn(Columns key, string header, string sort_prop, Func<OrderBookRowVM, IOrderBookCellStore> get_cell_store, double width, IDataGridColumnPersistentFilter<OrderBookRowVM, TFilterState> filter, string filter_template)
: base(key, header, get_cell_store, sort_prop, width, filter, filter_template) { }
public SimpleTextColumn(Columns key, string header, string sort_prop, Func<OrderBookRowVM, string> get_text, double width,
IDataGridColumnPersistentFilter<OrderRecordTuple, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
: base(key, header, get_text, sort_prop, width, filter, filter_template, comparer) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) {
var cell = _get_cell_store(row);
if (!string.IsNullOrEmpty(cell.current.text))
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, cell.current.text, position, RowHeight,
font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, cell.animations);
}
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, _get_text(row), position, RowHeight,
font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
}
#region Explicit Column Defs
public class SideColumn : OrderbookColumnBase<Side[]>, IRenderColumn<OrderBookRowVM> {
public SideColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, Side[]> filter)
: base(Columns.Side, "B/S", r => r.side.store, nameof(OrderBookRowVM.side), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues) { }
public SideColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, Side[]> filter)
: base(Columns.Side, "B/S", r => r.side.ToString(), nameof(OrderBookRowVM.side), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues, _wrap_comparer(r => r.side)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.side.text, position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.side.store.animations);
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.side.ToString(), position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
}
public class SizeColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
public SizeColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, UIntMinMaxState> filter)
: base(Columns.Size, "Qty", r => r.quantity.store, nameof(OrderBookRowVM.quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax) {
public SizeColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, UIntMinMaxState> filter)
: base(Columns.Size, "Qty", r => r.quantity.ToString(), nameof(OrderBookRowVM.quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.quantity)) {
sort_member_path = nameof(OrderBookRowVM.quantity);
}
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.quantity.text, position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.quantity.store.animations);
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.quantity.ToString(), position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
}
public class FilledColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
public FilledColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, UIntMinMaxState> filter)
: base(Columns.Filled, "Filled Qty", r => r.filled_quantity.store, nameof(OrderBookRowVM.filled_quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax) {
public FilledColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, UIntMinMaxState> filter)
: base(Columns.Filled, "Filled Qty", r => r.filled_quantity.ToString(), nameof(OrderBookRowVM.filled_quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.filled_quantity)) {
sort_member_path = nameof(OrderBookRowVM.filled_quantity);
}
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.filled_quantity.text, position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.filled_quantity.store.animations);
}
public class PriceColumn : OrderbookColumnBase<DoubleMinMaxState>, IRenderColumn<OrderBookRowVM> {
public PriceColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, DoubleMinMaxState> filter)
: base(Columns.Price, "Price", r => r.price.store, nameof(OrderBookRowVM.price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.price.text,
position, RowHeight, font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.price.store.animations);
}
public class AvgFilledColumn : OrderbookColumnBase<DoubleMinMaxState>, IRenderColumn<OrderBookRowVM> {
public AvgFilledColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, DoubleMinMaxState> filter)
: base(Columns.AvgFilled, "Avg Filled", r => r.avg_price.store, nameof(OrderBookRowVM.avg_price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) {
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.avg_price.text,
position, RowHeight, font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.avg_price.store.animations);
}
}
public class LastFilledColumn : OrderbookColumnBase<DoubleMinMaxState>, IRenderColumn<OrderBookRowVM> {
public LastFilledColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, DoubleMinMaxState> filter)
: base(Columns.LastPrice, "Last Filled", r => r.last_price.store, nameof(OrderBookRowVM.last_price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.last_price.text,
position, RowHeight, font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.last_price.store.animations);
}
public class TimeCreatedColumn : OrderbookColumnBase<TimeFilterTuple>, IRenderColumn<OrderBookRowVM> {
public TimeCreatedColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, TimeFilterTuple> filter)
: base(Columns.Time, "Time", r => r.time_created.store, nameof(OrderBookRowVM.time_created), DefaultColumnWidths.Time, filter, DataGridFilterKnownTemplates.TimeFilter) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.time_created.text,
position, RowHeight, font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.time_created.store.animations);
}
public class LastChangeTimeColumn : OrderbookColumnBase<TimeFilterTuple>, IRenderColumn<OrderBookRowVM> {
public LastChangeTimeColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, TimeFilterTuple> filter)
: base(Columns.LastChange, "Last Change", r => r.last_change.store, nameof(OrderBookRowVM.last_change), DefaultColumnWidths.Time, filter, DataGridFilterKnownTemplates.TimeFilter) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.last_change.text,
position, RowHeight, font_brush, null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding, row.last_change.store.animations);
CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), font_size, row.filled_quantity.ToString(), position, RowHeight,
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
}
public class OrderBookOrderTypeColumn : OrderTypeColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, OrderType[]> filter)
: base(Columns.OrderType, new Binding($"{nameof(OrderBookRowVM.order_type)}.{nameof(IOrderBookCell<OrderType>.value)}"), new Binding(nameof(OrderBookRowVM.order_metadata)), filter) {
public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, OrderType[]> filter)
: base(Columns.OrderType, new Binding(nameof(OrderBookRowVM.order_type)), new Binding(nameof(OrderBookRowVM.order_metadata)), filter) {
id = key.ToString();
this.filter = filter;
sort_member_path = nameof(OrderBookRowVM.order_type);
@@ -449,12 +517,11 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
public new IDataGridColumnPersistentFilter<OrderBookRowVM, OrderType[]> filter { get; }
public new IDataGridColumnPersistentFilter<OrderRecordTuple, OrderType[]> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.order_type);
IDataGridColumnFilter<OrderBookRowVM> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction;
public IGridCellStore get_cell_store(OrderBookRowVM row) => row.order_type.store;
IDataGridColumnFilter<OrderRecordTuple> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
_cached_sort_direction = new_value;
@@ -465,8 +532,8 @@ namespace mbts.spark {
public class OrderBookLastMessageColumn : TextColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, string> filter)
: base(Columns.LastMessage, new Binding($"{nameof(OrderBookRowVM.last_msg)}.{nameof(OrderBookRowVM.IOrderBookCell<string>.value)}"), filter, DataGridFilterKnownTemplates.Regex) {
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, string> filter)
: base(Columns.LastMessage, new Binding(nameof(OrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) {
id = key.ToString();
this.filter = filter;
Header = "Last Message";
@@ -475,12 +542,11 @@ namespace mbts.spark {
tooltip_binding = new Binding(nameof(OrderBookRowVM.last_msg));
}
public new IDataGridColumnPersistentFilter<OrderBookRowVM, string> filter { get; }
public new IDataGridColumnPersistentFilter<OrderRecordTuple, string> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.last_msg);
IDataGridColumnFilter<OrderBookRowVM> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction;
public IGridCellStore get_cell_store(OrderBookRowVM row) => row.last_msg.store;
IDataGridColumnFilter<OrderRecordTuple> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
_cached_sort_direction = new_value;
@@ -495,7 +561,7 @@ namespace mbts.spark {
ListSortDirection? _cached_sort_direction;
public SecurityColumn(IDataGridColumnPersistentFilter<OrderBookRowVM, SecurityCriteria> filter) : base(Columns.Security) {
public SecurityColumn(IDataGridColumnPersistentFilter<OrderRecordTuple, SecurityCriteria> filter) : base(Columns.Security) {
id = key.ToString();
this.filter = filter;
Header = DefaultColumnHeaders.Security;
@@ -504,14 +570,13 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
public IDataGridColumnPersistentFilter<OrderBookRowVM, SecurityCriteria> filter { get; }
public IDataGridColumnPersistentFilter<OrderRecordTuple, SecurityCriteria> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.security, SecurityHelper.Comparer.InstanceImmutable.to_nullable());
IDataGridColumnFilter<OrderBookRowVM> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderRecordTuple> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues;
ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction;
public IGridCellStore get_cell_store(OrderBookRowVM row) => row.security.store;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
public override FrameworkElement view_factory() {
// expander
@@ -522,7 +587,7 @@ namespace mbts.spark {
toggle_button.SetResourceReference(ToggleButton.StyleProperty, ExpandCollapseToggleStyleKey);
//
var security_view = new TextBlock { FontFamily = font_family, FontSize = font_size, Foreground = font_brush };
security_view.SetBinding(TextBlock.TextProperty, $"{nameof(OrderBookRowVM.security)}.{nameof(IGridCell.text)}");
security_view.SetBinding(TextBlock.TextProperty, nameof(OrderBookRowVM.security_text));
security_view.SetBinding(TextBlock.HorizontalAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this });
security_view.SetBinding(TextBlock.ForegroundProperty, new Binding(nameof(font_brush)) { Source = this });
security_view.SetBinding(TextBlock.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this });
@@ -536,7 +601,7 @@ namespace mbts.spark {
grid.Children.Add(security_view);
//
var border = new Border { Child = grid };
CellRender.set_background_animation_bindings(border, $"{nameof(OrderBookRowVM.security)}.{nameof(OrderBookRowVM.security.store)}");
CellRender.set_background_animation_bindings(border, nameof(OrderBookRowVM.security));
return border;
}
@@ -568,7 +633,7 @@ namespace mbts.spark {
}
public static GlyphContext get_glyph_context(OrderBookRowVM r) => r.is_child ? _child_glyph_context : TextUtils.StandardGlyphContext;
public static Brush get_side_brush(OrderBookRowVM r) => r.side.value == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
public static Brush get_side_brush(OrderBookRowVM r) => r.side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
public static BindingBase get_font_weight_binding() => new Binding(nameof(OrderBookRowVM.is_child)) { Converter = _font_weight_converter };
}
}
@@ -0,0 +1,141 @@
using bts.api.core;
using bts.collections;
using bts.utils;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
namespace mbts.spark {
class OrderBookRowCollection : ObservableCollection<OrderBookRowVM> {
static readonly IEqualityComparer<INode<OrderBookRowVM>> _node_equality_comparer = EqualityComparer.Create<INode<OrderBookRowVM>, uint>(n => n.value.order_key);
readonly Func<OrderRecordTuple, OrderBookRowVM> _row_factory;
SortedTree<OrderBookRowVM, uint> _tree;
IComparer<OrderBookRowVM> _comparer;
Func<OrderRecordTuple, bool> _filter;
bool _is_refresh_pending;
int _last_row_count = 0, _deferment_count = 0;
public OrderBookRowCollection(Func<OrderRecordTuple, OrderBookRowVM> row_factory, IComparer<OrderBookRowVM> comparer) {
_row_factory = row_factory;
_tree = new SortedTree<OrderBookRowVM, uint>(_comparer = comparer, r => r.order_key, r => r.parent_order_key);
}
public Func<OrderRecordTuple, bool> filter { get => _filter; set { _filter = value; refresh(); } }
public IComparer<OrderBookRowVM> comparer { get => _comparer; set { _tree = _tree.Resort(_comparer = value); refresh(); } }
public IEnumerable<OrderBookRowVM> all_rows => _tree;
public IEnumerable<OrderBookRowVM> _visible_rows =>
filter == null ?
_tree.Where(r => r.is_visible) :
_tree.Where(r => r.is_visible && filter(r.order_tuple));
bool _is_refresh_deferred => _deferment_count > 0;
public IEnumerable<INode<OrderBookRowVM>> get_inner_nodes(OrderBookRowVM row) =>
_tree.EnumerateInnerNodes(row);
public IEnumerable<OrderBookRowVM> get_descendent_rows(OrderBookRowVM row) =>
_tree.EnumerateInnerValues(row);
public void refresh() {
if (_is_refresh_deferred) {
_is_refresh_pending = true;
} else {
_is_refresh_pending = false;
this.sync_with(_visible_rows);
}
}
public IDisposable defer_refresh(bool force_refresh_after = false) {
// use a counter instead of a simple bool flag to gracefully handle recursive calls to defer_refresh(),
// by only calling refresh() after all IDisposables returned by defer_refresh() have been disposed.
_deferment_count++;
_is_refresh_pending |= force_refresh_after;
return Disposable.Create(() => {
_deferment_count--;
if (_is_refresh_pending)
refresh();
});
}
public void update(IIncrementalTableUpdateTransform<OrderRecordTuple, uint> table) {
IEnumerable<INode<OrderBookRowVM>> impacted_branch_roots;
if (table.removed.Count() == _last_row_count) {
// full refresh (most likely this is the first update or a server restart)
_tree.Clear();
_tree.AddAll(table.added.Select(_row_factory));
impacted_branch_roots = table.added.Select(ort => _tree.GetRootNode(ort.order.Key)).Distinct(_node_equality_comparer);
} else {
/// The update proceedure, broken down into steps, will be executed in the following order:
/// 1) Removes - independent of filter, as <see cref="SortedTree{T, TKey}.Remove(T)"/> is idempotent and cheap
/// 2) Changes
/// 3) Adds
// 1) Removes
foreach (OrderRecordTuple ort in table.removed)
_tree.Remove(ort.order.Key);
if (filter == null) {
// 2) Changes (unfiltered)
foreach (Change<OrderRecordTuple> change in table.changes)
change_row(change.New);
// 3) Adds (unfiltered)
foreach (OrderRecordTuple ort in table.added) {
_tree.Insert(_row_factory(ort));
}
} else {
// 2) Changes (filtered)
foreach (Change<OrderRecordTuple> change in table.changes) {
if (filter(change.Old)) {
if (filter(change.New)) {
change_row(change.New);
} else {
_tree.Remove(change.Old.order.Key);
}
} else if (filter(change.New)) {
_tree.Insert(_row_factory(change.New));
}
}
// 3 Adds (filtered)
foreach (OrderRecordTuple item in table.added.Where(filter))
_tree.Insert(_row_factory(item));
}
impacted_branch_roots =
table.added.Concat(table.changed).Select(ort => ort.order.Key)
.Concat(
table.removed
.Where(ort => ort.order.has_parent())
.Select(ort => ort.order.ParentKey)
.Distinct() // since these are ParentKeys, there could be duplicates.
).Select(_tree.GetRootNode)
.Distinct(_node_equality_comparer);
}
_last_row_count += table.added.Count() - table.removed.Count();
foreach (var n in impacted_branch_roots) {
_refresh_tree_properties(0, true, n);
}
refresh();
// local methods
void change_row(OrderRecordTuple newval) =>
_tree.Replace(newval.order.Key, r => {
r.update(newval);
return r;
});
}
void _refresh_tree_properties(int depth_level, bool is_visible, INode<OrderBookRowVM> node) {
node.value.depth_level = depth_level;
node.value.is_visible = is_visible;
using (var en = node.inner.GetEnumerator()) {
if (en.MoveNext()) {
node.value.is_parent = true;
depth_level++;
do _refresh_tree_properties(depth_level, node.value.is_visible && node.value.is_expanded, en.Current);
while (en.MoveNext());
}
}
}
}
}
@@ -6,403 +6,130 @@ using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using static mbts.spark.OrderBookView;
using OrderStatus = bts.api.orderman.OrderStatus;
namespace mbts.spark {
partial class OrderBookRowVM : DisposableViewModelBase, IEquatable<OrderBookRowVM>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
const string _unknown_security_price_format_string = "0.#########";
const int _unknown_security_price_num_fractional_digits = 9;
readonly OrderBookVM _book_vm;
readonly OrdersModel _model;
readonly Property<bool> _visible, _expanded, _passes_filter;
readonly DelegateProperty<int> _depth_level;
readonly HashSet<OrderBookRowVM> _child_rows = new HashSet<OrderBookRowVM>();
readonly ObservantCommand _show_order_modify_cmd;
OrderRecordImmutable _order;
SecurityMD? _security_md;
string _symbol;
OrderBookRowVM _parent;
OrderBookVM.BranchFilterSource _branch_filter_source;
// Core
IOrderBookCellStore<uint> _order_key_store_backing;
IOrderBookCellStore<uint> _parent_order_key_store_backing;
IOrderBookCellStore<uint> _security_key_store_backing;
IOrderBookCellStore<SecurityImmutable?> _security_store_backing;
IOrderBookCellStore<Venue> _exchange_store_backing;
IOrderBookCellStore<string> _symbol_store_backing;
// Def
IOrderBookCellStore<CustomOrderDefinition.CustomOneofCase> _order_type_store_backing;
IOrderBookCellStore<Side> _side_store_backing;
IOrderBookCellStore<string> _user_store_backing;
IOrderBookCellStore<string> _account_store_backing;
IOrderBookCellStore<TimeInForce> _time_in_force_store_backing;
IOrderBookCellStore<DateTime> _time_created_store_backing;
// State
IOrderBookCellStore<DateTime> _last_change_store_backing;
IOrderBookCellStore<OrderStatus> _status_store_backing;
IOrderBookCellStore<double> _price_store_backing;
IOrderBookCellStore<uint> _quantity_store_backing;
IOrderBookCellStore<uint> _filled_quantity_store_backing;
IOrderBookCellStore<double> _last_price_store_backing;
IOrderBookCellStore<double> _avg_price_store_backing;
IOrderBookCellStore<string> _last_msg_store_backing;
IOrderBookCellStore<OrderSubType> _order_sub_type_store_backing;
// Core
IOrderBookCellStore<uint> _order_key_store => _order_key_store_backing ?? (_order_key_store_backing = CellFactory.create(this, _book_vm.columns.order_key_column, nameof(order_key), r => r._order.Key, r => r._order_key_store));
IOrderBookCellStore<uint> _parent_order_key_store => _parent_order_key_store_backing ?? (_parent_order_key_store_backing = CellFactory.create(this, _book_vm.columns.parent_key_column, nameof(parent_order_key), r => r._order.ParentKey, r => r._parent_order_key_store));
IOrderBookCellStore<uint> _security_key_store => _security_key_store_backing ?? (_security_key_store_backing = CellFactory.create(this, _book_vm.columns.security_key_column, nameof(security_key), r => r._order.security_key(), r => r._security_key_store));
IOrderBookCellStore<SecurityImmutable?> _security_store => _security_store_backing ?? (_security_store_backing = CellFactory.create_nullable(this, _book_vm.columns.security_column, nameof(security), r => r._security, r => r._security_store, v => v.display_name()));
IOrderBookCellStore<Venue> _exchange_store => _exchange_store_backing ?? (_exchange_store_backing = CellFactory.create(this, _book_vm.columns.exchange_column, nameof(exchange), r => r._security.HasValue ? _security.Value.Exchange : Venue.Unset, r => r._exchange_store));
IOrderBookCellStore<string> _symbol_store => _symbol_store_backing ?? (_symbol_store_backing = CellFactory.create(this, _book_vm.columns.symbol_column, nameof(symbol), r => r._symbol, r => r._symbol_store, v => !String.IsNullOrEmpty(v) ? v : "unknown symbol"));
// Def
IOrderBookCellStore<CustomOrderDefinition.CustomOneofCase> _order_type_store => _order_type_store_backing ?? (_order_type_store_backing = CellFactory.create(this, _book_vm.columns.order_type_column, nameof(order_type), r => r._order.order_type(), r => r._order_type_store));
IOrderBookCellStore<Side> _side_store => _side_store_backing ?? (_side_store_backing = CellFactory.create(this, _book_vm.columns.side_column, nameof(side), r => r._order.side(), r => r._side_store));
IOrderBookCellStore<string> _user_store => _user_store_backing ?? (_user_store_backing = CellFactory.create(this, _book_vm.columns.user_column, nameof(user), r => _order.user(), r => r._user_store));
IOrderBookCellStore<string> _account_store => _account_store_backing ?? (_account_store_backing = CellFactory.create(this, _book_vm.columns.account_column, nameof(account), r => r._order.account(), r => r._account_store));
IOrderBookCellStore<TimeInForce> _time_in_force_store => _time_in_force_store_backing ?? (_time_in_force_store_backing = CellFactory.create(this, _book_vm.columns.time_in_force_column, nameof(time_in_force), r => r._order.time_in_force(), r => r._time_in_force_store));
IOrderBookCellStore<DateTime> _time_created_store => _time_created_store_backing ?? (_time_created_store_backing = CellFactory.create(this, _book_vm.columns.time_created_column, nameof(time_created), r => r._order.created(), r => r._time_created_store, format_date));
// State
IOrderBookCellStore<DateTime> _last_change_store => _last_change_store_backing ?? (_last_change_store_backing = CellFactory.create(this, _book_vm.columns.last_change_column, nameof(last_change), r => _order.last_change(), r => r._last_change_store, format_date));
IOrderBookCellStore<OrderStatus> _status_store => _status_store_backing ?? (_status_store_backing = CellFactory.create(this, _book_vm.columns.status_column, nameof(status), r => _order.status(), r => r._status_store));
IOrderBookCellStore<double> _price_store => _price_store_backing ?? (_price_store_backing = CellFactory.create(this, _book_vm.columns.price_column, nameof(price), r => _order.price(), r => r._price_store, format_price));
IOrderBookCellStore<uint> _quantity_store => _quantity_store_backing ?? (_quantity_store_backing = CellFactory.create(this, _book_vm.columns.qty_column, nameof(quantity), r => _order.quantity(), r => r._quantity_store));
IOrderBookCellStore<uint> _filled_quantity_store => _filled_quantity_store_backing ?? (_filled_quantity_store_backing = CellFactory.create(this, _book_vm.columns.filled_qty_column, nameof(filled_quantity), r => _order.filled(), r => r._filled_quantity_store));
IOrderBookCellStore<double> _last_price_store => _last_price_store_backing ?? (_last_price_store_backing = CellFactory.create(this, _book_vm.columns.last_price_column, nameof(last_price), r => _order.last_price(), r => r._last_price_store, format_price));
IOrderBookCellStore<double> _avg_price_store => _avg_price_store_backing ?? (_avg_price_store_backing = CellFactory.create(this, _book_vm.columns.avg_price_column, nameof(avg_price), r => _order.avg_price(), r => r._avg_price_store, format_price));
IOrderBookCellStore<string> _last_msg_store => _last_msg_store_backing ?? (_last_msg_store_backing = CellFactory.create(this, _book_vm.columns.last_message_column, nameof(last_msg), r => _order.last_msg(), r => r._last_msg_store));
IOrderBookCellStore<OrderSubType> _order_sub_type_store => _order_sub_type_store_backing ?? (_order_sub_type_store_backing = CellFactory.create(this, _book_vm.columns.sub_type_column, nameof(order_sub_type), r => r._order.sub_type(), r => r._order_sub_type_store, format_sub_type));
readonly OrderBookVM _owner;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd;
bool _is_parent, _is_expanded;
int _depth_level;
SecurityMD? _security_md => order_tuple.security_md;
public OrderBookRowVM(OrderBookVM owner, OrderRecordTuple order_tuple) {
_owner = owner;
this.order_tuple = order_tuple;
is_visible = !is_child;
}
static string format_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}";
string format_price(double v) => _security.HasValue ?
_security.Value.ContractSpec.format(v) :
Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string);
static string format_sub_type(OrderSubType v) {
public event Action invalidated;
// Core
public OrderRecordTuple order_tuple { get; private set; }
public OrderRecordImmutable order => order_tuple.order;
public OrderMetadata order_metadata => _owner.get_metadata(this);
public uint order_key => order.Key;
public uint parent_order_key => order.ParentKey;
public uint security_key => order.security_key();
public SecurityImmutable? security => _security_md.security();
public string security_text => security.display_name();
public Venue exchange => _security_md.exchange();
public string symbol => _security_md.symbol();
// Def
public CustomOrderDefinition.CustomOneofCase order_type => order.order_type();
public OrderSubType order_sub_type => order.sub_type();
public string order_sub_type_text => _fmt_order_sub_type(order_sub_type);
public Side side => order.side();
public string user => order.user();
public string account => order.account();
public TimeInForce time_in_force => order.time_in_force();
public DateTime time_created => order.created();
public string time_created_text => _fmt_date(time_created);
// State
public DateTime last_change => order.last_change();
public string last_change_text => _fmt_date(last_change);
public OrderStatus status => order.status();
public double price => order.price();
public double last_price => order.last_price();
public double avg_price => order.avg_price();
public string price_text => _fmt_price(price);
public string last_price_text => _fmt_price(last_price);
public string avg_price_text => _fmt_price(avg_price);
public uint quantity => order.quantity();
public uint filled_quantity => order.filled();
public string last_msg => order.last_msg();
// Tree
public bool is_parent { get => _is_parent; set => Set(ref _is_parent, value); }
public bool is_child => order.has_parent();
public bool is_visible { get; set; }
public bool is_expanded {
get => _is_expanded;
set {
if (Set(ref _is_expanded, value))
_owner.on_expanded_changed(this);
}
}
public int depth_level { get => _depth_level; set => Set(ref _depth_level, value); }
// Commands
public ICommand toggle_command => _toggle_expanded_cmd ?? (
_toggle_expanded_cmd = new DelegateCommand(() => is_expanded = !is_expanded));
ICommand DIYGrid.IActionableRowVM.default_command => _show_order_modify_cmd ??
(_show_order_modify_cmd = new DelegateCommand(() => _owner.show_order_modify(this), () => status == OrderStatus.Working));
public void update(OrderRecordTuple order_tuple) {
Log.assert(order_tuple.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key.");
bool had_security = _security_md.HasValue;
// _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);
OrderRecordImmutable old_order = order;
this.order_tuple = order_tuple;
// most cells are "render-cells," which don't use databindings - the only way to update such cells is to raise the invalidated event
bool invalidate = !(
old_order.last_change() == order.last_change() &&
old_order.filled() == order.filled() &&
old_order.last_price() == order.last_price() &&
old_order.avg_price().Equals(order.avg_price()) &&
old_order.price().Equals(order.price()) &&
old_order.quantity() == order.quantity() &&
old_order.last_msg() == order.last_msg());
// however, the order-type and security cells DO use databindings - if these cells have changed, the PropertyChanged event must be raised regardless of whether or not invalidated is raised
if (old_order.order_type() != order.order_type())
RaisePropertyChanged(nameof(order_type), nameof(order_metadata));
if (!had_security && _security_md.HasValue) {
RaisePropertyChanged(nameof(security));
// need to raise invalidated to refresh the price cells (the security.ContractSpec determines how they are formatted - Ticks!)
invalidate = true;
}
if (old_order.status() != order.status()) {
invalidate = true;
RaisePropertyChanged(nameof(status));
}
if (could_modify_execute.HasValue && could_modify_execute.Value != _show_order_modify_cmd.CanExecute(null))
_show_order_modify_cmd.RaiseCanExecuteChanged();
if (invalidate)
raise_invalidated();
}
public void raise_invalidated() => invalidated?.Invoke();
public bool Equals(OrderBookRowVM other) => other != null && other.order.Key == order.Key;
public override bool Equals(object obj) => Equals(obj as OrderBookRowVM);
public override int GetHashCode() => (int)order.Key;
public override string ToString() => $"{order_key} {last_change} {parent_order_key}";
static string _fmt_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}";
static string _fmt_order_sub_type(OrderSubType v) {
switch (v) {
case OrderSubType.HedgingLeg: return "H";
case OrderSubType.QuotingLeg: return "Q";
default: return string.Empty;
}
}
public OrderBookRowVM(IBus bus, OrderBookVM source_vm, OrdersModel model, OrderRecordImmutable record, SecurityMD? s) {
_book_vm = source_vm;
_model = model;
_order = record;
_security_md = s;
_symbol = _security_md.HasValue ? _security_md.Value.security.Symbol : null;
_visible = backing(nameof(is_visible), true);
_expanded = backing(nameof(is_expanded), false);
_depth_level = backing(nameof(depth_level), () => {
int i = 0;
var curr = this;
while (curr._parent != null) {
i++;
curr = curr._parent;
}
return i;
});
toggle_command = new DelegateCommand(() => is_expanded = !is_expanded);
_show_order_modify_cmd = new ObservantCommand(() => bus.post(SparkTags.ShowModifyOrderTag, _order.Key));
_show_order_modify_cmd.OnNext(status.value == OrderStatus.Working);
row_passes_filter = _book_vm.columns.filter(this);
_passes_filter = backing(nameof(passes_filter), row_passes_filter);
}
public event Action invalidated;
public event Action<(OrderRecordTuple old_val, OrderRecordTuple new_val)> updated;
public OrderRecordImmutable order => _order;
public OrderMetadata order_metadata => _model.factory.get_metadata(order_type.value);
public OrderBookRowVM parent => _parent;
public OrderRecordTuple current_data => new OrderRecordTuple(_order, _security_md);
// Core
public IOrderBookCell<uint> order_key => _order_key_store.current;
public IOrderBookCell<uint> parent_order_key => _parent_order_key_store.current;
public IOrderBookCell<uint> security_key => _security_key_store.current;
public IOrderBookCell<SecurityImmutable?> security => _security_store.current;
public IOrderBookCell<Venue> exchange => _exchange_store.current;
public IOrderBookCell<string> symbol => _symbol_store.current;
// Def
public IOrderBookCell<CustomOrderDefinition.CustomOneofCase> order_type => _order_type_store.current;
public IOrderBookCell<Side> side => _side_store.current;
public IOrderBookCell<string> user => _user_store.current;
public IOrderBookCell<string> account => _account_store.current;
public IOrderBookCell<TimeInForce> time_in_force => _time_in_force_store.current;
public IOrderBookCell<DateTime> time_created => _time_created_store.current;
// State
public IOrderBookCell<DateTime> last_change => _last_change_store.current;
public IOrderBookCell<OrderStatus> status => _status_store.current;
public IOrderBookCell<double> price => _price_store.current;
public IOrderBookCell<uint> quantity => _quantity_store.current;
public IOrderBookCell<uint> filled_quantity => _filled_quantity_store.current;
public IOrderBookCell<double> last_price => _last_price_store.current;
public IOrderBookCell<double> avg_price => _avg_price_store.current;
public IOrderBookCell<string> last_msg => _last_msg_store.current;
public IOrderBookCell<OrderSubType> order_sub_type => _order_sub_type_store.current;
// Commands
public ICommand toggle_command { get; }
ICommand ui.controls.DIYGrid.IActionableRowVM.default_command => _show_order_modify_cmd;
// Accessories
public bool is_parent => _child_rows.Count > 0;
public bool is_child => _order.has_parent();
public IReadOnlyCollection<OrderBookRowVM> child_orders => _child_rows;
public OrderBookVM.BranchFilterSource branch_filter_source => _branch_filter_source;
public bool passes_filter => _passes_filter.Value;
public bool row_passes_filter { get; private set; }
public bool is_visible {
get => _visible.Value;
set {
_visible.set(value);
if (is_expanded) {
foreach (var child_row in _child_rows)
child_row.is_visible = value;
}
}
}
public bool is_expanded {
get => _expanded.Value;
set {
_expanded.set(value);
foreach (var child_row in child_orders)
child_row.is_visible = value;
}
}
public int depth_level => _depth_level.Value;
SecurityImmutable? _security => _security_md?.security;
// '_dynamic_render_cells' are presented by 'RenderColumns,' and may change value during the lifetime of this row
// Note: by instantiating all these cells inside a CellPropertyGroup, we can update all of them with a single call.
// this reduces the risk of accidentally failing to update one of the cells, esp if we make changes to them down the road.
IEnumerable<IOrderBookCellStore> _dynamic_render_cells {
get {
yield return _last_change_store;
yield return _price_store;
yield return _quantity_store;
yield return _filled_quantity_store;
yield return _avg_price_store;
yield return _last_price_store;
yield return _status_store;
yield return _last_msg_store;
}
}
IEnumerable<IOrderBookCellStore> _security_dependent_cells {
get {
yield return _security_store;
yield return _exchange_store;
yield return _symbol_store;
}
}
IEnumerable<IOrderBookCellStore> _price_cells {
get {
yield return _price_store;
yield return _avg_price_store;
yield return _last_price_store;
yield return _symbol_store;
}
}
public ObservableCollection<RowAnimation> row_animations { get; } = new ObservableCollection<RowAnimation>();
DIYGrid.IGridCellStore[] _cell_stores_backing;
public IReadOnlyList<DIYGrid.IGridCellStore> cell_stores => _cell_stores_backing ?? (_cell_stores_backing = new DIYGrid.IGridCellStore[] {
_security_store,
_security_key_store,
_parent_order_key_store,
_order_key_store,
_symbol_store,
_time_created_store,
_user_store,
_account_store,
_exchange_store,
_time_in_force_store,
_order_type_store,
_order_sub_type_store,
_side_store,
_last_change_store,
_price_store,
_quantity_store,
_filled_quantity_store,
_avg_price_store,
_last_price_store,
_status_store,
_last_msg_store
});
public static Stack<OrderBookRowVM> lineage(OrderBookRowVM node) {
var rv = new Stack<OrderBookRowVM>();
rv.Push(node);
while (node._parent != null)
rv.Push((node = node._parent));
return rv;
}
public void join_branch_filter_source(OrderBookVM.BranchFilterSource new_branch_filter_source) {
if (_branch_filter_source != null) {
_branch_filter_source.passes_filter_changed -= _passes_filter.set;
}
_branch_filter_source = new_branch_filter_source;
_branch_filter_source.set_row_passes_filter(_order.Key, row_passes_filter);
foreach (var child_row in _child_rows)
child_row.join_branch_filter_source(_branch_filter_source);
_passes_filter.set(_branch_filter_source.passes_filter);
_branch_filter_source.passes_filter_changed += _passes_filter.set;
}
/// <summary>
/// Attaches the child-row to this row's branch-filter-source, and recursively refreshes sort/filter properties for the child and it's descendents.
/// </summary>
public void add_child_order(OrderBookRowVM child_row) {
if (_child_rows.Add(child_row) && _child_rows.Count == 1)
RaisePropertyChanged(nameof(is_parent));
child_row._parent = this;
// child orders that arrived in an earlier update use a temporary branch_filter_source
// need to tell _book_vm to remove the now-stale branch_filter_source.
if (child_row._branch_filter_source != null)
_book_vm.remove_branch_filter_root(child_row._order.Key);
// recursively updates 'live_sorting_props,' and 'is_visible' for child_row and descendents
child_row._on_lineage_changed();
}
public void remove_child_order(OrderBookRowVM child_row) {
if (_child_rows.Remove(child_row) && _child_rows.Count == 0)
RaisePropertyChanged(nameof(is_parent));
}
public void remove_parent(OrderBookVM.BranchFilterSource new_branch_filter_source) {
_parent = null;
join_branch_filter_source(new_branch_filter_source);
refresh_row_passes_filter();
foreach (var p in _book_vm.grid_settings_manager.live_sorting_props)
RaisePropertyChanged(p);
_depth_level.refresh();
foreach (OrderBookRowVM child_row in _child_rows)
child_row._on_lineage_changed();
}
public void update_order(OrderRecordImmutable order) {
Log.assert(order.ParentKey == _order.ParentKey, "Parent Keys can change?");
Log.assert(order.Key == _order.Key, "Keys can change?");
var old_data = current_data;
_order = order;
if (_update_partial(_dynamic_render_cells))
raise_invalidated();
_show_order_modify_cmd.OnNext(status.value == OrderStatus.Working);
refresh_row_passes_filter();
updated?.Invoke((old_data, current_data));
}
public void update_security(SecurityMD security_md) {
var old_data = current_data;
var old_spec = _security.spec_or_default();
_security_md = security_md;
_symbol = _security_md.HasValue ? _security_md.Value.security.Symbol : null;
if (!Equals(old_spec, _security.spec_or_default())) {
_update_partial(_security_dependent_cells);
foreach (var cell_store in _price_cells)
cell_store.regenerate_cell();
raise_invalidated();
} else if (_update_partial(_security_dependent_cells)) {
raise_invalidated();
}
refresh_row_passes_filter();
updated?.Invoke((old_data, current_data));
}
public void refresh_row_passes_filter() {
row_passes_filter = _book_vm.columns.filter(this);
if (_branch_filter_source != null) {
_branch_filter_source.set_row_passes_filter(_order.Key, row_passes_filter);
} else {
_passes_filter.set(row_passes_filter);
}
}
public void raise_invalidated() => invalidated?.Invoke();
public bool Equals(OrderBookRowVM other) => other != null && other._order.Key == _order.Key;
public override bool Equals(object obj) => Equals(obj as OrderBookRowVM);
public override int GetHashCode() => (int)_order.Key;
public override string ToString() => $"{order_key} {last_change} {parent_order_key}";
protected override void Dispose(bool disposing) {
// idempotent
if (_branch_filter_source != null) {
_branch_filter_source.passes_filter_changed -= _passes_filter.set;
_branch_filter_source = null;
}
}
static IEnumerable<OrderBookRowVM> _descendents(OrderBookRowVM root) {
foreach (var child in root.child_orders) {
yield return child;
foreach (var grand_child in _descendents(child))
yield return grand_child;
}
}
static IOrderBookCellStore _cell_store_from_column(OrderBookRowVM row, Columns column) {
switch (column) {
case Columns.OrderKey: return row._order_key_store;
case Columns.ParentKey: return row._parent_order_key_store;
case Columns.SecurityKey: return row._security_key_store;
case Columns.Security: return row._security_store;
case Columns.Symbol: return row._symbol_store;
case Columns.Exchange: return row._exchange_store;
case Columns.OrderType: return row._order_type_store;
case Columns.Side: return row._side_store;
case Columns.User: return row._user_store;
case Columns.Account: return row._account_store;
case Columns.TimeInForce: return row._time_in_force_store;
case Columns.Time: return row._time_created_store;
case Columns.LastChange: return row._last_change_store;
case Columns.Status: return row._status_store;
case Columns.Price: return row._price_store;
case Columns.Size: return row._quantity_store;
case Columns.Filled: return row._filled_quantity_store;
case Columns.LastPrice: return row._last_price_store;
case Columns.AvgFilled: return row._avg_price_store;
case Columns.LastMessage: return row._last_msg_store;
case Columns.SubType: return row._order_sub_type_store;
default: throw new ArgumentException(nameof(column));
}
}
// Note: this method assumes that lineage exists (i.e. _parent is not null).
void _on_lineage_changed() {
_depth_level.refresh();
// parent 'branch_filter_source' can be null:
// if the parent is itself an orphan - meaning this is the middle of an update -
// the final branch-filter-root will be determined after all new orders have been added
if (_parent._branch_filter_source != null)
join_branch_filter_source(_parent._branch_filter_source);
_visible.set(_parent.is_visible && _parent.is_expanded);
// refresh the sort by calling regenerate_cell() for each live-sorting-columns corresponding cell-store
foreach (Columns column in _book_vm.live_sorting_columns)
_cell_store_from_column(this, column).regenerate_cell();
// finally, repeat for each child-row
foreach (var child_row in _child_rows)
child_row._on_lineage_changed();
}
bool _update_partial(IEnumerable<IOrderBookCellStore> target_cell_stores) {
bool updated = false;
foreach (var cell_store in target_cell_stores) {
if (cell_store.refresh()) {
updated = true;
if (_book_vm.live_sorting_columns.Contains(cell_store.column.key)) {
// refresh the sort by calling regenerate_cell() for each descendent-row
foreach (OrderBookRowVM dr in _descendents(this))
cell_store.select_other(dr).regenerate_cell();
}
}
}
return updated;
}
string _fmt_price(double v) => security.HasValue ?
security.Value.ContractSpec.format(v) :
Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string);
}
}
@@ -1,220 +1,74 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.shell;
using mbts.collections;
using bts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using static bts.shell.OrderBookWindowFactory;
using static mbts.spark.OrderBookView;
namespace mbts.spark {
partial class OrderBookVM : DisposableViewModelBase, IHandleRowSelection {
readonly LiveSortingColumKeys _live_sorting_columns;
namespace mbts.spark {
partial class OrderBookVM : ViewModelBase, IDisposable, IHandleRowSelection, IHandleGridSorting, IWillLetYouKnowWhenIDispose {
readonly IBus _bus;
readonly OrdersModel _model;
readonly Property<OrderBookRowVM> _current_row;
readonly OrderBookRowCollection _row_collection;
readonly ObservableCollection<OrderBookRowVM> _selected_rows = new ObservableCollection<OrderBookRowVM>();
readonly OrderBookColumnCollection _columns;
readonly List<IDisposable> _resources;
OrderBookStartupData _state;
Dictionary<uint, OrderBookRowVM> _order_rows_cache = new Dictionary<uint, OrderBookRowVM>();
Dictionary<uint, BranchFilterSource> _branch_filter_roots = new Dictionary<uint, BranchFilterSource>();
ObservableCollection<OrderBookRowVM> _order_rows = new ObservableCollection<OrderBookRowVM>();
ObservableCollection<OrderBookRowVM> _selected_rows = new ObservableCollection<OrderBookRowVM>();
SetMap<uint, uint> _parent_to_children = new SetMap<uint, uint>();
SetMap<uint, uint> _security_orders = new SetMap<uint, uint>();
public OrderBookVM(IObservable<string> owner_title, IBus bus, INotificationService notification_service, OrdersModel model) {
var order_securities_subject = new Subject<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)>();
columns = new OrderBookColumnCollection(bus, model, order_securities_subject);
rows_view = CollectionViewSource.GetDefaultView(_order_rows);
rows_view.Filter = obj => obj is OrderBookRowVM vm && vm.is_visible && vm.passes_filter;
columns.filter_changed += () => {
foreach (var vm in _order_rows)
vm.refresh_row_passes_filter();
};
var cvls = (ICollectionViewLiveShaping)rows_view;
cvls.IsLiveFiltering = true;
cvls.IsLiveSorting = true;
cvls.LiveFilteringProperties.AddRange(nameof(OrderBookRowVM.is_visible), nameof(OrderBookRowVM.passes_filter));
_bus = bus;
_model = model;
_columns = new OrderBookColumnCollection(bus, model, model.on_order_securities.Select(u => (u.added.Values.Select(smd => smd.security), u.removed.Values.Select(smd => smd.security))));
_row_collection = new OrderBookRowCollection(ort => new OrderBookRowVM(this, ort), _columns.get_comparer_data().comp) { filter = _columns.get_filter() };
_current_row = backing<OrderBookRowVM>(nameof(current_row));
collapse_all_rows_command = new DelegateCommand(
() => {
foreach (var r in _order_rows.Where(r => r.is_visible && r.passes_filter))
r.is_expanded = false;
});
expand_all_rows_command = new DelegateCommand(
() => {
foreach (var r in _order_rows.Where(r => r.is_visible && r.passes_filter))
r.is_expanded = true;
});
grid_settings_manager = _create_grid_settings_manager(owner_title, bus, notification_service, model, _order_rows, rows_view, columns);
_live_sorting_columns = new LiveSortingColumKeys(grid_settings_manager.live_sorting_props);
SetMap<uint, uint> missing_security_orders = new SetMap<uint, uint>();
IReadOnlyDictionary<uint, SecurityMD> security_dict = new Dictionary<uint, SecurityMD>();
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(on_securities),
model.on_orders.OnDispatcher().Subscribe(on_orders),
grid_settings_manager,
columns,
order_securities_subject);
void on_orders(TableUpdate<OrderRecordImmutable, uint> table) {
// clear everything (most likely the server restarted)
if (table.removed.Count() == _order_rows.Count && !table.added.Any()) {
_selected_rows.Clear();
_order_rows.DisposeAll();
_order_rows.Clear();
_order_rows_cache.Clear();
_branch_filter_roots.Clear();
_parent_to_children.clear();
_security_orders.clear();
missing_security_orders.clear();
Log.Ui.warn("OrderBook received reset message.");
return;
}
var added_securities = new List<SecurityImmutable>(1);
var removed_securities = new List<SecurityImmutable>(1);
foreach (var o in table.removed) {
if (_order_rows_cache.TryPopValue(o.Key, out OrderBookRowVM row)) {
row.Dispose();
_order_rows.Remove(row);
if (_security_orders.removes_key(o.Def.SecurityKey, o.Key)) {
if (row.security.value.HasValue)
removed_securities.Add(row.security.value.Value);
}
if (o.has_parent()) {
_parent_to_children.remove(o.ParentKey, o.Key);
if (row.parent != null) {
row.parent.remove_child_order(row);
} else {
_branch_filter_roots.Remove(o.Key);
}
} else {
_branch_filter_roots.Remove(o.Key);
}
// the child_rows will most-likely be removed in this update, but we can't be sure,
// until that happens they must serve as tempororay branch-filter-roots
foreach (var child_row in row.child_orders) {
var bfs = new BranchFilterSource();
child_row.remove_parent(bfs);
_branch_filter_roots.Add(child_row.order.Key, bfs);
}
missing_security_orders.remove(o.Key);
_columns.filter_changed += on_filter_changed;
collapse_all_rows_command = new DelegateCommand(() => set_all_is_expanded(false));
expand_all_rows_command = new DelegateCommand(() => set_all_is_expanded(true));
_resources = new List<IDisposable> {
model.on_order_tuples_table.OnDispatcher().Subscribe(_row_collection.update),
(grid_settings_manager = _create_grid_settings_manager(owner_title, bus, notification_service, model, columns)),
Disposable.Create(() => {
_columns.filter_changed -= on_filter_changed;
Disposable.dispose(_row_collection);
}),
_columns
};
// local methods
void set_all_is_expanded(bool is_expanded) {
using (_row_collection.defer_refresh()) {
foreach (var r in _row_collection.all_rows) {
r.is_expanded = is_expanded;
r.is_visible = is_expanded || !r.is_child;
}
}
foreach (var ch in table.changes)
_order_rows_cache[ch.New.Key].update_order(ch.New);
var orphans = new Dictionary<uint, OrderBookRowVM>();
foreach (var o in table.added) {
SecurityMD? security_md;
if (security_dict.TryGetValue(o.Def.SecurityKey, out SecurityMD smd)) {
security_md = smd;
if (_security_orders.adds_key(o.Def.SecurityKey, o.Key))
added_securities.Add(security_md.Value.security);
} else {
missing_security_orders.add(o.Def.SecurityKey, o.Key);
security_md = null;
_security_orders.add(o.Def.SecurityKey, o.Key);
}
OrderBookRowVM row = new OrderBookRowVM(bus, this, model, o, security_md);
if (!o.has_parent()) {
// if it doesn't have a parent, it must be a root; create a new BranchFilterSource
var bfs = new BranchFilterSource();
_branch_filter_roots.Add(o.Key, bfs);
row.join_branch_filter_source(bfs);
} else {
_parent_to_children.add(o.ParentKey, o.Key);
if (_order_rows_cache.TryGetValue(o.ParentKey, out OrderBookRowVM pvm)) {
pvm.add_child_order(row);
} else {
// (**) look for orphans' parents again after all new orders have been added to _order_vm_cache
// don't create a temporary BranchFilterSource root just yet. (**)
orphans.Add(o.Key, row);
_order_rows_cache.Add(o.Key, row);
try_add_children(row);
continue;
}
}
_order_rows_cache.Add(o.Key, row);
_order_rows.Add(row);
try_add_children(row);
}
// (**) since all new rows have been added by now, any remaining orphans will be assigned their own branch-filter-roots
// (usually, rows are tempororily added to orphans bc their parent is just behind them in the list of added orders) (**)
foreach (OrderBookRowVM row in orphans.Values) {
var bfs = new BranchFilterSource();
row.join_branch_filter_source(bfs);
_branch_filter_roots.Add(row.order.Key, bfs);
_order_rows.Add(row);
}
if (added_securities.Count > 0 || removed_securities.Count > 0)
order_securities_subject.OnNext((added_securities, removed_securities));
void try_add_children(OrderBookRowVM row) {
if (_parent_to_children.try_lookup(row.order.Key, out ISet<uint> children))
foreach (uint child_key in children) {
OrderBookRowVM child_vm = _order_rows_cache[child_key];
// (**) if children arrived in an earlier update, this will notify them that their parent has arrived (**)
// - their tempororary branch-filter-roots will be removed, and they will join that of their parent's
// - for the live-filter-properties, their corresponding cells will be regenerated and they will be re-inserted beneath their new parent.
row.add_child_order(child_vm);
if (orphans.Remove(child_key))
_order_rows.Add(child_vm);
else {
_order_rows.Remove(child_vm);
_order_rows.Add(child_vm);
}
}
}
}
// I assume we don't need to worry about orders "losing" or "changing" their security
// once the order vm discovers its security (by id), it will never change.
void on_securities(IReadOnlyDictionary<uint, SecurityMD> securities) {
security_dict = securities;
var added_securities = new List<SecurityImmutable>(); // assume securities won't be removed
foreach (var missing_sec_orders in missing_security_orders.ToList()) {
if (securities.TryGetValue(missing_sec_orders.Key, out SecurityMD smd)) {
missing_security_orders.remove(missing_sec_orders.Key);
added_securities.Add(smd.security);
foreach (var order_key in missing_sec_orders) {
var vm = _order_rows_cache[order_key];
vm.update_security(smd);
}
}
}
if (added_securities.Count > 0)
order_securities_subject.OnNext((added_securities, new List<SecurityImmutable>(0)));
}
void on_filter_changed() =>
_row_collection.filter = _columns.get_filter();
}
public event Action<OrderRecordImmutable?> selected_order_changed;
public event Action<bool> OnDisposed;
public OrderBookColumnCollection columns { get; }
public ISet<Columns> live_sorting_columns => _live_sorting_columns;
public ICollectionView rows_view { get; }
public ObservableCollection<DIYGrid.ColumnBase> columns => _columns;
public ObservableCollection<OrderBookRowVM> rows => _row_collection;
public OrderBookRowVM current_row { get => _current_row.Value; set => _current_row.Value = value ?? _selected_rows.FirstOrDefault(); }
public OrderRecordImmutable? current_order => current_row?.order;
public IEnumerable<OrderRecordImmutable> selected_orders => _selected_rows.Select(r => r.order);
public GridSettingsManager<OrderBookRowVM, OrderRecordTuple, INotificationServiceDataCache, OrderRecordTuplePredicate> grid_settings_manager { get; }
public ICommand collapse_all_rows_command { get; }
public ICommand expand_all_rows_command { get; }
@@ -226,25 +80,63 @@ namespace mbts.spark {
public OrderBookStartupData create() {
var (grid, animations) = grid_settings_manager.create();
return new OrderBookStartupData(columns.create(), grid, animations.Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_builder, a.cell_animations, a.row_animations, a.sound_notifications)));
return new OrderBookStartupData(_columns.create(), grid, animations.Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_builder, a.cell_animations, a.row_animations, a.sound_notifications)));
}
public void load_from(OrderBookStartupData state) {
if (state == null) return;
_state = state;
grid_settings_manager.load_from((state.grid, state.predicate_animations));
columns.load_from(state.filters);
_columns.load_from(state.filters);
}
internal void remove_branch_filter_root(uint key) =>
_branch_filter_roots.Remove(key);
protected override void Dispose(bool disposing) =>
Disposable.dispose(_order_rows);
public void on_sorting(object sender, DIYGridSortingEventArgs e) {
if (e.Column is ICVOrderBookColumn col) {
e.Handled = true;
_columns.on_sorting(col, !KeyboardExtensions.IsShiftDown());
(var comp, var desc) = _columns.get_comparer_data();
Log.Ui.info($"{nameof(OrderBookRowVM)} begin resort: {desc}");
_row_collection.comparer = comp;
} else {
Log.Ui.warn($"{nameof(OrderBookVM)} failed to process sorting event: Column was not of type {nameof(ICVOrderBookColumn)}");
}
}
internal void show_order_modify(OrderBookRowVM row) =>
_bus.post(SparkTags.ShowModifyOrderTag, row.order_key);
internal void on_expanded_changed(OrderBookRowVM row) {
using (_row_collection.defer_refresh(true)) {
if (row.is_expanded) {
_on_expanded(row);
} else {
_on_collapsed(row);
}
}
}
void _on_expanded(OrderBookRowVM row) {
foreach (var node in _row_collection.get_inner_nodes(row)) {
node.value.is_visible = true;
if (node.value.is_expanded)
_on_expanded(node.value);
}
}
void _on_collapsed(OrderBookRowVM row) {
foreach (var dr in _row_collection.get_descendent_rows(row))
dr.is_visible = false;
}
public OrderMetadata get_metadata(OrderBookRowVM row) => _model.factory.get_metadata(row.order_type);
public void Dispose() {
Disposable.dispose(_resources);
OnDisposed?.Invoke(true);
}
static GridSettingsManager<OrderBookRowVM, OrderRecordTuple, INotificationServiceDataCache, OrderRecordTuplePredicate> _create_grid_settings_manager(
IObservable<string> owner_title, IBus bus, INotificationService notification_service, OrdersModel model,
ObservableCollection<OrderBookRowVM> rows, ICollectionView rows_view, ObservableCollection<DIYGrid.ColumnBase> columns) {
IObservable<string> owner_title, IBus bus, INotificationService notification_service, OrdersModel model, ObservableCollection<DIYGrid.ColumnBase> columns) {
// make font-weight immutable for all columns (the font-weight rule is hard-coded: Regular for root-orders, Light for all others)
// TODO: Remove the immutable font-weight flags when cell animation is ready
var col_settings_flags = EnumHelper.get_values<Columns>().ToDictionary(
@@ -255,7 +147,7 @@ namespace mbts.spark {
col_settings_flags[c.ToString()] = GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableFontWeight;
}
return new GridSettingsManager<OrderBookRowVM, OrderRecordTuple, INotificationServiceDataCache, OrderRecordTuplePredicate>(
owner_title, bus, notification_service, model, rows, rows_view, columns,
owner_title, bus, notification_service, model, columns,
() => {
var pvm = PredicateBuilderVMWrapper.create<OrderRecordTuple, OrderRecordTuplePredicate, OrderRecordTuplePredicate.PredicateTypeOneofCase>(
OrderRecordTuplePredicateVMFactory.get_oneofs(bus, model), rp => rp.predicate_type_case);
@@ -295,84 +187,5 @@ namespace mbts.spark {
default: return default;
}
}
internal class BranchFilterSource {
readonly HashSet<uint> _orders_pass_filter = new HashSet<uint>();
public event Action<bool> passes_filter_changed;
public bool passes_filter => _orders_pass_filter.Count > 0;
public void set_row_passes_filter(uint key, bool value) {
if (value) {
if (_orders_pass_filter.Add(key) && _orders_pass_filter.Count == 1)
passes_filter_changed?.Invoke(value);
} else if (_orders_pass_filter.Remove(key) && _orders_pass_filter.Count == 0) {
passes_filter_changed?.Invoke(value);
}
}
}
class LiveSortingColumKeys : HashSet<Columns> {
public LiveSortingColumKeys(ObservableCollection<string> live_sorting_props) {
_add_items(live_sorting_props);
live_sorting_props.CollectionChanged += (s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: _add_items(e.NewItems); break;
case NotifyCollectionChangedAction.Remove: _remove_items(e.OldItems); break;
case NotifyCollectionChangedAction.Replace:
_remove_items(e.OldItems);
_add_items(e.NewItems);
break;
case NotifyCollectionChangedAction.Reset:
Clear();
_add_items(live_sorting_props);
break;
}
};
}
public static bool try_parse(string prop_name, out Columns result) {
switch (prop_name) {
case nameof(OrderBookRowVM.security): result = Columns.Security; break;
case nameof(OrderBookRowVM.symbol): result = Columns.Symbol; break;
case nameof(OrderBookRowVM.time_created): result = Columns.Time; break;
case nameof(OrderBookRowVM.last_change): result = Columns.LastChange; break;
case nameof(OrderBookRowVM.user): result = Columns.User; break;
case nameof(OrderBookRowVM.account): result = Columns.Account; break;
case nameof(OrderBookRowVM.exchange): result = Columns.Exchange; break;
case nameof(OrderBookRowVM.time_in_force): result = Columns.TimeInForce; break;
case nameof(OrderBookRowVM.order_type): result = Columns.OrderType; break;
case nameof(OrderBookRowVM.order_sub_type): result = Columns.SubType; break;
case nameof(OrderBookRowVM.side): result = Columns.Side; break;
case nameof(OrderBookRowVM.quantity): result = Columns.Size; break;
case nameof(OrderBookRowVM.filled_quantity): result = Columns.Filled; break;
case nameof(OrderBookRowVM.price): result = Columns.Price; break;
case nameof(OrderBookRowVM.avg_price): result = Columns.AvgFilled; break;
case nameof(OrderBookRowVM.last_price): result = Columns.LastPrice; break;
case nameof(OrderBookRowVM.status): result = Columns.Status; break;
case nameof(OrderBookRowVM.last_msg): result = Columns.LastMessage; break;
case nameof(OrderBookRowVM.security_key): result = Columns.SecurityKey; break;
case nameof(OrderBookRowVM.order_key): result = Columns.OrderKey; break;
case nameof(OrderBookRowVM.parent_order_key): result = Columns.ParentKey; break;
default: result = default; return false;
}
return true;
}
void _add_items(IList prop_names) {
foreach (string pn in prop_names) {
if (try_parse(pn, out Columns c))
Add(c);
}
}
void _remove_items(IList prop_names) {
foreach (string pn in prop_names) {
if (try_parse(pn, out Columns c))
Remove(c);
}
}
}
}
}
@@ -48,7 +48,7 @@
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="False"/>
<Condition Binding="{Binding status.value}" Value="{uc:Enum Working, Type=order:OrderStatus}"/>
<Condition Binding="{Binding status}" Value="{uc:Enum Working, Type=order:OrderStatus}"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Background" Value="{x:Static Member=working_order_background_brush, MemberType={uc:Nested uc:BTSColors.Orders}}"/>
@@ -67,7 +67,7 @@
Grid.Row="2"
Columns="{Binding columns}"
CurrentRow="{Binding current_row, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Rows="{Binding rows_view}"
Rows="{Binding rows}"
RowStyle="{StaticResource {x:Static sp:OrderBookView.RowStyleKey}}"
RowTemplate="{StaticResource {x:Static sp:OrderBookView.RowTemplateKey}}"
SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}"
@@ -29,6 +29,12 @@ namespace mbts.utils {
public static IComparer<TOutter> wrap<TInner, TOutter>(this IComparer<TInner> inner_comparer, Func<TOutter, TInner> selector) =>
Comparer<TOutter>.Create((a, b) => inner_comparer.Compare(a == null ? default : selector(a), b == null ? default : selector(b)));
public static IComparer<T?> to_nullable<T>(this IComparer<T> comparer) where T : struct =>
Comparer<T?>.Create(nullable_comparison<T>(comparer.Compare));
public static IComparer<T> reverse<T>(this IComparer<T> comparer) =>
Comparer<T>.Create((a, b) => comparer.Compare(b, a));
class NonGenericComparerWrapper<T> : IComparer {
readonly IComparer<T> _comparer;
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
namespace mbts.utils {
class ComparerBuilder<T> {
public readonly List<IComparer<T>> _comparers_list;
public ComparerBuilder() =>
_comparers_list = new List<IComparer<T>>(2);
public ComparerBuilder(IEnumerable<IComparer<T>> comparers) =>
_comparers_list = new List<IComparer<T>>(comparers);
public void add(IComparer<T> comparer) =>
_comparers_list.Add(comparer);
public void add<TValue>(Func<T, TValue> get) =>
add(get, Comparer<TValue>.Default);
public void add<TValue>(Func<T, TValue> get, IComparer<TValue> comparer) =>
add(CompareUtils.wrap(comparer, get));
public void clear() =>
_comparers_list.Clear();
public IComparer<T> to_comparer() => new _Comparer(_comparers_list.ToArray());
class _Comparer : IComparer<T> {
readonly IComparer<T>[] _comparers;
public _Comparer(IComparer<T>[] comparers) =>
_comparers = comparers;
public int Compare(T x, T y) {
foreach (var comp in _comparers) {
int result = comp.Compare(x, y);
if (result != 0)
return result;
}
return 0;
}
}
}
}
@@ -10,7 +10,6 @@ using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Media;
@@ -22,14 +21,10 @@ namespace mbts.ui {
where TRow : IRowVM
where TPredicateBuilder : IPredicateBuilder<TRowData, TPredicateBuilderArg>, new() {
//
public readonly ObservableCollection<string> live_sorting_props;
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly INotificationService _notification_service;
readonly List<IDisposable> _resources, _notification_subs = new List<IDisposable>();
readonly ObservableCollection<TRow> _rows;
readonly ICollectionView _rows_view;
readonly ObservableCollection<ColumnBase> _columns;
readonly Property<GridSettings> _grid_settings;
readonly DelegateProperty<FontFamily> _font_family;
@@ -41,15 +36,13 @@ namespace mbts.ui {
IEnumerable<IPredicateAnimationsData<TRowData, TPredicateBuilder>> _predicate_animations_data;
public GridSettingsManager(
IObservable<string> owner_title, IBus bus, INotificationService notification_service, OrdersModel orders_model, ObservableCollection<TRow> rows,
ICollectionView rows_view, ObservableCollection<ColumnBase> columns, Func<IPropertyWrapperVM<TPredicateBuilder>> create_predicate_vm,
IObservable<string> owner_title, IBus bus, INotificationService notification_service, OrdersModel orders_model,
ObservableCollection<ColumnBase> columns, Func<IPropertyWrapperVM<TPredicateBuilder>> create_predicate_vm,
Func<string, IPropertyWrapperVM<TPredicateBuilder>> create_column_predicate_vm, TPredicateBuilderArg arg, IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> column_flags = null) {
//
_bus = bus;
_notification_service = notification_service;
_orders_model = orders_model;
_rows = rows;
_rows_view = rows_view;
_columns = columns;
_arg = arg;
_grid_settings = backing(nameof(grid_settings), GridSettings.Default);
@@ -59,8 +52,6 @@ namespace mbts.ui {
_font_color = backing(nameof(font_color), () => grid_settings.font_color.rgb_solid_brush().frozen(), nameof(grid_settings));
_selection_highlight = backing(nameof(selection_highlight), () => grid_settings.selection_highlight.to_brush().frozen(), nameof(grid_settings));
_resources = new List<IDisposable> {
ObservableAutoWrapper.connect<SortDescriptionCollection, SortDescription, string>(
rows_view.SortDescriptions, live_sorting_props = ((ICollectionViewLiveShaping)rows_view).LiveSortingProperties, sd => sd.PropertyName),
(launch_settings_editor = new DialogCommand(create_settings_view))
};
Window create_settings_view() {
@@ -78,7 +69,6 @@ namespace mbts.ui {
vm.committed += () => {
var (grid, predicate_animations_data) = vm.create();
// IMPORTANT: don't overwrite current sorting
grid = grid.with(sorting_criterion: rows_view.get_sorting_criteria(columns));
load_from((grid, predicate_animations_data));
};
vm.RequestClose += (s, e) => WindowUtilities.force_close(window);
@@ -101,7 +91,7 @@ namespace mbts.ui {
public (GridSettings grid, IEnumerable<IPredicateAnimationsData<TRowData, TPredicateBuilder>> predicate_animations_data) create() {
// IMPORTANT: don't overwrite current sorting
_grid_settings.set(grid_settings.with(_columns.Select(c => c.create()), _rows_view.get_sorting_criteria(_columns)));
_grid_settings.set(grid_settings.with(_columns.Select(c => c.create())));
return (grid_settings, _predicate_animations_data);
}
@@ -111,7 +101,7 @@ namespace mbts.ui {
_grid_settings.set(grid);
foreach (ColumnBase col in _columns)
col.set_fallback_font_params(new FontFamily(grid.font_family), grid.font_size, grid.font_color.rgb_color(), grid.font_weight);
_rows_view.set_sort_descriptions(grid.sorting_criterion, _columns);
//_rows_view.set_sort_descriptions(grid.sorting_criterion, _columns);
_predicate_animations_data = value.predicate_animations_data;
_animation_defs.clear();
foreach (var pa in _predicate_animations_data) {
@@ -59,6 +59,12 @@ namespace mbts.spark {
public static SecurityImmutable? security(this SecurityMD? security_md) =>
security_md.HasValue ? new SecurityImmutable?(security_md.Value.security) : new SecurityImmutable?();
public static Venue exchange(this SecurityMD? security_md) =>
security_md.HasValue ? security_md.Value.security.Exchange : Venue.Unset;
public static string symbol(this SecurityMD? security_md) =>
security_md.HasValue ? security_md.Value.security.Symbol : "unknown";
public static async Task<SecurityImmutable> get_security_async(IBus bus, uint security_key) =>
await bus.subscribe(SparkTags.SecuritiesTag).Where(map => map.ContainsKey(security_key)).Select(map => map[security_key].security).FirstAsync();
@@ -24,6 +24,8 @@ namespace bts.collections {
}
}
public int Count => _size;
bool Contains(T item) {
return BinarySearch(item) >= 0;
}
@@ -57,6 +59,16 @@ namespace bts.collections {
return false;
}
public void Clear() {
Array.Clear(_values, 0, _values.Length);
_size = 0;
}
public bool TryGetIndex(T item, out int result) {
result = BinarySearch(item);
return result > 0;
}
public T this [int index] {
get {
return _values[index];
+52 -11
View File
@@ -2,11 +2,14 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace bts.collections {
interface INode<T> {
T value { get; }
IEnumerable<INode<T>> inner { get; }
}
public class SortedTree<T, TKey> : IEnumerable<T> {
class SortedTree<T, TKey> : IEnumerable<T> {
readonly IComparer<Node> _comparer;
readonly Func<T, TKey> id;
readonly Func<T, TKey> parent;
@@ -57,10 +60,20 @@ namespace bts.collections {
}
}
}
public void Remove(T item) {
var item_id = id(item);
public void Replace(TKey key, Func<T, T> replace) {
Node node = _index[key];
SortedList<Node> node_list = _index.TryGetValue(parent(node.value), out Node pnode) ? pnode.children : _tree;
node_list.Remove(node);
node.value = replace(node.value);
node_list.Add(node);
}
public void Remove(T item) => Remove(id(item));
public void Remove(TKey item_id) {
if (_index.TryGetValue(item_id, out Node itemnode)) {
if (_index.TryGetValue(parent(item), out Node parentnode)) {
if (_index.TryGetValue(parent(itemnode.value), out Node parentnode)) {
parentnode.children.Remove(itemnode);
}
else {
@@ -95,6 +108,19 @@ namespace bts.collections {
}
}
public void Clear() {
foreach (Node n in _tree)
_clear_node(n);
_tree.Clear();
_index.Clear();
void _clear_node(Node n) {
foreach (Node cn in n.children)
_clear_node(cn);
n.children.Clear();
}
}
IEnumerable<T> iterate(SortedList<Node> nodes) {
foreach (var n in nodes) {
yield return n.value;
@@ -114,14 +140,27 @@ namespace bts.collections {
return null;
}
public INode<T> GetRootNode(TKey key) =>
_index.TryGetValue(key, out Node node) ? GetRootNode(node) : null;
Node GetRootNode(Node node) =>
_index.TryGetValue(parent(node.value), out Node pnode) ? GetRootNode(pnode) : node;
public IEnumerable<T> EnumerateGroup(T item) {
var pnode = parentmost(item);
if (pnode != null) {
yield return pnode.value;
foreach (var child in iterate(pnode.children)) {
yield return child;
}
return pnode == null ? Enumerable.Empty<T>() : EnumerateNode(pnode);
}
public IEnumerable<T> EnumerateInnerValues(T item) =>
iterate(_index[id(item)].children);
public IEnumerable<INode<T>> EnumerateInnerNodes(T item) =>
_index[id(item)].children;
IEnumerable<T> EnumerateNode(Node node) {
yield return node.value;
foreach (var child in iterate(node.children)) {
yield return child;
}
}
public IEnumerator<T> GetEnumerator() {
@@ -131,10 +170,12 @@ namespace bts.collections {
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
class Node {
class Node : INode<T> {
public Node(T i, IComparer<Node> c) { value = i; children = new SortedList<Node>(c); }
public T value;
public SortedList<Node> children;
T INode<T>.value => value;
IEnumerable<INode<T>> INode<T>.inner => children;
}
}
}