1230 lines
67 KiB
C#
1230 lines
67 KiB
C#
using bts;
|
|
using bts.api;
|
|
using bts.api.core;
|
|
using bts.api.orderman;
|
|
using bts.shell.orderbook;
|
|
using bts.utils;
|
|
using mbts.spark.filters;
|
|
using mbts.ui;
|
|
using mbts.ui.controls;
|
|
using mbts.ui.converters;
|
|
using mbts.ui.spark;
|
|
using mbts.ui.utility;
|
|
using mbts.ui.utility.text;
|
|
using mbts.ui.utilities;
|
|
using mbts.utils;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.ComponentModel;
|
|
using System.Linq;
|
|
using System.Reactive.Linq;
|
|
using System.Windows;
|
|
using System.Windows.Controls;
|
|
using System.Windows.Controls.Primitives;
|
|
using System.Windows.Data;
|
|
using System.Windows.Media;
|
|
using Columns = mbts.spark.OrderBookGridView.ColumnKeys;
|
|
using static mbts.ui.controls.DIYGrid;
|
|
using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
|
|
using System.Windows.Input;
|
|
using System.Reactive.Disposables;
|
|
|
|
namespace mbts.spark {
|
|
// This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup.
|
|
interface ICVOrderBookColumn : IKeyedColumn<Columns>, IGridColumn {
|
|
ListSortDirection? SortDirection { get; set; }
|
|
IDataGridColumnFilter<OrderSecurity> filter { get; }
|
|
IComparer<OrderBookRowVM> comparer { get; }
|
|
}
|
|
|
|
class OrderBookSortingData : IEquatable<OrderBookSortingData> {
|
|
public readonly IReadOnlyList<SortingCriteria> sorting_criterion;
|
|
public readonly IComparer<OrderBookRowVM> comparer;
|
|
public readonly string desc;
|
|
|
|
public OrderBookSortingData(IEnumerable<ICVOrderBookColumn> column_sorting_hierarchy) {
|
|
var comp_builder = new ComparerBuilder<OrderBookRowVM>();
|
|
foreach (var col in column_sorting_hierarchy)
|
|
comp_builder.add(col.SortDirection.Value == ListSortDirection.Ascending ? col.comparer : col.comparer.reverse());
|
|
if (!column_sorting_hierarchy.Any(col => col.key == Columns.OrderKey)) {
|
|
// the resultant comparer must to be 100% deterministic, as SortedList (the building block of the SortedTree) uses a BinarySearch to find/remove items and does NOT check for item-equality.
|
|
comp_builder.add(Comparer<OrderBookRowVM>.Create((l, r) => l.order_key.CompareTo(r.order_key)));
|
|
}
|
|
comparer = comp_builder.to_comparer();
|
|
sorting_criterion = column_sorting_hierarchy.Select(col => new SortingCriteria(col.id, col.SortDirection.GetValueOrDefault() == ListSortDirection.Ascending)).ToArray();
|
|
desc = string.Join(", ", sorting_criterion);
|
|
}
|
|
|
|
public bool Equals(OrderBookSortingData other) => other != null && EqualityComparer.safe_sequence_equals(sorting_criterion, other.sorting_criterion);
|
|
public override bool Equals(object obj) => base.Equals(obj);
|
|
public override int GetHashCode() => EqualityComparer.aggregate_hash(sorting_criterion);
|
|
public override string ToString() => desc;
|
|
}
|
|
|
|
partial class OrderBookVM {
|
|
public class OrderBookColumnCollection : ObservableCollection<ColumnBase>, IValueFactory<(FilterStates filters, IReadOnlyList<SortingCriteria> sorting)>, IDisposable {
|
|
readonly List<ICVOrderBookColumn> _active_comparers = new List<ICVOrderBookColumn>();
|
|
CompositeDisposable _resources = new CompositeDisposable();
|
|
|
|
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
|
|
// security
|
|
Add(security_column = new SecurityColumn(
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, SecurityImmutable, SecurityCriteria>(
|
|
order_securities,
|
|
ort => ort.security ?? SecurityDataHelper.Defaults.SecurityImmutable,
|
|
SecurityCriteria.from_securities,
|
|
SecurityCriteria.get_to_securities(bus),
|
|
nameof(OrderBookRowVM.security),
|
|
EqualityComparer.Create<SecurityImmutable, uint>(s => s.Id),
|
|
SecurityHelper.Comparer.InstanceImmutable
|
|
)));
|
|
// symbol
|
|
Add(symbol_column = new SimpleTextColumn<string[]>(
|
|
Columns.Symbol,
|
|
DefaultColumnHeaders.Symbol,
|
|
r => r.symbol,
|
|
DefaultColumnWidths.Symbol,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, string>(
|
|
mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(),
|
|
ort => ort.security?.Symbol ?? string.Empty,
|
|
nameof(OrderBookRowVM.symbol)
|
|
),
|
|
DataGridFilterKnownTemplates.DiscreteValues,
|
|
_wrap_comparer(r => r.symbol)));
|
|
// time_created
|
|
Add(time_created_column = new SimpleTextColumn<TimeFilterTuple>(
|
|
Columns.Time,
|
|
"Time",
|
|
r => r.time_created_text,
|
|
DefaultColumnWidths.Time,
|
|
new TimeFilterVM<OrderSecurity>(
|
|
ort => ort.order.created(),
|
|
nameof(OrderBookRowVM.time_created)),
|
|
DataGridFilterKnownTemplates.TimeFilter,
|
|
_wrap_comparer(r => r.time_created)));
|
|
// last_change
|
|
Add(last_change_column = new SimpleTextColumn<TimeFilterTuple>(
|
|
Columns.LastChange,
|
|
"Last Change",
|
|
r => r.last_change_text,
|
|
DefaultColumnWidths.Time,
|
|
new TimeFilterVM<OrderSecurity>(
|
|
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,
|
|
r => r.user,
|
|
DefaultColumnWidths.User,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, string>(
|
|
model.factory.subscribe_users().Select(d => d.Values),
|
|
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,
|
|
r => r.account,
|
|
DefaultColumnWidths.Account,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, string, string[]>(
|
|
model.factory.subscribe_accounts().Select(d => d.Values),
|
|
ort => ort.order.account(),
|
|
vals => vals.ToArray(),
|
|
vals => Observable.Return(vals),
|
|
nameof(OrderBookRowVM.account)),
|
|
DataGridFilterKnownTemplates.DiscreteValues,
|
|
_wrap_comparer(r => r.account)));
|
|
// exchange
|
|
Add(exchange_column = new SimpleTextColumn<Venue[]>(
|
|
Columns.Exchange,
|
|
DefaultColumnHeaders.Exchange,
|
|
r => r.exchange.ToString(),
|
|
DefaultColumnWidths.Exchange,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, Venue>(
|
|
EnumHelper.get_values_except(Venue.Unset).ToList(),
|
|
ort => ort.security.exchange_or_default(),
|
|
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,
|
|
r => r.time_in_force.ToString(),
|
|
DefaultColumnWidths.TimeInForce,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, TimeInForce>(
|
|
EnumHelper.get_values<TimeInForce>().ToList(),
|
|
ort => ort.order.time_in_force(),
|
|
nameof(OrderBookRowVM.time_in_force)),
|
|
DataGridFilterKnownTemplates.EnumValues,
|
|
_wrap_comparer(r => r.time_in_force)));
|
|
// (algo items)
|
|
var algo_items_source = model.subscribe_all_algos().SelectKeyValue(AlgoDataVM.from_data, d => AlgoID.from_algo_key(d.data.key)).OnDispatcher();
|
|
var algo_items_comp = AlgoCollectionHelper.algo_data_vm_comparer.to_non_generic();
|
|
var algo_items_group_desc = new PropertyGroupDescription(nameof(AlgoDataVM.group));
|
|
// order type
|
|
Add(order_type_column = new OrderBookOrderTypeColumn(
|
|
Columns.OrderType,
|
|
nameof(OrderBookRowVM.badge_fill),
|
|
nameof(OrderBookRowVM.display_name),
|
|
_wrap_comparer(r => r.order_type),
|
|
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurity, AlgoDataVM, AlgoID>(
|
|
o => new AlgoDataVM(o.algo.GetValueOrDefault()),
|
|
vm => AlgoID.from_algo_key(vm.data.key), out var order_type_filter_observer, out var order_type_items_view)));
|
|
_resources.Add(algo_items_source.Subscribe(order_type_filter_observer));
|
|
order_type_items_view.CustomSort = algo_items_comp;
|
|
order_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
|
|
// root algo type
|
|
Add(root_algo_type_column = new OrderBookOrderTypeColumn(
|
|
Columns.RootAlgoType,
|
|
nameof(OrderBookRowVM.root_algo_badge_fill),
|
|
nameof(OrderBookRowVM.root_algo_display_name),
|
|
_wrap_comparer(r => r.order_tuple.root_algo.value.CustomCase),
|
|
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurity, AlgoDataVM, AlgoID>(
|
|
o => new AlgoDataVM(o.root_algo),
|
|
vm => AlgoID.from_algo_key(vm.data.key), out var root_algo_type_observer, out var root_algo_type_items_view),
|
|
DefaultColumnHeaders.RootAlgoType));
|
|
_resources.Add(algo_items_source.Subscribe(root_algo_type_observer));
|
|
root_algo_type_items_view.CustomSort = algo_items_comp;
|
|
root_algo_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
|
|
// order sub type
|
|
Add(sub_type_column = new SimpleTextColumn<OrderSubType[]>(
|
|
Columns.SubType,
|
|
"Sub Type",
|
|
r => r.order_sub_type_text,
|
|
80,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, OrderSubType>(
|
|
EnumHelper.get_values<OrderSubType>().ToList(),
|
|
ort => ort.order.sub_type(),
|
|
nameof(OrderBookRowVM.order_sub_type)),
|
|
OrderBookGridView.SubTypeFilterTemplateKey,
|
|
_wrap_comparer(r => r.order_sub_type)));
|
|
// side
|
|
Add(side_column = new SideColumn(
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, Side>(
|
|
new[] { Side.Buy, Side.Sell },
|
|
ort => ort.order.side(),
|
|
nameof(OrderBookRowVM.side))));
|
|
// quantity
|
|
Add(qty_column = new SizeColumn(
|
|
new UIntMinMax<OrderSecurity>(ort => ort.order.quantity(), nameof(OrderBookRowVM.quantity))));
|
|
// edit quantity column
|
|
// not usually part of the main order book, but it's useful to add it
|
|
// rather than debugging the popup window
|
|
//Add(edit_qty_column = new EditableQtyColumn());
|
|
// filled quantity
|
|
Add(filled_qty_column = new FilledColumn(
|
|
new UIntMinMax<OrderSecurity>(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
|
|
// price
|
|
Add(price_column = new SimpleTextColumn<DoubleMinMaxState>(
|
|
Columns.Price,
|
|
"Price",
|
|
r => r.price_text,
|
|
DefaultColumnWidths.Price,
|
|
new PriceMinMax<OrderSecurity>(
|
|
ort => ort.order.price(),
|
|
nameof(OrderBookRowVM.price)),
|
|
DataGridFilterKnownTemplates.DoubleMinMax,
|
|
_wrap_comparer(r => r.price)));
|
|
// edit price column
|
|
// not usually part of the main order book, but it's useful to add it
|
|
// rather than debugging the popup window
|
|
//Add(edit_price_column = new OrderBookVM.EditablePriceColumn());
|
|
//Add(new OrderBookVM.AttachColumn("DataContext.attach_vm"));
|
|
// avg filled price
|
|
Add(avg_price_column = new SimpleTextColumn<DoubleMinMaxState>(
|
|
Columns.AvgFilled,
|
|
"Avg Price",
|
|
r => r.avg_price_text,
|
|
DefaultColumnWidths.Price,
|
|
new PriceMinMax<OrderSecurity>(
|
|
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 SimpleTextColumn<DoubleMinMaxState>(
|
|
Columns.LastPrice,
|
|
"Last Filled",
|
|
r => r.last_price_text,
|
|
DefaultColumnWidths.Price,
|
|
new PriceMinMax<OrderSecurity>(
|
|
ort => ort.order.last_price(),
|
|
nameof(OrderBookRowVM.last_price)),
|
|
DataGridFilterKnownTemplates.DoubleMinMax,
|
|
_wrap_comparer(r => r.last_price)));
|
|
// piq
|
|
Add(piq_column = new PiqColumn(
|
|
new UIntMinMax<OrderSecurity>(ort => ort.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq))));
|
|
// status
|
|
Add(status_column = new SimpleTextColumn<OrderStatus[]>(
|
|
Columns.Status,
|
|
"Status",
|
|
r => r.status.ToString(),
|
|
80,
|
|
DiscreteValuesFilterVM.Create<OrderSecurity, OrderStatus>(
|
|
EnumHelper.get_values<OrderStatus>().ToList(),
|
|
ort => ort.order.status(),
|
|
nameof(OrderBookRowVM.status)),
|
|
DataGridFilterKnownTemplates.EnumValues,
|
|
_wrap_comparer(r => r.status)));
|
|
// last message
|
|
Add(last_message_column = new OrderBookLastMessageColumn(
|
|
new RegexFilterVM<OrderSecurity>(
|
|
ort => ort.order.last_msg(),
|
|
nameof(OrderBookRowVM.last_msg))));
|
|
// security key
|
|
Add(security_key_column = new SimpleTextColumn<string>(
|
|
Columns.SecurityKey,
|
|
DefaultColumnHeaders.SecurityKey,
|
|
r => r.security_key.ToString(),
|
|
DefaultColumnWidths.SecurityKey,
|
|
new RegexFilterVM<OrderSecurity>(
|
|
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,
|
|
r => r.order_key.ToString(),
|
|
DefaultColumnWidths.OrderKey,
|
|
new RegexFilterVM<OrderSecurity>(
|
|
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",
|
|
r => r.parent_order_key.ToString(),
|
|
DefaultColumnWidths.ParentKey,
|
|
new RegexFilterVM<OrderSecurity>(
|
|
ort => ort.order.ParentKey.ToString(),
|
|
nameof(OrderBookRowVM.parent_order_key)),
|
|
DataGridFilterKnownTemplates.Regex,
|
|
_wrap_comparer(r => r.parent_order_key)));
|
|
// attached target order key
|
|
Add(attached_target_order_key_column = new SimpleTextColumn<string>(
|
|
Columns.AttachedTargetOrderKey,
|
|
DefaultColumnHeaders.AttachedTargetOrderKey,
|
|
r => r.order.attached_target_order_key().ToString(),
|
|
DefaultColumnWidths.AttachedTargetOrderKey,
|
|
new RegexFilterVM<OrderSecurity>(
|
|
ort => ort.order.attached_target_order_key().ToString(),
|
|
nameof(OrderBookRowVM.parent_order_key)),
|
|
DataGridFilterKnownTemplates.Regex,
|
|
_wrap_comparer(r => r.order.attached_target_order_key())));
|
|
}
|
|
|
|
public event Action filter_changed;
|
|
|
|
public SecurityColumn security_column { get; }
|
|
public SimpleTextColumn<string[]> symbol_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; }
|
|
public SimpleTextColumn<TimeInForce[]> time_in_force_column { get; }
|
|
public OrderBookOrderTypeColumn order_type_column { get; }
|
|
public OrderBookOrderTypeColumn root_algo_type_column { get; }
|
|
public SimpleTextColumn<OrderSubType[]> sub_type_column { get; }
|
|
public SideColumn side_column { get; }
|
|
public SizeColumn qty_column { get; }
|
|
public EditableQtyColumn edit_qty_column { get; }
|
|
public SimpleTextColumn<DoubleMinMaxState> price_column { get; }
|
|
public FilledColumn filled_qty_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 SimpleTextColumn<string> attached_target_order_key_column { get; }
|
|
public PiqColumn piq_column { get; }
|
|
|
|
public FilterStates create_filter_states() =>
|
|
new FilterStates {
|
|
order_key_regex = order_key_column.filter.get_state(),
|
|
parent_key_regex = parent_key_column.filter.get_state(),
|
|
attached_target_order_key_regex = attached_target_order_key_column.filter.get_state(),
|
|
time_created = time_created_column.filter.get_state(),
|
|
users = user_column.filter.get_state(),
|
|
accounts = account_column.filter.get_state(),
|
|
exchanges = exchange_column.filter.get_state(),
|
|
tifs = time_in_force_column.filter.get_state(),
|
|
order_types = order_type_column.filter.get_state(),
|
|
root_algo_types = root_algo_type_column.filter.get_state(),
|
|
order_sub_types = sub_type_column.filter.get_state(),
|
|
sides = side_column.filter.get_state(),
|
|
qty = qty_column.filter.get_state(),
|
|
price = price_column.filter.get_state(),
|
|
qty_filled = filled_qty_column.filter.get_state(),
|
|
avg_price = avg_price_column.filter.get_state(),
|
|
last_price = last_price_column.filter.get_state(),
|
|
statuses = status_column.filter.get_state(),
|
|
exchange_message_regex = last_message_column.filter.get_state(),
|
|
last_change = last_change_column.filter.get_state(),
|
|
security_criteria = security_column.filter.get_state(),
|
|
symbols = symbol_column.filter.get_state(),
|
|
piq = piq_column.filter.get_state()
|
|
};
|
|
|
|
public (FilterStates filters, IReadOnlyList<SortingCriteria> sorting) create() =>
|
|
(create_filter_states(), get_sorting_data().sorting_criterion);
|
|
|
|
public void load_from((FilterStates filters, IReadOnlyList<SortingCriteria> sorting) state) {
|
|
if (state.filters is FilterStates fs) {
|
|
security_column.filter.load_state(fs.security_criteria);
|
|
symbol_column.filter.load_state(fs.symbols);
|
|
time_created_column.filter.load_state(fs.time_created);
|
|
user_column.filter.load_state(fs.users);
|
|
account_column.filter.load_state(fs.accounts);
|
|
price_column.filter.load_state(fs.price);
|
|
qty_column.filter.load_state(fs.qty);
|
|
filled_qty_column.filter.load_state(fs.qty_filled);
|
|
side_column.filter.load_state(fs.sides);
|
|
order_type_column.filter.load_state(fs.order_types);
|
|
root_algo_type_column.filter.load_state(fs.root_algo_types);
|
|
sub_type_column.filter.load_state(fs.order_sub_types);
|
|
time_in_force_column.filter.load_state(fs.tifs);
|
|
exchange_column.filter.load_state(fs.exchanges);
|
|
order_key_column.filter.load_state(fs.order_key_regex);
|
|
parent_key_column.filter.load_state(fs.parent_key_regex);
|
|
attached_target_order_key_column.filter.load_state(fs.attached_target_order_key_regex);
|
|
avg_price_column.filter.load_state(fs.avg_price);
|
|
last_price_column.filter.load_state(fs.last_price);
|
|
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);
|
|
piq_column.filter.load_state(fs.piq);
|
|
}
|
|
_active_comparers.Clear();
|
|
foreach (var col in this)
|
|
col.SortDirection = null;
|
|
if (state.sorting is IReadOnlyList<SortingCriteria> sorting) {
|
|
foreach (var sc in sorting) {
|
|
this.OfType<ICVOrderBookColumn>().ApplyToFirst(col => col.id.iequals(sc.col_name),
|
|
col => {
|
|
col.SortDirection = sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending;
|
|
_active_comparers.Add(col);
|
|
});
|
|
}
|
|
}
|
|
if (_active_comparers.Count == 0) {
|
|
// safeguard against empty sort, fallback to time-created
|
|
time_created_column.SortDirection = ListSortDirection.Descending;
|
|
_active_comparers.Add(time_created_column);
|
|
}
|
|
}
|
|
|
|
public Func<OrderSecurity, 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<OrderSecurity, bool>(r => active_filters.All(f => f.filter(r)));
|
|
}
|
|
|
|
public OrderBookSortingData get_sorting_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;
|
|
}
|
|
return new OrderBookSortingData(safe_active_comparers);
|
|
}
|
|
|
|
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() {
|
|
Disposable.dispose(ref _resources);
|
|
foreach (var col in this.OfType<ICVOrderBookColumn>())
|
|
(col.filter as IDisposable)?.Dispose();
|
|
Clear();
|
|
}
|
|
|
|
/// <see cref="OrderBookColumnCollection"/> ONLY supports sorting/filtering behavior for columns that implement <see cref="ICVOrderBookColumn"/>.
|
|
/// This is because OrderBook, unlike the other windows (as of 10/30/2018), does not use <see cref="ICollectionView"/> as the sorting/filtering model.
|
|
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);
|
|
}
|
|
}
|
|
|
|
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);
|
|
|
|
static KeyBinding _create_keyinput_binding(Key k, string command_path) {
|
|
var key_binding = new KeyBinding { Key = k };
|
|
BindingOperations.SetBinding(
|
|
key_binding,
|
|
InputBinding.CommandProperty,
|
|
new Binding { Path = new PropertyPath(command_path) }
|
|
);
|
|
return key_binding;
|
|
}
|
|
|
|
public abstract class OrderbookColumnBase<T> : ColumnBase<Columns>, IKeyedColumn<Columns>, IFilterableColumn, ICVOrderBookColumn {
|
|
ListSortDirection? _cached_sort_direction;
|
|
readonly string _filter_template;
|
|
protected readonly Func<OrderBookRowVM, string> _get_text;
|
|
GlyphContext _root_glyph_context, _child_glyph_context;
|
|
|
|
protected OrderbookColumnBase(Columns col_key, string header, Func<OrderBookRowVM, string> get_text, double width,
|
|
IDataGridColumnPersistentFilter<OrderSecurity, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
|
|
id = key.ToString();
|
|
Width = width;
|
|
Header = header;
|
|
_get_text = get_text;
|
|
this.filter = filter;
|
|
_filter_template = filter_template;
|
|
_cached_sort_direction = SortDirection;
|
|
this.comparer = comparer;
|
|
font_params_changed += refresh_glyph_contexts;
|
|
refresh_glyph_contexts();
|
|
void refresh_glyph_contexts() {
|
|
_root_glyph_context = GlyphContext.create(font_family, RenderUtils.root_font_weight);
|
|
_child_glyph_context = GlyphContext.create(font_family, RenderUtils.child_font_weight);
|
|
}
|
|
}
|
|
|
|
public IDataGridColumnPersistentFilter<OrderSecurity, T> filter { get; }
|
|
public IComparer<OrderBookRowVM> comparer { get; }
|
|
|
|
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
|
|
IDataGridColumnFilter IFilterableColumn.filter => filter;
|
|
string IFilterableColumn.filter_template => _filter_template;
|
|
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
|
|
|
|
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
|
|
_cached_sort_direction = new_value;
|
|
base.OnSortDirectionChanged(new_value);
|
|
}
|
|
protected GlyphContext _get_glyph_context(OrderBookRowVM row) => row.is_child ? _child_glyph_context : _root_glyph_context;
|
|
}
|
|
|
|
public class SimpleTextColumn<TFilterState> : OrderbookColumnBase<TFilterState>, IRenderColumn<OrderBookRowVM> {
|
|
public SimpleTextColumn(Columns key, string header, Func<OrderBookRowVM, string> get_text, double width,
|
|
IDataGridColumnPersistentFilter<OrderSecurity, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
|
|
: base(key, header, get_text, width, filter, filter_template, comparer) { }
|
|
|
|
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
|
|
CellRender.draw_text(dc, _get_glyph_context(row), font_size, _get_text(row), position, row_height,
|
|
RenderUtils.get_foreground(row, font_brush), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
|
|
}
|
|
|
|
#region Explicit Column Defs
|
|
public class SideColumn : OrderbookColumnBase<Side[]>, IRenderColumn<OrderBookRowVM> {
|
|
public SideColumn(IDataGridColumnPersistentFilter<OrderSecurity, Side[]> filter)
|
|
: base(Columns.Side, "B/S", r => r.side.ToString(), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues, _wrap_comparer(r => r.side)) { }
|
|
|
|
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
|
|
CellRender.draw_text(dc, _get_glyph_context(row), font_size, row.side.ToString(), position, row_height,
|
|
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
|
|
}
|
|
|
|
public class SizeColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
|
|
public SizeColumn(IDataGridColumnPersistentFilter<OrderSecurity, UIntMinMaxState> filter)
|
|
: base(Columns.Size, "Qty", r => r.quantity.ToString(), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.quantity)) { }
|
|
|
|
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
|
|
CellRender.draw_text(dc, _get_glyph_context(row), font_size, row.quantity.ToString(), position, row_height,
|
|
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
|
|
}
|
|
|
|
public class FilledColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
|
|
public FilledColumn(IDataGridColumnPersistentFilter<OrderSecurity, UIntMinMaxState> filter)
|
|
: base(Columns.Filled, "Filled Qty", r => r.filled_quantity.ToString(), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.filled_quantity)) { }
|
|
|
|
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
|
|
CellRender.draw_text(dc, _get_glyph_context(row), font_size, row.filled_quantity.ToString(), position, row_height,
|
|
RenderUtils.get_side_brush(row), null, horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
|
|
}
|
|
|
|
public class OrderBookOrderTypeColumn : OrderTypeColumn<Columns>, ICVOrderBookColumn {
|
|
readonly BindingBase _foreground_binding;
|
|
ListSortDirection? _cached_sort_direction;
|
|
|
|
public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer<OrderBookRowVM> row_comparer, IDataGridColumnPersistentFilter<OrderSecurity, AlgoID[]> filter, string header = DefaultColumnHeaders.OrderType)
|
|
: base(key, new Binding(badge_fill_binding_path), new Binding(display_name_binding_path), filter, header) {
|
|
id = key.ToString();
|
|
this.filter = filter;
|
|
font_weight_binding = RenderUtils.get_font_weight_binding();
|
|
_foreground_binding = RenderUtils.get_foreground_binding(this);
|
|
_cached_sort_direction = SortDirection;
|
|
this.comparer = row_comparer;
|
|
}
|
|
|
|
public new IDataGridColumnPersistentFilter<OrderSecurity, AlgoID[]> filter { get; }
|
|
public override string filter_template => DataGridFilterKnownTemplates.AlgoType;
|
|
public IComparer<OrderBookRowVM> comparer { get; }
|
|
|
|
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
|
|
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var view = base.view_factory();
|
|
view.SetBinding(OrderTypeItem.ForegroundProperty, _foreground_binding);
|
|
return view;
|
|
}
|
|
|
|
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
|
|
_cached_sort_direction = new_value;
|
|
base.OnSortDirectionChanged(new_value);
|
|
}
|
|
}
|
|
|
|
public class OrderBookLastMessageColumn : TextColumn<Columns>, ICVOrderBookColumn {
|
|
ListSortDirection? _cached_sort_direction;
|
|
|
|
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurity, string> filter)
|
|
: base(Columns.LastMessage, new Binding(nameof(OrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) {
|
|
id = key.ToString();
|
|
this.filter = filter;
|
|
Header = "Last Message";
|
|
Width = DefaultColumnWidths.LastMessage;
|
|
tooltip_binding = new Binding(nameof(OrderBookRowVM.last_msg));
|
|
}
|
|
|
|
public new IDataGridColumnPersistentFilter<OrderSecurity, string> filter { get; }
|
|
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.last_msg);
|
|
|
|
IDataGridColumnFilter<OrderSecurity> 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;
|
|
base.OnSortDirectionChanged(new_value);
|
|
}
|
|
}
|
|
|
|
public class PiqColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
|
|
public PiqColumn(IDataGridColumnPersistentFilter<OrderSecurity, UIntMinMaxState> filter)
|
|
: base(Columns.Piq, "PIQ", r => r.piq_text, DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.piq)) { }
|
|
|
|
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
|
|
CellRender.draw_text(dc, _get_glyph_context(row), font_size, row.piq_text, position, row_height,
|
|
RenderUtils.get_foreground(row, font_brush), null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding);
|
|
}
|
|
|
|
public class SecurityColumn : FrameworkElementColumnBase<Columns>, ICVOrderBookColumn, IFilterableColumn {
|
|
readonly BindingBase _font_weight_binding = RenderUtils.get_font_weight_binding(), _foreground_binding;
|
|
readonly IValueConverter _expander_visiblilty_converter = new ui.converters.BooleanToVisibilityConverter { VisibilityForFalse = Visibility.Hidden };
|
|
readonly IValueConverter _margin_converter = new AnonymousValueConverter<int, Thickness>(level => new Thickness(10 * level, 0, 0, 0));
|
|
|
|
ListSortDirection? _cached_sort_direction;
|
|
|
|
public SecurityColumn(IDataGridColumnPersistentFilter<OrderSecurity, SecurityCriteria> filter) : base(Columns.Security) {
|
|
id = key.ToString();
|
|
this.filter = filter;
|
|
_foreground_binding = RenderUtils.get_foreground_binding(this);
|
|
Header = DefaultColumnHeaders.Security;
|
|
Width = DefaultColumnWidths.Security;
|
|
_cached_sort_direction = SortDirection;
|
|
}
|
|
|
|
public IDataGridColumnPersistentFilter<OrderSecurity, SecurityCriteria> filter { get; }
|
|
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.security, SecurityHelper.Comparer.InstanceImmutable.to_nullable());
|
|
|
|
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
|
|
IDataGridColumnFilter IFilterableColumn.filter => filter;
|
|
string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues;
|
|
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
|
|
|
|
public override FrameworkElement view_factory() {
|
|
// expander
|
|
var toggle_button = new ToggleButton { ClickMode = ClickMode.Press, IsThreeState = false };
|
|
toggle_button.SetBinding(ToggleButton.IsCheckedProperty, new Binding(nameof(OrderBookRowVM.is_expanded)));
|
|
toggle_button.SetBinding(ToggleButton.MarginProperty, new Binding(nameof(OrderBookRowVM.depth_level)) { Converter = _margin_converter });
|
|
toggle_button.SetBinding(ToggleButton.VisibilityProperty, new Binding(nameof(OrderBookRowVM.is_parent)) { Converter = _expander_visiblilty_converter });
|
|
toggle_button.SetResourceReference(ToggleButton.StyleProperty, OrderBookGridView.ExpandCollapseToggleStyleKey);
|
|
//
|
|
var security_view = new TextBlock { Foreground = font_brush };
|
|
security_view.SetBinding(TextBlock.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this });
|
|
security_view.SetBinding(TextBlock.FontSizeProperty, new Binding(nameof(font_size)) { Source = this });
|
|
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, _foreground_binding);
|
|
security_view.SetBinding(TextBlock.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this });
|
|
security_view.SetBinding(TextBlock.FontWeightProperty, _font_weight_binding);
|
|
//
|
|
var grid = new Grid { VerticalAlignment = VerticalAlignment.Center };
|
|
Grid.SetColumn(security_view, 1);
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
|
|
grid.Children.Add(toggle_button);
|
|
grid.Children.Add(security_view);
|
|
//
|
|
return new Border { Child = grid, Margin = new Thickness(10, 0, 0, 0) };
|
|
}
|
|
|
|
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
|
|
_cached_sort_direction = new_value;
|
|
base.OnSortDirectionChanged(new_value);
|
|
}
|
|
}
|
|
|
|
public class CancelColumn : FrameworkElementColumnBase<Columns> {
|
|
readonly BindingBase _command_binding;
|
|
|
|
public CancelColumn(string command_property) : base(Columns.Cancel) {
|
|
id = key.ToString();
|
|
Header = DefaultColumnHeaders.Cancel;
|
|
_command_binding = new Binding(command_property);
|
|
}
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var grid = new Grid() {
|
|
HorizontalAlignment = HorizontalAlignment.Center,
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
};
|
|
var l1 = new System.Windows.Shapes.Line() {
|
|
StrokeThickness = 1,
|
|
Stroke = Brushes.White,
|
|
X1 = 0.5,
|
|
Y1 = 0.5,
|
|
X2 = 7,
|
|
Y2 = 7
|
|
};
|
|
var l2 = new System.Windows.Shapes.Line() {
|
|
StrokeThickness = 1,
|
|
Stroke = Brushes.White,
|
|
X1 = 0.5,
|
|
Y1 = 7,
|
|
X2 = 7,
|
|
Y2 = 0.5
|
|
};
|
|
grid.Children.Add(l1);
|
|
grid.Children.Add(l2);
|
|
|
|
var button = new Button() {
|
|
Content = grid,
|
|
Background = Brushes.Red,
|
|
Foreground = Brushes.White,
|
|
Margin = new Thickness(2),
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
Height = 14,
|
|
Width = 14,
|
|
Focusable = false
|
|
};
|
|
|
|
button.SetBinding(Button.CommandProperty, _command_binding);
|
|
return button;
|
|
}
|
|
}
|
|
|
|
public class AttachDetachColumn : FrameworkElementColumnBase<Columns> {
|
|
readonly Type _mini_or_full_ob_type;
|
|
|
|
public AttachDetachColumn(Type mini_or_full_ob_type) : base(Columns.Attach) {
|
|
if (!(mini_or_full_ob_type == typeof(MiniOrderBookView) || mini_or_full_ob_type == typeof(OrderBookView))) {
|
|
throw new ArgumentException();
|
|
}
|
|
id = key.ToString();
|
|
Header = DefaultColumnHeaders.AttachDetach;
|
|
Width = 45;
|
|
|
|
_mini_or_full_ob_type = mini_or_full_ob_type;
|
|
}
|
|
|
|
// General DataBinding trouble shooting tip:
|
|
// This is how one can get extra debug statements during databinding
|
|
//PresentationTraceSources.SetTraceLevel(_datacontext_binding, PresentationTraceLevel.High);
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var popup = new System.Windows.Controls.Primitives.Popup();
|
|
|
|
#region Attach Button
|
|
|
|
// create the attach button and assign the menu to it
|
|
var attach_button = new Button() {
|
|
Name = "attach_button",
|
|
Content = new Image() { Source = Icons.AttachAlgos },
|
|
HorizontalAlignment = HorizontalAlignment.Stretch,
|
|
VerticalAlignment = VerticalAlignment.Stretch,
|
|
Focusable = false,
|
|
ToolTip = "Attach"
|
|
};
|
|
var attach_grid = new Grid() {
|
|
Width = 20,
|
|
Height = 20,
|
|
HorizontalAlignment = HorizontalAlignment.Center,
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
};
|
|
attach_grid.Children.Add(attach_button);
|
|
attach_button.Click += (s, e) => { popup.IsOpen = !popup.IsOpen; };
|
|
|
|
var orderbook_vm_datacontext_binding = new Binding("DataContext");
|
|
orderbook_vm_datacontext_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, _mini_or_full_ob_type, 1);
|
|
|
|
// setting the button binding, easy, same visual tree as the MiniOrderBookView
|
|
// this has button has to be bound to the orderbook_vm b/c of the popup
|
|
// that will be assigned to the PlacementTarget and the DataContext will be
|
|
// kept in sync between those controls via a PlacementTarget.DataContext binding
|
|
attach_button.SetBinding(Button.DataContextProperty, orderbook_vm_datacontext_binding);
|
|
|
|
var row_vm_attach_to_visibility = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.is_attachable))) { Converter = new mbts.ui.converters.BooleanToVisibilityConverter() };
|
|
row_vm_attach_to_visibility.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
|
|
attach_button.SetBinding(Button.VisibilityProperty, row_vm_attach_to_visibility);
|
|
|
|
var row_vm_attach_command_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.attach_command)));
|
|
row_vm_attach_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
|
|
attach_button.SetBinding(Button.CommandProperty, row_vm_attach_command_binding);
|
|
|
|
#region OrderParamsPanel
|
|
// finally, set the order_params DataContext to that of the ContextMenu
|
|
var order_params = AlgoEditorGridView.create_attach_view();
|
|
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.attach_vm)));
|
|
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
|
|
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
|
|
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
|
|
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
|
|
order_params.SetBinding(AlgoEditorGridView.AlgoParamRowsProperty, new Binding(nameof(OrderParamsVM.param_rows)));
|
|
#endregion
|
|
|
|
#region Dialog Skirt
|
|
var dialog_skirt_button_style =
|
|
Application.Current.TryFindResource(DialogSkirt.DialogSkirtButtonStyleKey) as Style ??
|
|
Application.Current.TryFindResource("CommonButton") as Style ??
|
|
Application.Current.TryFindResource(typeof(Button)) as Style;
|
|
|
|
// go find the OBVM on the ContextMenu to get the command
|
|
// The button for which this will server as a Binding to needs to both perform the send_attached_orders
|
|
// command *AND* close the algo param popup. Previously this was accomplished by setting both the Command
|
|
// and Click event on a Button appropriately, but since the Button that will perform this
|
|
// ultimately lives inside of the DialogSkirt, we don't have direct access to it. Ergo,
|
|
// we make use of this addition trick from John that allows for both of these things to happen.
|
|
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
|
|
// pure genious!
|
|
var send_attach_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.send_attached_orders_cmd))) {
|
|
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
|
|
};
|
|
send_attach_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
|
|
|
|
// Our ultimate goal is to have the Ok button (DialogSkirtItem) run the send attached orders command.
|
|
// Since we're only dealing with binding paths in here and not actual objects, we don't have access
|
|
// to an actual Command, which is what the DialogSkirtItem expects. John came up with a sneaky
|
|
// way of setting the Button.CommandProperty via a Style backdoor, but it's also necessary to
|
|
// create a KeyedStyleSelector here I guess.
|
|
// Also, the DialogSkirt Ok button seems to magically close the popup, cool!
|
|
var send_attached_button_style = new Style(typeof(Button), dialog_skirt_button_style);
|
|
send_attached_button_style.Setters.Add(new Setter(Button.CommandProperty, send_attach_button_binding));
|
|
var awesome_command_style_key = "SendAttachButtonStyleKey";
|
|
var cancel_style_key = "CancelButtonStyleKey";
|
|
|
|
var dialog_skirt = new DialogSkirt {
|
|
RightItems = new[] {
|
|
new DialogSkirtItem("OK", null, awesome_command_style_key) { is_default = true },
|
|
new DialogSkirtItem("Cancel", new DelegateCommand(() => popup.IsOpen = false), cancel_style_key) { is_cancel = true }
|
|
}};
|
|
|
|
var kss = new KeyedStyleSelector();
|
|
kss.Map.Add(new StyleSelectorKeyValue {
|
|
Key = awesome_command_style_key,
|
|
Value = send_attached_button_style
|
|
});
|
|
kss.Map.Add(
|
|
new StyleSelectorKeyValue {
|
|
Key = cancel_style_key,
|
|
Value = new Style(typeof(Button), dialog_skirt_button_style)
|
|
});
|
|
dialog_skirt.RightItemContainerStyleSelector = kss;
|
|
|
|
Grid.SetRow(dialog_skirt, 1);
|
|
var grid = new Grid();
|
|
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
|
|
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
|
|
grid.Children.Add(order_params);
|
|
grid.Children.Add(dialog_skirt);
|
|
|
|
var border = new Border() {
|
|
Background = BTSColors.common_background_brush,
|
|
BorderThickness = new Thickness(1),
|
|
Name = "attach_border",
|
|
Child = grid,
|
|
};
|
|
|
|
#endregion
|
|
|
|
popup.Child = border;
|
|
popup.StaysOpen = false;
|
|
popup.PlacementTarget = attach_button;
|
|
popup.Placement = PlacementMode.Bottom;
|
|
// assign the Popup the DataContext of PlacementTarget, which will always be kept in sync with our parent button
|
|
popup.SetBinding(Popup.DataContextProperty, new Binding("PlacementTarget.DataContext") {
|
|
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
|
|
});
|
|
|
|
#endregion
|
|
|
|
#region Detach Button
|
|
|
|
var detach_button = new Button() {
|
|
Name = "detach_button",
|
|
Content = new Image() { Source = Icons.DetachAlgos },
|
|
HorizontalAlignment = HorizontalAlignment.Stretch,
|
|
VerticalAlignment = VerticalAlignment.Stretch,
|
|
Focusable = false,
|
|
ToolTip = "Detach"
|
|
};
|
|
|
|
//var orderbook_vm_datacontext_binding = new Binding(_detach_command_binding_path);
|
|
//orderbook_vm_datacontext_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, _mini_or_full_ob_type, 1);
|
|
detach_button.SetBinding(Button.CommandProperty, new Binding(nameof(OrderBookRowVM.detach_command)));
|
|
detach_button.SetBinding(Button.VisibilityProperty, new Binding(nameof(OrderBookRowVM.is_detachable)) { Converter = new mbts.ui.converters.BooleanToVisibilityConverter() });
|
|
|
|
|
|
var detach_grid = new Grid() {
|
|
HorizontalAlignment = HorizontalAlignment.Center,
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
Width = 20,
|
|
Height = 20,
|
|
};
|
|
detach_grid.Children.Add(detach_button);
|
|
|
|
#endregion
|
|
|
|
var the_whole_thing = new Grid();
|
|
the_whole_thing.Children.Add(attach_grid);
|
|
the_whole_thing.Children.Add(detach_grid);
|
|
the_whole_thing.Children.Add(popup);
|
|
|
|
return the_whole_thing;
|
|
}
|
|
}
|
|
|
|
public class UpdateColumn : FrameworkElementColumnBase<Columns> {
|
|
readonly Type _mini_or_full_ob_type;
|
|
|
|
public UpdateColumn(Type mini_or_full_ob_type) : base(Columns.Update) {
|
|
if (!(mini_or_full_ob_type == typeof(MiniOrderBookView) || mini_or_full_ob_type == typeof(OrderBookView))) {
|
|
throw new ArgumentException();
|
|
}
|
|
id = key.ToString();
|
|
Header = DefaultColumnHeaders.Update;
|
|
Width = 45;
|
|
|
|
_mini_or_full_ob_type = mini_or_full_ob_type;
|
|
}
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var popup = new System.Windows.Controls.Primitives.Popup();
|
|
|
|
#region Attach Button
|
|
|
|
// create the attach button and assign the menu to it
|
|
var update_button = new Button() {
|
|
Name = "update_button",
|
|
Content = "···",
|
|
Margin = new Thickness(2),
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
Focusable = false
|
|
};
|
|
update_button.Click += (s, e) => { popup.IsOpen = !popup.IsOpen; };
|
|
|
|
var orderbook_vm_datacontext_binding = new Binding("DataContext");
|
|
orderbook_vm_datacontext_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, _mini_or_full_ob_type, 1);
|
|
|
|
// setting the button binding, easy, same visual tree as the MiniOrderBookView
|
|
// this has button has to be bound to the orderbook_vm b/c of the popup
|
|
// that will be assigned to the PlacementTarget and the DataContext will be
|
|
// kept in sync between those controls via a PlacementTarget.DataContext binding
|
|
update_button.SetBinding(Button.DataContextProperty, orderbook_vm_datacontext_binding);
|
|
|
|
var row_vm_update_command_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.update_command)));
|
|
row_vm_update_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
|
|
update_button.SetBinding(Button.CommandProperty, row_vm_update_command_binding);
|
|
|
|
#endregion
|
|
|
|
#region OrderParamsPanel
|
|
// finally, set the order_params DataContext to that of the ContextMenu
|
|
var order_params = new AlgoEditorGridView {
|
|
Margin = new Thickness(6),
|
|
CanUserChangeAlgoRoot = false,
|
|
};
|
|
;
|
|
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.order_mod_vm)));
|
|
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
|
|
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
|
|
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
|
|
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
|
|
order_params.SetBinding(AlgoEditorGridView.AlgoParamRowsProperty, new Binding(nameof(OrderParamsVM.param_rows)));
|
|
#endregion
|
|
|
|
#region Dialog Skirt
|
|
var dialog_skirt_button_style =
|
|
Application.Current.TryFindResource(DialogSkirt.DialogSkirtButtonStyleKey) as Style ??
|
|
Application.Current.TryFindResource("CommonButton") as Style ??
|
|
Application.Current.TryFindResource(typeof(Button)) as Style;
|
|
|
|
// go find the OBVM on the ContextMenu to get the command
|
|
// The button for which this will server as a Binding to needs to both perform the send_attached_orders
|
|
// command *AND* close the algo param popup. Previously this was accomplished by setting both the Command
|
|
// and Click event on a Button appropriately, but since the Button that will perform this
|
|
// ultimately lives inside of the DialogSkirt, we don't have direct access to it. Ergo,
|
|
// we make use of this addition trick from John that allows for both of these things to happen.
|
|
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
|
|
// pure genious!
|
|
var modify_selected_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.modify_selected_orders_cmd))) {
|
|
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
|
|
};
|
|
modify_selected_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
|
|
|
|
// Our ultimate goal is to have the Ok button (DialogSkirtItem) run the send attached orders command.
|
|
// Since we're only dealing with binding paths in here and not actual objects, we don't have access
|
|
// to an actual Command, which is what the DialogSkirtItem expects. John came up with a sneaky
|
|
// way of setting the Button.CommandProperty via a Style backdoor, but it's also necessary to
|
|
// create a KeyedStyleSelector here I guess.
|
|
// Also, the DialogSkirt Ok button seems to magically close the popup, cool!
|
|
var send_attached_button_style = new Style(typeof(Button), dialog_skirt_button_style);
|
|
send_attached_button_style.Setters.Add(new Setter(Button.CommandProperty, modify_selected_button_binding));
|
|
var awesome_command_style_key = "SendAttachButtonStyleKey";
|
|
var cancel_style_key = "CancelButtonStyleKey";
|
|
|
|
var dialog_skirt = new DialogSkirt {
|
|
RightItems = new[] {
|
|
new DialogSkirtItem("OK", null, awesome_command_style_key) { is_default = true },
|
|
new DialogSkirtItem("Cancel", new DelegateCommand(() => popup.IsOpen = false), cancel_style_key) { is_cancel = true }
|
|
}
|
|
};
|
|
|
|
var kss = new KeyedStyleSelector();
|
|
kss.Map.Add(new StyleSelectorKeyValue {
|
|
Key = awesome_command_style_key,
|
|
Value = send_attached_button_style
|
|
});
|
|
kss.Map.Add(
|
|
new StyleSelectorKeyValue {
|
|
Key = cancel_style_key,
|
|
Value = new Style(typeof(Button), dialog_skirt_button_style)
|
|
});
|
|
dialog_skirt.RightItemContainerStyleSelector = kss;
|
|
|
|
Grid.SetRow(dialog_skirt, 1);
|
|
var grid = new Grid();
|
|
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
|
|
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
|
|
grid.Children.Add(order_params);
|
|
grid.Children.Add(dialog_skirt);
|
|
|
|
var border = new Border() {
|
|
Background = BTSColors.common_background_brush,
|
|
BorderThickness = new Thickness(1),
|
|
Name = "update_border",
|
|
Child = grid,
|
|
};
|
|
|
|
#endregion
|
|
|
|
popup.Child = border;
|
|
popup.StaysOpen = false;
|
|
popup.PlacementTarget = update_button;
|
|
popup.Placement = PlacementMode.Bottom;
|
|
// assign the Popup the DataContext of PlacementTarget, which will always be kept in sync with our parent button
|
|
popup.SetBinding(Popup.DataContextProperty, new Binding("PlacementTarget.DataContext") {
|
|
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
|
|
});
|
|
popup.Closed += (s, e) => {
|
|
if (popup.try_find_ancestor_of_type(out MiniOrderBookView mini_ob) && mini_ob.DataContext is OrderBookVM ob_vm)
|
|
ob_vm.is_attaching_orders = false;
|
|
};
|
|
|
|
var the_whole_thing = new Grid();
|
|
the_whole_thing.Children.Add(update_button);
|
|
the_whole_thing.Children.Add(popup);
|
|
|
|
return the_whole_thing;
|
|
}
|
|
}
|
|
|
|
public class EditableQtyColumn:FrameworkElementColumnBase<Columns> {
|
|
|
|
public EditableQtyColumn() : base(Columns.EditableQty) {
|
|
id = key.ToString();
|
|
Header = "Qty";
|
|
Width = 40;
|
|
}
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var tick_up_down = new TickUpDownNullableUIntCommit();
|
|
tick_up_down.SetBinding(TickUpDownNullableUIntCommit.SourceValueProperty, nameof(OrderBookRowVM.prospective_quantity));
|
|
tick_up_down.SetBinding(TickUpDownNullableUIntCommit.OnCommitProperty, nameof(OrderBookRowVM.modify_order_quantity_andor_price));
|
|
tick_up_down.InputBindings.Add(_create_keyinput_binding(Key.Enter, nameof(OrderBookRowVM.modify_order_quantity_andor_price)));
|
|
tick_up_down.InputBindings.Add(_create_keyinput_binding(Key.Escape, nameof(OrderBookRowVM.revert_prospective_order_quantity_andor_price)));
|
|
return tick_up_down;
|
|
}
|
|
}
|
|
|
|
public class EditablePriceColumn : FrameworkElementColumnBase<Columns> {
|
|
|
|
public EditablePriceColumn() : base(Columns.EditablePrice) {
|
|
id = key.ToString();
|
|
Header = "Price";
|
|
Width = 64;
|
|
}
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var price_up_down = new PriceEntryCommitControl();
|
|
price_up_down.SetBinding(PriceEntryCommitControl.SourceValueProperty, nameof(OrderBookRowVM.prospective_price));
|
|
price_up_down.SetBinding(PriceEntryCommitControl.SourceContractSpecProperty, nameof(OrderBookRowVM.contract_spec));
|
|
price_up_down.SetBinding(PriceEntryCommitControl.OnCommitProperty, nameof(OrderBookRowVM.modify_order_quantity_andor_price));
|
|
price_up_down.InputBindings.Add(_create_keyinput_binding(Key.Enter, nameof(OrderBookRowVM.modify_order_quantity_andor_price)));
|
|
price_up_down.InputBindings.Add(_create_keyinput_binding(Key.Escape, nameof(OrderBookRowVM.revert_prospective_order_quantity_andor_price)));
|
|
return price_up_down;
|
|
}
|
|
|
|
}
|
|
|
|
public class CommitColumn : FrameworkElementColumnBase<Columns> {
|
|
public CommitColumn() : base(Columns.Commit) {
|
|
id = key.ToString();
|
|
Header = "";
|
|
Width = 20;
|
|
}
|
|
|
|
public override FrameworkElement view_factory() {
|
|
var commit_button = new Button() {
|
|
Name = "commit_button",
|
|
Content = "✔",
|
|
HorizontalAlignment = HorizontalAlignment.Stretch,
|
|
VerticalAlignment = VerticalAlignment.Stretch,
|
|
};
|
|
|
|
var is_enabled_trigger = new Trigger() { Property = Button.IsEnabledProperty, Value = true };
|
|
is_enabled_trigger.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Colors.Green).frozen()));
|
|
is_enabled_trigger.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Colors.White).frozen()));
|
|
var s = new Style(typeof(Button));
|
|
s.Triggers.Add(is_enabled_trigger);
|
|
commit_button.Style = s;
|
|
|
|
commit_button.SetBinding(Button.CommandProperty, nameof(OrderBookRowVM.modify_order_quantity_andor_price));
|
|
|
|
var grid = new Grid() {
|
|
HorizontalAlignment = HorizontalAlignment.Center,
|
|
VerticalAlignment = VerticalAlignment.Center,
|
|
Width = 20,
|
|
Height = 20,
|
|
};
|
|
grid.Children.Add(commit_button);
|
|
return grid;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
static class RenderUtils {
|
|
public static FontWeight
|
|
root_font_weight = FontWeights.Normal,
|
|
child_font_weight = FontWeights.Normal;
|
|
static readonly IMultiValueConverter _foreground_converter =
|
|
ValueConverter.create<bool, Brush, Brush>(_get_foreground);
|
|
|
|
public static double font_size = FontSizes.Small;
|
|
|
|
public static readonly IValueConverter
|
|
_sub_type_text_converter = new ui.spark.converters.OrderSubTypeDisplayTextConverter(),
|
|
_side_brush_converter = new AnonymousValueConverter<Side, Brush>(s => s == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask),
|
|
_font_weight_converter = new AnonymousValueConverter<bool, FontWeight>(is_child => is_child ? child_font_weight : root_font_weight);
|
|
|
|
public static readonly IMultiValueConverter
|
|
_price_text_converter = new ui.spark.converters.TickDisplayConverter(),
|
|
_background_converter = new AnonymousMultiValueConverter<bool, OrderStatus, Brush>(
|
|
(selected, status) => selected || status != OrderStatus.Working ? Brushes.Transparent : BTSColors.Orders.working_order_background_brush);
|
|
|
|
static readonly bool _animate_child_order_rows = mbts.config.Configuration.get<bts.config.OrderBookOptions>().animate_child_order_rows;
|
|
|
|
public static BindingBase _get_background_binding() {
|
|
var mb = new MultiBinding { Converter = _background_converter };
|
|
mb.Bindings.Add(new Binding(nameof(ListBoxItem.IsSelected)) { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1) });
|
|
mb.Bindings.Add(new Binding(nameof(OrderBookRowVM.status)));
|
|
return mb;
|
|
}
|
|
|
|
public static BindingBase get_foreground_binding(ColumnBase col) {
|
|
var col_font_brush_binding = new Binding(nameof(ColumnBase.font_brush)) { Source = col };
|
|
if (!_animate_child_order_rows)
|
|
return col_font_brush_binding;
|
|
var mb = new MultiBinding { Converter = _foreground_converter };
|
|
mb.Bindings.Add(new Binding(nameof(OrderBookRowVM.is_child)));
|
|
mb.Bindings.Add(col_font_brush_binding);
|
|
return mb;
|
|
}
|
|
|
|
public static Brush get_side_brush(OrderBookRowVM r) => get_foreground(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 };
|
|
|
|
public static Brush get_foreground(OrderBookRowVM row, Brush brush) =>
|
|
_animate_child_order_rows ? _get_foreground(row.is_child, brush) : brush;
|
|
|
|
static Brush _get_foreground(bool is_child, Brush brush) {
|
|
if (is_child) {
|
|
brush = brush.Clone();
|
|
brush.Opacity = 0.75;
|
|
}
|
|
return brush;
|
|
}
|
|
}
|
|
}
|
|
}
|