diff --git a/.vscode/launch.json b/.vscode/launch.json
index 71b5a8e9e..fac8a7668 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -249,7 +249,7 @@
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"args": [
"test",
- "[mbo]"
+ "SingleWriterConcurrentVector"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server/",
diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md
index f6effe705..9326622cd 100644
--- a/doc/user/content/release_notes/_index.md
+++ b/doc/user/content/release_notes/_index.md
@@ -4,6 +4,63 @@ weight = 3
sort_by = "weight"
insert_anchor_links = "right"
+++
+## 2.2.0
+### User Visible Changes
+ - Made our orders easier to spot in MBO display
+ - Changed middle-click on center column to recenter ladder and introduced Alt middle-click on center to bring up the MBO popup
+ - Fixed Net/Absolute radio button in risk admin UI
+ - Fixed double counting of spread legs in limits
+ - Removed expired fills from the system
+ - Improved handling of orders with undiscovered securities
+ - Added feedback to the ladder when the user attempts to middle click on bid/ask columns using an order that does not have parameters
+ - Fixed display of algo studio algo types in order book
+## 2.1.4
+### User Visible Changes
+ - Fixed handling of cancel button in security picker
+
+## 2.1.3
+### User Visible Changes
+ - Fixed a simulator bug in the handling of 0 sized orders
+
+## 2.2.1
+### User Visible Changes
+ - Fixed order book form exception when display a spreader order for whichs the legs were not present yet
+
+## 2.1.1
+### User Visible Changes
+ - Added PIQ to GLBX Iceberg orders
+ - Corrected handling of stop limit orders
+
+## 2.1.0
+### User Visible Changes
+ - Added support for the GLBX Iceberg order type
+ - Allowed quick algo param edits by middle-clicking on either the bid/ask columns or a "favorite" button
+ - Added support for manual fills, either entered manually or imported from file. Manual fills are used only for P&L purposes, they have no impact on limits
+ - Allowed the LTQ and VAP values to be overlayed on the same ladder column
+ - Added day position information to the ladder
+ - Added PIQ to the mini order book
+ - Fixed a rare bug that could lead to server failure when requesting market data
+ - Fixed a bug that could cause incorrect price displays for certain types of synthetic securities
+
+## 2.0.5
+### User Visible Changes
+ - Fixed a bug in the handling of rejected QHO orders
+ - Implemented stricter position limit enforcement
+ - Fixed a bug that could cause server failure when trying to attach to already attached orders
+
+## 2.0.4
+### User Visible Changes
+ - Fixed performance regression in order manager
+
+### Internal changes
+ - Improved market data diagnostics for bad configurations
+ - Changed market data default buffer size
+
+## 2.0.3
+### Internal changes
+ - Improved backwards compatibility in UI settings
+
+
## 2.0.2
### User Visible Changes
- Middle click the ladder price column to show the orders for that price level
diff --git a/src/client/spark/Daemons/SecurityPickerDaemon.cs b/src/client/spark/Daemons/SecurityPickerDaemon.cs
index 81aad4a78..43fc91a58 100644
--- a/src/client/spark/Daemons/SecurityPickerDaemon.cs
+++ b/src/client/spark/Daemons/SecurityPickerDaemon.cs
@@ -73,6 +73,7 @@ namespace bts {
window.Close();
message.complete(select_result(vm)).execute(_bus);
};
+ vm.cancel_action = () => window.Close();
window.move_to_mouse();
window.Show();
}
diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs
index 1d730b6ee..dcc11df03 100644
--- a/src/client/spark/Images/Icons.cs
+++ b/src/client/spark/Images/Icons.cs
@@ -24,10 +24,12 @@ namespace mbts.ui {
AddFileThinGeometryKey = nameof(AddFileThinGeometryKey),
AttachAlgosKey = nameof(AttachAlgosKey),
CheckMarkGeometryKey = nameof(CheckMarkGeometryKey),
+ DataEditGeometryKey = nameof(DataEditGeometryKey),
DetachAlgosKey = nameof(DetachAlgosKey),
DiskGeometryKey = nameof(DiskGeometryKey),
DiskFileGeometryKey = nameof(DiskFileGeometryKey),
DocumentGeometryKey = nameof(DocumentGeometryKey),
+ DocumentAddGeometryKey = nameof(DocumentAddGeometryKey),
DocumentBrokenGeometryKey = nameof(DocumentBrokenGeometryKey),
DocumentCopyGeometryKey = nameof(DocumentCopyGeometryKey),
DocumentEmptyGeometryKey = nameof(DocumentEmptyGeometryKey),
@@ -145,11 +147,13 @@ namespace mbts.ui {
public static ImageSource ModifyOrder { get { return load_resource_and_freeze("ModifyOrder"); } }
public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey);
public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } }
+ public static ImageSource DataEdit => create_icon(DataEditGeometryKey, Brushes.White, new Pen(Brushes.Black, 1).frozen());
public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } }
public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red);
public static ImageSource Disk => create_icon(DiskGeometryKey);
public static ImageSource DiskFile => create_icon(DiskFileGeometryKey);
public static ImageSource Display { get { return load_resource_and_freeze("Display"); } }
+ public static ImageSource DocumentAdd => create_icon(DocumentAddGeometryKey);
public static ImageSource DocumentBroken => create_icon(DocumentBrokenGeometryKey);
public static ImageSource DocumentCopy => create_icon(DocumentCopyGeometryKey);
public static ImageSource DocumentEmpty => create_icon(DocumentEmptyGeometryKey);
diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml
index 115c988c4..e5c29b5e4 100644
--- a/src/client/spark/Images/Vector/Icons.xaml
+++ b/src/client/spark/Images/Vector/Icons.xaml
@@ -48,6 +48,10 @@
+
+ M10.830011,12.05L13.334007,12.05 13.334007,16.535997 17.819998,16.535997 17.819998,19.03902 13.334007,19.03902 13.334007,23.525016 10.830988,23.525016 10.830988,19.03902 6.3460046,19.03902 6.3449975,16.53499 10.830988,16.535997z M2.2799975,2.4149805L2.2799975,29.580015 22.121998,29.580015 22.121998,8.500008 15.83599,8.500008 15.83599,2.4149805z M0,0L15.83599,0 17.125998,0 22.681996,5.439977 24.407,7.125007 24.407,32.000001 0,32.000001z
+
+
diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs
index ef8d80395..f8cbef51c 100644
--- a/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs
+++ b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs
@@ -149,11 +149,33 @@ namespace mbts.spark {
}
void _host_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
+ // When middle click over bid or ask columns:
+ // Non-parameterizalbe order: change cursor to No indicating sending an order is not possible
+ // Parameterizable order: if qty is null/0, flash and No cursor
+ var pos = e.GetPosition(_host);
+ var column_type = _host._column_for_point(pos).column_type;
+ var selected_algo_can_expand = _host._vm.order_properties_vm?.selected_algo_definition?.algo_root?.can_expand ?? true;
+ if (e.MiddleButton == MouseButtonState.Pressed &&
+ (column_type == LadderGridHost.ColumnType.Bid || column_type == LadderGridHost.ColumnType.Ask)) {
+ if (!selected_algo_can_expand) {
+ _host.Cursor = Cursors.No;
+ }
+ if (selected_algo_can_expand && (_host._vm.size_calculator.value ?? 0) == 0) {
+ _host._vm.size_calculator.flash_error();
+ _host.Cursor = Cursors.No;
+ }
+ }
+
_is_mouse_down = true;
InvalidateVisual();
}
void _host_MouseUp(object sender, MouseButtonEventArgs e) {
+ // This will reset the cursor appropriately if the middle mouse button
+ // has been pressed while over the bid or ask columns
+ var point = e.GetPosition(_host);
+ _set_current_row_and_column(point);
+
_is_mouse_down = false;
_is_mouse_dragging = false;
InvalidateVisual();
diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
index 7b4a662c2..f2bf4d0e3 100644
--- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
+++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml
@@ -19,6 +19,7 @@
+
@@ -31,7 +32,6 @@
-
@@ -455,13 +455,33 @@
diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
index 1bfc35beb..f4f6ecea7 100644
--- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
+++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs
@@ -1,4 +1,7 @@
-using bts.collections;
+using bts;
+using bts.collections;
+using bts.utils;
+using mbts.ui.converters;
using mbts.utils;
using System.Linq;
using System.Windows;
@@ -8,6 +11,35 @@ using System.Windows.Input;
namespace mbts.spark {
partial class LadderView : UserControl {
+ public static IMultiValueConverter PositionToolTipConverter =
+ ValueConverter.create((account, show_day_pos, show_total_pos) => {
+ const string day_pos_text = "day", total_pos_text = "total";
+ if (!account.HasValue)
+ return string.Empty;
+ var sb = new StringBuilderEx(account.Value.name);
+ string primary_pos;
+ if (show_day_pos) {
+ primary_pos = day_pos_text;
+ if (show_total_pos) {
+ sb.Add(" '", primary_pos, " ");
+ sb.Add("(", total_pos_text, ")' ");
+ } else {
+ sb.Add(" ", primary_pos, " ");
+ }
+ } else if (show_total_pos) {
+ primary_pos = total_pos_text;
+ sb.Add(" ", primary_pos, " ");
+ } else {
+ // unexpected code path (the button for which this tooltip is destined should be invisible in this case), but no need to throw an exception.
+ return string.Empty;
+ }
+ sb.Add("position\n(click to copy ");
+ if (show_day_pos && show_total_pos)
+ sb.Add(primary_pos, " position ");
+ sb.Add("to size)");
+ return sb.ToString();
+ });
+
readonly double _max_zoom, _min_zoom;
internal LadderView(LadderVM vm) {
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillRow.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillRow.cs
new file mode 100644
index 000000000..b49b47c00
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillRow.cs
@@ -0,0 +1,149 @@
+using bts.api;
+using bts.api.position;
+using bts.utils;
+using mbts;
+using mbts.spark;
+using mbts.ui.shell;
+using System;
+using System.Collections.Generic;
+using System.Reactive.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+namespace bts.shell.manual_fills {
+ class ManualFillRow : DisposableViewModelBase, IEquatable {
+ public const int _uncommitted_record_id = -1;
+ static readonly PropertyInfo[] _snapshot_props =
+ Array.ConvertAll(new[] {
+ nameof(security),
+ nameof(account),
+ nameof(user),
+ nameof(side),
+ nameof(size),
+ nameof(price)
+ }, typeof(ManualFillRow).GetProperty);
+ readonly Property _is_dirty;
+ readonly Property _editable_item_state;
+ readonly DelegateProperty _is_valid;
+ SecurityImmutable? _security;
+ AccountTuple? _account;
+ UserTuple? _user;
+ Side _side;
+ uint _size;
+ double _price;
+ bool _is_selected;
+ ManualFillData? _data;
+ IDisposable _committed_snapshot;
+
+ public ManualFillRow(ManualFillData data) {
+ _data = data;
+ key = data.key;
+ _security = data.value.security;
+ _account = data.value.account;
+ _user = data.value.user;
+ _side = data.value.manual_fill.Side;
+ _size = data.value.manual_fill.Quantity;
+ _price = data.value.manual_fill.Price;
+ if (placeholder_key.HasValue) {
+ _is_dirty = backing(nameof(is_dirty), false);
+ _editable_item_state = backing(nameof(editable_item_state), EditableItemState.Uncommitted);
+ _committed_snapshot = ObjectSnapshot.create(this, _snapshot_props);
+ } else {
+ _is_dirty = backing(nameof(is_dirty), ObjectSnapshot.dirty_monitor(this, out _committed_snapshot, _snapshot_props));
+ _editable_item_state = backing(nameof(editable_item_state), _is_dirty, ch => ch.newval ? EditableItemState.Modified : EditableItemState.None);
+ }
+ _is_valid = backing(nameof(is_valid), () => _validate(this));
+ }
+
+ public event Action is_selected_changed;
+ // key/id
+ public ManualFillKey key { get; }
+ public long? placeholder_key => key.unpersisted;
+ public int record_id => key.persisted ?? _uncommitted_record_id;
+ public string record_id_display_text => key.persisted?.ToString();
+ // security/spec
+ public SecurityImmutable? security {
+ get => _security;
+ set {
+ if (_set(ref _security, value))
+ RaisePropertyChanged(nameof(spec));
+ }
+ }
+ public ContractSpecificationImmutable? spec => security.spec_or_default();
+ // account/user
+ public AccountTuple? account { get => _account; set => _set(ref _account, value); }
+ public UserTuple? user { get => _user; set => _set(ref _user, value); }
+ // side/size/price
+ public Side side { get => _side; set => _set(ref _side, value); }
+ public uint size { get => _size; set => _set(ref _size, value); }
+ public double price { get => _price; set => _set(ref _price, value); }
+ // is selected
+ public bool is_selected {
+ get => _is_selected;
+ set {
+ if (_set(ref _is_selected, value))
+ is_selected_changed?.Invoke(value);
+ }
+ }
+ // dirty/valid/editable-state
+ public bool is_dirty => _is_dirty.Value;
+ public bool is_valid => _is_valid.Value;
+ public EditableItemState editable_item_state => _editable_item_state.Value;
+
+ public ManualFillData data => _data ??
+ (_data = new ManualFillData(key, new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user))).Value;
+
+ public void revert() =>
+ _committed_snapshot.Dispose();
+
+ public IObservable subscribe_is_dirty() =>
+ _is_dirty.observe_current(true);
+
+ public IObservable subscribe_is_selected() =>
+ Observable.Create(o => {
+ o.OnNext(is_selected);
+ is_selected_changed += o.OnNext;
+ return Disposable.Create(() => is_selected_changed -= o.OnNext);
+ });
+
+ public ManualFill to_man_fill() =>
+ new ManualFill {
+ RecordId = record_id,
+ AccountId = account?.id ?? 0,
+ AccountName = account?.name ?? string.Empty,
+ UserId = user?.id ?? 0,
+ Price = price,
+ Side = side,
+ Quantity = size,
+ SecurityKey = security?.Id ?? 0
+ };
+
+ public ManualFillTuple to_tuple() =>
+ new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user);
+
+ public bool Equals(ManualFillRow other) =>
+ data == other?.data;
+
+ public override bool Equals(object obj) => Equals(obj as ManualFillRow);
+ public override int GetHashCode() => record_id;
+
+ static bool _validate(ManualFillRow row) =>
+ row.security.HasValue &&
+ row.account.HasValue &&
+ row.user.HasValue &&
+ row.side != Side.Undefined &&
+ !double.IsNaN(row._price);
+
+ bool _set(ref T backing, T value, [CallerMemberName] string prop_name = "") =>
+ _set(ref backing, value, EqualityComparer.Default, prop_name);
+
+ bool _set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName] string prop_name = "") {
+ if (Set(ref backing, value, comparer, prop_name)) {
+ _is_valid.refresh();
+ _data = null;
+ return true;
+ }
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml
new file mode 100644
index 000000000..18da3c039
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml
@@ -0,0 +1,84 @@
+
+
+ 4
+ 8
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml.cs
new file mode 100644
index 000000000..0c597bf14
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml.cs
@@ -0,0 +1,22 @@
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace mbts.ui.spark {
+ ///
+ /// Interaction logic for ManualFillRowEditor.xaml
+ ///
+ partial class ManualFillRowEditor : UserControl {
+ public const string
+ SecuritiesKey = nameof(SecuritiesKey),
+ AccountsKey = nameof(AccountsKey),
+ UsersKey = nameof(UsersKey),
+ SidesKey = nameof(SidesKey);
+
+ public static readonly RoutedCommand
+ CommitCommand = new RoutedCommand(),
+ CancelCommand = new RoutedCommand();
+
+ public ManualFillRowEditor() =>
+ InitializeComponent();
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml
new file mode 100644
index 000000000..58c33c1dd
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml.cs
new file mode 100644
index 000000000..e3a0e8cde
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsDialog.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace mbts.ui.spark {
+ ///
+ /// Interaction logic for ManualFillsImportConflictsDialog.xaml
+ ///
+ partial class ManualFillsImportConflictsDialog : Window {
+ public ManualFillsImportConflictsDialog() =>
+ InitializeComponent();
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsVM.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsVM.cs
new file mode 100644
index 000000000..c2125db20
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsVM.cs
@@ -0,0 +1,106 @@
+using bts.api;
+using bts.collections;
+using mbts;
+using mbts.collections;
+using mbts.ui;
+using mbts.ui.shell;
+using mbts.ui.utility;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Reactive.Linq;
+using System.Windows.Data;
+using System.Windows.Input;
+using Component = mbts.ui.spark.ManualFillsImportConflictsView.ManualFillComponent;
+
+namespace bts.shell.manual_fills {
+ class ManualFillsImportVM : DisposableViewModelBase, IRequestViewClose {
+ readonly RefCountMap _conflicts = new RefCountMap();
+ IReadOnlyDictionary _security_map = DictionaryHelper.empty();
+
+ public ManualFillsImportVM(int num_fills) {
+ rows_view = CollectionViewSource.GetDefaultView(rows);
+ ok_cmd = new DelegateCommand(() => import_request?.Invoke());
+ cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs()));
+ this.num_fills = num_fills;
+ _dispose = ObservableAutoWrapper.connect_item_hooks(rows, r =>
+ r.subscribe_has_error().Subscribe(has_error => {
+ if (has_error) {
+ if (r.affected_fills.Count(_conflicts.increment_adds_key) == 0)
+ return;
+ } else if (r.affected_fills.Count(_conflicts.decrement_removes_key) == 0)
+ return;
+ RaisePropertyChanged(nameof(num_successfully_parsed_fills));
+ }));
+ }
+
+ public event Action import_request;
+ public event EventHandler RequestClose;
+
+ public ObservableCollection rows { get; } = new ObservableCollection();
+ public ICollectionView rows_view { get; }
+ public int num_fills { get; }
+ public int num_successfully_parsed_fills => num_fills - _conflicts.Count;
+ // misc items sources
+ public IEnumerable sides => new[] { Side.Buy, Side.Sell };
+ public ObservableCollection accounts { get; } = new ObservableCollection();
+ public ObservableCollection users { get; } = new ObservableCollection();
+ public IReadOnlyDictionary security_map {
+ get => _security_map;
+ set {
+ if (!ReferenceEquals(_security_map, value)) {
+ _security_map = value;
+ _resolve_securities();
+ RaisePropertyChanged();
+ }
+ }
+ }
+ // commands
+ public ICommand ok_cmd { get; }
+ public ICommand cancel_cmd { get; }
+
+ void _resolve_securities() {
+ if (_security_map == null)
+ return;
+ var reverse_lookup = ManualFillsParser.reverse_lookup(MappedDictionary.create(_security_map, v => v.security.ToString()));
+ foreach (var r in rows) {
+ if (r.component == Component.Security && r.has_error) {
+ var id = reverse_lookup(r.text);
+ if (id != 0 && _security_map.TryGetValue(id, out var smd))
+ r.value = smd.security;
+ }
+ }
+ }
+
+ public class Row : ViewModelBase, ITemplateSelectorKey {
+ readonly DelegateProperty _has_error;
+ object _value;
+ string _text;
+
+ public Row(Component component, string text, IReadOnlyCollection affected_fills, object error_value, object value) {
+ this.component = component;
+ this.text = text;
+ this.affected_fills = affected_fills;
+ _value = value;
+ _has_error = backing(nameof(has_error), () => Equals(this.value, error_value));
+ }
+
+ public Component component { get; }
+ public string text { get => _text; set => Set(ref _text, value); }
+ public IReadOnlyCollection affected_fills { get; }
+ public object value {
+ get => _value;
+ set {
+ if (Set(ref _value, value))
+ _has_error.refresh();
+ }
+ }
+ public bool has_error => _has_error.Value;
+ string ITemplateSelectorKey.key => component.ToString();
+
+ public IObservable subscribe_has_error() => _has_error.observe_current(true);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml
new file mode 100644
index 000000000..097112a63
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml
@@ -0,0 +1,144 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml.cs
new file mode 100644
index 000000000..54e5dc78d
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsImportConflictsView.xaml.cs
@@ -0,0 +1,30 @@
+using System.Windows.Controls;
+
+namespace mbts.ui.spark {
+ ///
+ /// Interaction logic for ManualFillsImportConflictsView.xaml
+ ///
+ partial class ManualFillsImportConflictsView : UserControl {
+ public ManualFillsImportConflictsView() =>
+ InitializeComponent();
+
+ public enum ManualFillComponent {
+ Security,
+ Account,
+ User,
+ Side,
+ Size,
+ Price
+ }
+
+ public static class ManualFillComponentNames {
+ public static readonly string
+ Security = ManualFillComponent.Security.ToString(),
+ Account = ManualFillComponent.Account.ToString(),
+ User = ManualFillComponent.User.ToString(),
+ Side = ManualFillComponent.Side.ToString(),
+ Size = ManualFillComponent.Size.ToString(),
+ Price = ManualFillComponent.Price.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs
new file mode 100644
index 000000000..871aaf940
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs
@@ -0,0 +1,107 @@
+using bts.api.core;
+using bts.api.position;
+using bts.collections;
+using mbts.spark;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reactive.Linq;
+using System.Threading.Tasks;
+
+namespace bts.shell.manual_fills {
+ struct ManualFillKey : IEquatable, IComparable {
+ public readonly int? persisted;
+ public readonly long? unpersisted;
+
+ public ManualFillKey(int persisted) {
+ this.persisted = persisted;
+ unpersisted = null;
+ }
+
+ public ManualFillKey(long unpersisted) {
+ this.unpersisted = unpersisted;
+ persisted = null;
+ }
+
+ public int CompareTo(ManualFillKey other) {
+ if (persisted.HasValue) {
+ if (other.persisted.HasValue) {
+ return persisted.Value.CompareTo(other.persisted.Value);
+ } else if (other.unpersisted.HasValue) {
+ return -1;
+ } else return 1;
+ } else if (unpersisted.HasValue) {
+ return other.unpersisted.HasValue ? unpersisted.Value.CompareTo(other.unpersisted.Value) : 1;
+ } else return !other.persisted.HasValue && !other.unpersisted.HasValue ? 0 : -1;
+ }
+
+ public override string ToString() => persisted.HasValue ? persisted.Value.ToString() : unpersisted.HasValue ? unpersisted.Value.ToString() : "(N/A)";
+
+ public bool Equals(ManualFillKey other) =>
+ persisted == other.persisted &&
+ unpersisted == other.unpersisted;
+
+ public override bool Equals(object obj) =>
+ obj is ManualFillKey other && Equals(other);
+
+ public override int GetHashCode() => persisted ?? unpersisted?.GetHashCode() ?? 0;
+ public static bool operator ==(ManualFillKey a, ManualFillKey b) => a.Equals(b);
+ public static bool operator !=(ManualFillKey a, ManualFillKey b) => !a.Equals(b);
+ }
+
+ struct ManualFillData : IEquatable {
+ public static readonly Func key_fn = mfd => mfd.key;
+
+ public readonly ManualFillKey key;
+ public readonly ManualFillTuple value;
+
+ public ManualFillData(ManualFillKey key, ManualFillTuple value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public bool Equals(ManualFillData other) =>
+ key == other.key &&
+ value.Equals(other.value);
+
+ public override bool Equals(object obj) =>
+ obj is ManualFillData other && Equals(other);
+
+ public override int GetHashCode() =>
+ key.GetHashCode();
+
+ public static bool operator ==(ManualFillData a, ManualFillData b) => a.Equals(b);
+ public static bool operator !=(ManualFillData a, ManualFillData b) => !a.Equals(b);
+ }
+
+ class ManualFillsModel {
+ readonly OrdersModel _model;
+
+ public ManualFillsModel(OrdersModel model)
+ : this(model, model.on_manual_fill_tuples,
+ model.factory.subscribe_accounts().Select(d => MappedDictionary.create(d, kv => new AccountTuple(kv.Key, kv.Value))).Table(u => u.id),
+ model.factory.subscribe_users().Select(d => MappedDictionary.create(d, kv => new UserTuple(kv.Key, kv.Value))).Table(a => a.id)) { }
+
+ public ManualFillsModel(OrdersModel model, IObservable> manual_fills, IObservable> accounts, IObservable> users) {
+ _model = model;
+ this.manual_fills = manual_fills.SelectKeyValue(
+ mft => new ManualFillData(new ManualFillKey(mft.manual_fill.RecordId), mft),
+ ManualFillData.key_fn);
+ this.accounts = accounts;
+ this.users = users;
+ }
+
+ public IObservable> manual_fills { get; }
+ public IObservable> accounts { get; }
+ public IObservable> users { get; }
+
+ public async Task delete_fills(IEnumerable fills) =>
+ await _model.delete_manual_fills(fills);
+
+ public async Task create_fills(IEnumerable fills) =>
+ await _model.create_manual_fills(fills);
+
+ public async Task update_fills(IEnumerable fills) =>
+ await _model.update_manual_fills(fills);
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsParser.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsParser.cs
new file mode 100644
index 000000000..7d6ca8968
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsParser.cs
@@ -0,0 +1,162 @@
+using bts.api;
+using bts.api.position;
+using bts.collections;
+using bts.utils;
+using mbts.ui.utility;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ManualFillComponent = mbts.ui.spark.ManualFillsImportConflictsView.ManualFillComponent;
+
+namespace bts.shell.manual_fills {
+ class ParsedManualFill {
+ public readonly Guid unpersisted_id = Guid.NewGuid();
+ public readonly ManualFill result = new ManualFill();
+
+ public (string text, bool success) security { get; set; }
+ public (string text, bool success) account { get; set; }
+ public (string text, bool success) user { get; set; }
+ public (string text, bool success) side { get; set; }
+ public (string text, bool success) quantity { get; set; }
+ public (string text, bool success) price { get; set; }
+
+ public bool Equals(ParsedManualFill other) => other != null && unpersisted_id == other.unpersisted_id;
+ public override bool Equals(object obj) => Equals(obj as ParsedManualFill);
+ public override int GetHashCode() => unpersisted_id.GetHashCode();
+ }
+
+ static class ManualFillsParser {
+ public const string file_extension = "csv";
+
+ public static Action assign_component(ManualFillComponent component) {
+ switch (component) {
+ case ManualFillComponent.Security: return (mf, val) => mf.SecurityKey = ConvertUtils.try_convert(val)?.Id ?? 0;
+ case ManualFillComponent.Account: return (mf, val) => mf.AccountId = ConvertUtils.try_convert(val)?.id ?? 0;
+ case ManualFillComponent.User: return (mf, val) => mf.UserId = ConvertUtils.try_convert(val)?.id ?? 0;
+ case ManualFillComponent.Side: return (mf, val) => mf.Side = ConvertUtils.try_convert(val, Side.Undefined);
+ case ManualFillComponent.Size: return (mf, val) => mf.Quantity = ConvertUtils.try_convert(val);
+ case ManualFillComponent.Price: return (mf, val) => mf.Price = ConvertUtils.try_convert(val, double.NaN);
+ default: throw new NotImplementedException();
+ }
+ }
+
+ /// Note: the returned dictionary will have entries for each , regardless of whether or not that component has any conflicts.
+ public static Dictionary>> get_conflicts(IEnumerable parsed_fills) {
+ var missing_components = EnumHelper.get_values().ToDictionary(c => c, c => new Dictionary>());
+ var mk_list = new Func>(_ => new List());
+ foreach (var pmf in parsed_fills) {
+ if (!pmf.security.success) {
+ add_missing(ManualFillComponent.Security, pmf.security.text, pmf);
+ }
+ if (!pmf.account.success) {
+ add_missing(ManualFillComponent.Account, pmf.account.text, pmf);
+ }
+ if (!pmf.user.success) {
+ add_missing(ManualFillComponent.User, pmf.user.text, pmf);
+ }
+ if (!pmf.quantity.success) {
+ add_missing(ManualFillComponent.Size, pmf.quantity.text, pmf);
+ }
+ if (!pmf.side.success) {
+ add_missing(ManualFillComponent.Side, pmf.side.text, pmf);
+ }
+ if (!pmf.price.success) {
+ add_missing(ManualFillComponent.Price, pmf.price.text, pmf);
+ }
+ }
+ return missing_components;
+ void add_missing(ManualFillComponent component, string text, ParsedManualFill result) =>
+ missing_components[component].GetOrAdd(text ?? string.Empty, mk_list).Add(result);
+ }
+
+ // This implementation prioritizes simplicity over speed.
+ // The security desc lookup could be better optimized, but the speed at which fills are imported is probably not a paramount concern.
+ public static IEnumerable parse_rows(IEnumerable rows, IReadOnlyDictionary security_map, IReadOnlyDictionary account_map, IReadOnlyDictionary user_map) =>
+ parse_rows(rows,
+ reverse_lookup(MappedDictionary.create(security_map, kv => kv.Value.ToString())),
+ reverse_lookup(account_map),
+ reverse_lookup(user_map));
+
+ public static IEnumerable parse_rows(IEnumerable rows, Func security_id_lookup, Func account_id_lookup, Func user_id_lookup) {
+ var columns = new[] {
+ (Headers.Security, Cells.security(security_id_lookup)),
+ (Headers.Account, Cells.account(account_id_lookup)),
+ (Headers.User, Cells.user(user_id_lookup)),
+ (Headers.Side, Cells.side),
+ (Headers.Quantity, Cells.quantity),
+ (Headers.Price, Cells.price)
+ }.ToDictionary(col => col.Item1, col => col.Item2.with_null_check());
+ return RowParser.parse_rows(rows, columns, Cells.delimiter);
+ }
+
+ public static Func reverse_lookup(IReadOnlyDictionary map) {
+ var lookup = map.ToLookup(kv => kv.Value, kv => kv.Key);
+ return cell_text => lookup.Contains(cell_text) ? lookup[cell_text].First() : default;
+ }
+
+ static class Headers {
+ public const string
+ Security = "Security",
+ Account = "Account",
+ User = "User",
+ Side = "Side",
+ Quantity = "Quantity",
+ Price = "Price";
+ }
+
+ static class Cells {
+ public const char delimiter = ',';
+
+ public static RowParser.AssignColumnValue security(Func reverse_id_lookup) {
+ return impl;
+ void impl(ref ParsedManualFill pmf, string text) {
+ pmf.result.SecurityKey = reverse_id_lookup(text);
+ pmf.security = (text, pmf.result.SecurityKey != 0);
+ }
+ }
+
+ public static void side(ref ParsedManualFill pmf, string cell_text) {
+ switch (cell_text[0]) {
+ case 'B': pmf.result.Side = Side.Buy; break;
+ case 'S': pmf.result.Side = Side.Sell; break;
+ default: pmf.side = (cell_text, false); break;
+ }
+ pmf.side = (cell_text, true);
+ }
+
+ public static void quantity(ref ParsedManualFill pmf, string cell_text) {
+ if (uint.TryParse(cell_text, out uint v)) {
+ pmf.result.Quantity = v;
+ pmf.quantity = (cell_text, true);
+ } else {
+ pmf.quantity = (cell_text, false);
+ }
+ }
+
+ public static void price(ref ParsedManualFill pmf, string cell_text) {
+ if (double.TryParse(cell_text, out var v)) {
+ pmf.result.Price = v;
+ pmf.price = (cell_text, true);
+ } else {
+ pmf.price = (cell_text, false);
+ }
+ }
+
+ public static RowParser.AssignColumnValue account(Func reverse_id_lookup) {
+ return impl;
+ void impl(ref ParsedManualFill pmf, string text) {
+ pmf.result.AccountId = reverse_id_lookup(text);
+ pmf.account = (text, pmf.result.AccountId != 0);
+ }
+ }
+
+ public static RowParser.AssignColumnValue user(Func reverse_id_lookup) {
+ return impl;
+ void impl(ref ParsedManualFill pmf, string text) {
+ pmf.result.UserId = reverse_id_lookup(text);
+ pmf.user = (text, pmf.result.UserId != 0);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsSettings.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsSettings.cs
new file mode 100644
index 000000000..725e6f374
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsSettings.cs
@@ -0,0 +1,23 @@
+using mbts.ui;
+using ProtoBuf;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace bts.shell.manual_fills {
+ [ProtoContract]
+ class ManualFillsSettings {
+ [ProtoMember(1)]
+ readonly SortingCriteria[] _sorting_criterion;
+
+ public static ManualFillsSettings Default =>
+ new ManualFillsSettings(new[] { new SortingCriteria(nameof(mbts.ui.spark.ManualFillsView.Columns.Security), true) });
+
+ public ManualFillsSettings() { }
+
+ public ManualFillsSettings(IEnumerable sorting_criterion) =>
+ _sorting_criterion = sorting_criterion.ToArray();
+
+ public IReadOnlyList sorting_criterion => _sorting_criterion ?? Array.Empty();
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs
new file mode 100644
index 000000000..cb2ecf39b
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs
@@ -0,0 +1,222 @@
+using bts.api;
+using bts.api.core;
+using bts.api.position;
+using bts.collections;
+using mbts;
+using mbts.spark;
+using mbts.ui;
+using mbts.ui.controls;
+using mbts.ui.shell;
+using mbts.ui.utility;
+using mbts.utils;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Reactive.Linq;
+using System.Threading.Tasks;
+using System.Windows.Data;
+using System.Windows.Input;
+using Disposable = mbts.Disposable;
+using ManualFillComponent = mbts.ui.spark.ManualFillsImportConflictsView.ManualFillComponent;
+
+namespace bts.shell.manual_fills {
+ enum EditableItemState {
+ None, // Committed and not modified
+ Modified, // Committed and modified
+ Uncommitted // Uncommitted (modified n/a)
+ }
+
+ class ManualFillsVM : DisposableViewModelBase {
+ const int _max_unconfirmed_removes = 16;
+ static readonly IComparer _row_key_comparer = Comparer.Create((a, b) => a.key.CompareTo(b.key));
+ readonly IBus _bus;
+ readonly ManualFillsModel _model;
+ readonly ObservableCollection
+ _persisted_rows = new ObservableCollection(),
+ _placeholder_rows = new ObservableCollection();
+ long _placeholder_id_counter = long.MinValue;
+ IDisposable _import_fills_hooks;
+
+ public static ManualFillsVM create(IBus bus, OrdersModel model) =>
+ new ManualFillsVM(bus, new ManualFillsModel(model));
+
+ public ManualFillsVM(IBus bus, ManualFillsModel model) {
+ _bus = bus;
+ _model = model;
+ var merged_rows = new ObservableAggregateCollection(_persisted_rows, _placeholder_rows);
+ rows_view = CollectionViewSource.GetDefaultView(merged_rows);
+ // mons
+ var dirty_mon = new ReactiveThresholdMonitor(r => r.subscribe_is_dirty());
+ var selection_mon = new ReactiveThresholdMonitor(r => r.subscribe_is_selected());
+ var placeholder_mon = new ReactiveThresholdMonitor();
+ // commands
+ commit_all_fills_cmd = ObservantAsyncCommand.create(() => _commit_async(merged_rows), out var commit_all_fils_observer);
+ commit_selected_fills_cmd = ObservantAsyncCommand.create(() => _commit_async(selection_mon.filtered_items), out var commit_selected_fills_observer);
+ revert_all_cmd = ObservantCommand.create(() => revert(dirty_mon.filtered_items.ToList()), out var revert_all_observer);
+ revert_selected_fills_cmd = ObservantCommand.create(() => revert(selection_mon.filtered_items.ToList()), out var revert_selected_fills_observer);
+ remove_selected_fills_cmd = ObservantAsyncCommand.create(remove_selected_fills_async, out var remove_selected_fills_observer);
+ add_fill_cmd = new DelegateCommand(_add_fill);
+ import_fills_cmd = FileDialogCommand.open_file(_import_fills, extensions: ManualFillsParser.file_extension);
+ //
+ var dirty_or_new_src = dirty_mon.CombineLatest(placeholder_mon, LogicalDelegates.Or);
+ _dispose = Disposable.Create(
+ RXCollection.connect(_persisted_rows,
+ _model.manual_fills.OnDispatcher(),
+ Observable.Return(Comparer.Create((a, b) => a.key.CompareTo(b.key))),
+ mfd => new ManualFillRow(mfd),
+ mfr => mfr.data),
+ _bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m => {
+ security_map = m;
+ RaisePropertyChanged(nameof(security_map));
+ }),
+ ObservableAutoWrapper.connect_item_hooks(_persisted_rows, r => Disposable.Create(dirty_mon.join(r), selection_mon.join(r))),
+ ObservableAutoWrapper.connect_item_hooks(_placeholder_rows, r => Disposable.Create(selection_mon.join(r), placeholder_mon.join(r, Observable.Return(true)))),
+ // command param subs
+ dirty_mon.Subscribe(revert_all_observer),
+ dirty_or_new_src.OnDispatcher().Subscribe(commit_all_fils_observer),
+ selection_mon.Subscribe(remove_selected_fills_observer),
+ selection_mon.CombineLatest(dirty_mon, LogicalDelegates.And).OnDispatcher().Subscribe(revert_selected_fills_observer),
+ selection_mon.CombineLatest(dirty_or_new_src, LogicalDelegates.And).OnDispatcher().Subscribe(commit_selected_fills_observer),
+ // accounts/users subs
+ RXCollection.connect(accounts, model.accounts.OnDispatcher(), a => new AccountTuple?(a), a => a.Value, Comparer.Default),
+ RXCollection.connect(users, model.users.OnDispatcher(), u => new UserTuple?(u), u => u.Value, Comparer.Default),
+ Disposable.Create(() => Disposable.dispose(ref _import_fills_hooks))
+ );
+ // local methods
+ void revert(IReadOnlyList rows) {
+ foreach (var r in rows)
+ r.revert();
+ }
+ async Task remove_selected_fills_async() {
+ if (selection_mon.filtered_items.Count < _max_unconfirmed_removes || BTSMessageBox.Confirm($"Are you sure you want to delete {selection_mon.filtered_items.Count} fills?", "Delete Fills")) {
+ var persisted_fills = new List();
+ foreach (var r in selection_mon.filtered_items.ToList()) {
+ if (r.placeholder_key.HasValue)
+ _placeholder_rows.RemoveSorted(r, _row_key_comparer);
+ else persisted_fills.Add(r.to_man_fill());
+ }
+ await _model.delete_fills(persisted_fills);
+ }
+ }
+ }
+
+ public ICollectionView rows_view { get; }
+ // misc items sources
+ public IEnumerable sides => new[] { Side.Buy, Side.Sell };
+ public ObservableCollection accounts { get; } = new ObservableCollection();
+ public ObservableCollection users { get; } = new ObservableCollection();
+ public IReadOnlyDictionary security_map { get; private set; } = DictionaryHelper.empty();
+ // commands
+ public ICommand add_fill_cmd { get; }
+ public ICommand commit_all_fills_cmd { get; }
+ public ICommand commit_selected_fills_cmd { get; }
+ public ICommand import_fills_cmd { get; }
+ public ICommand remove_selected_fills_cmd { get; }
+ public ICommand revert_all_cmd { get; }
+ public ICommand revert_selected_fills_cmd { get; }
+
+ public ManualFillRow row_factory() =>
+ new ManualFillRow(
+ new ManualFillData(
+ new ManualFillKey(_placeholder_id_counter++),
+ new ManualFillTuple(new ManualFillImmutable(new ManualFill {
+ Side = Side.Buy
+ }), null, accounts.FirstOrDefault(), users.FirstOrDefault())));
+
+ void _add_fill(ManualFillRow new_row) =>
+ _placeholder_rows.InsertSorted((new_row ?? (new_row = row_factory())).placeholder_key.HasValue ?
+ new_row : throw new InvalidOperationException("New row is already persisted."),
+ _row_key_comparer);
+
+ async Task _commit_async(IEnumerable rows) {
+ var updates = new List();
+ var adds = new List<(ManualFill man_fill, long pl_key)>();
+ foreach (var r in rows) {
+ if (r.is_dirty) {
+ updates.Add(r.to_man_fill());
+ } else if (r.placeholder_key.HasValue) {
+ adds.Add((r.to_man_fill(), r.placeholder_key.Value));
+ }
+ }
+ if (updates.Count > 0)
+ await _model.update_fills(updates);
+ if (adds.Count > 0) {
+ await _model.create_fills(adds.WrapSelector(r => r.man_fill, null));
+ _placeholder_rows
+ .WrapSelector(r => r.placeholder_key.Value, null)
+ .RemoveSorted(adds.Select(r => r.pl_key));
+ }
+ }
+
+ void _import_fills(string file_name) {
+ try {
+ var lines = File.ReadAllLines(file_name);
+ var parsed_fills = ManualFillsParser.parse_rows(
+ lines,
+ MappedDictionary.create(security_map, kv => kv.Value.security),
+ accounts.ToDictionary(a => a.Value.id, a => a.Value.name),
+ users.ToDictionary(u => u.Value.id, u => u.Value.name)
+ ).ToList();
+ var conflicts = ManualFillsParser.get_conflicts(parsed_fills);
+ if (conflicts.Values.Any(c => c.Count > 0)) {
+ // init vm
+ var vm = new ManualFillsImportVM(parsed_fills.Count) {
+ security_map = security_map
+ };
+ // add rows
+ foreach (var kv in conflicts) {
+ var assign_del = ManualFillsParser.assign_component(kv.Key);
+ foreach (var text_groups in kv.Value) {
+ var eval = get_error_value(kv.Key);
+ var row = new ManualFillsImportVM.Row(kv.Key, text_groups.Key, text_groups.Value, eval, eval);
+ vm.rows.Add(row);
+ vm.import_request += () => {
+ foreach (var pmf in text_groups.Value)
+ assign_del(pmf.result, row.value);
+ };
+ }
+ }
+ var win = new mbts.ui.spark.ManualFillsImportConflictsDialog {
+ DataContext = vm,
+ Title = ManualFillsWindowFactory.window_name,
+ Topmost = true
+ };
+ vm.RequestClose += (s, e) => Disposable.dispose(ref _import_fills_hooks);
+ vm.import_request += () => {
+ add_imported_fills();
+ Disposable.dispose(ref _import_fills_hooks);
+ };
+ Disposable.replace(ref _import_fills_hooks, Disposable.Create(
+ ObservableAutoWrapper.connect(accounts, vm.accounts),
+ ObservableAutoWrapper.connect(users, vm.users),
+ vm,
+ Disposable.Create(close)
+ ));
+ win.move_to_mouse(-200, -75);
+ win.Show();
+ void close() => WindowUtilities.force_close(win);
+ object get_error_value(ManualFillComponent component) {
+ switch (component) {
+ case ManualFillComponent.Price: return double.NaN;
+ case ManualFillComponent.Size: return 0;
+ default: return null;
+ }
+ }
+ } else {
+ add_imported_fills();
+ }
+ void add_imported_fills() =>
+ _placeholder_rows.InsertSorted(parsed_fills.Select(pmf => new ManualFillRow(new ManualFillData(new ManualFillKey(_placeholder_id_counter++), new ManualFillTuple(new ManualFillImmutable(pmf.result),
+ pmf.result.SecurityKey != 0 && security_map.TryGetValue(pmf.result.SecurityKey, out var smd) ? smd.security : (SecurityImmutable?)null,
+ accounts.FirstOrDefault(a => a?.id == pmf.result.AccountId),
+ users.FirstOrDefault(a => a?.id == pmf.result.UserId))))), _row_key_comparer);
+ } catch (Exception ex) {
+ BTSMessageBox.Error($"Error importing fills: {ex}.", ManualFillsWindowFactory.window_name);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml
new file mode 100644
index 000000000..22f954abb
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml
@@ -0,0 +1,247 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml.cs
new file mode 100644
index 000000000..78fb5b10b
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml.cs
@@ -0,0 +1,97 @@
+using bts.shell.manual_fills;
+using mbts.ui.controls.adorners;
+using mbts.ui.converters;
+using mbts.utils;
+using System;
+using System.Reactive.Disposables;
+using System.Reactive.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Media;
+
+namespace mbts.ui.spark {
+ ///
+ /// Interaction logic for ManualFillsView.xaml
+ ///
+ partial class ManualFillsView : UserControl {
+ public static readonly IMultiValueConverter
+ RowHeaderVisualStateConverter = ValueConverter.create(
+ (edit_state, is_valid) => is_valid ? edit_state.ToString() : edit_state == EditableItemState.Uncommitted ? "ErrorUncommitted" : "Error");
+
+ public enum Columns {
+ RecordID,
+ Security,
+ Account,
+ User,
+ Side,
+ Size,
+ Price
+ }
+
+ IDisposable _transaction;
+
+ public ManualFillsView() =>
+ InitializeComponent();
+
+ public static readonly DependencyProperty ImageBrushProperty =
+ DependencyProperty.RegisterAttached("ImageBrush", typeof(Brush), typeof(ManualFillsView));
+
+ public static Brush GetImageBrush(DependencyObject d) => d.GetValue(ImageBrushProperty) as Brush;
+ public static void SetImageBrush(DependencyObject d, Brush value) => d.SetValue(ImageBrushProperty, value);
+
+ public void begin_add_fill() {
+ if (!(DataContext is ManualFillsVM vm))
+ return;
+ Disposable.dispose(ref _transaction);
+ var row = vm.row_factory();
+ var row_editor = new ManualFillRowEditor { DataContext = row };
+ row_editor.CommandBindings.Add(new CommandBinding(ManualFillRowEditor.CommitCommand, commit_executed));
+ row_editor.CommandBindings.Add(new CommandBinding(ManualFillRowEditor.CancelCommand, cancel_executed));
+ // dynamic resources
+ row_editor.Resources[ManualFillRowEditor.AccountsKey] = vm.accounts;
+ row_editor.Resources[ManualFillRowEditor.UsersKey] = vm.users;
+ row_editor.Resources[ManualFillRowEditor.SidesKey] = vm.sides;
+ FocusManager.SetIsFocusScope(row_editor, true);
+ var sec_hook = vm.as_demuxer().subscribe(nameof(ManualFillsVM.security_map)).OnDispatcher().Subscribe(v => row_editor.Resources[ManualFillRowEditor.SecuritiesKey] = v);
+ // popup adorner
+ var popup_adorner = new PopupAdorner(
+ data_grid, data_grid,
+ new Border {
+ Child = row_editor,
+ Background = BTSColors.common_background_brush,
+ BorderBrush = Brushes.Black,
+ BorderThickness = new Thickness(1),
+ Padding = new Thickness(0, 6, 0, 0),
+ HorizontalAlignment = HorizontalAlignment.Left,
+ VerticalAlignment = VerticalAlignment.Top
+ },
+ HorizontalPosition.Middle,
+ VerticalPosition.Middle,
+ 0,
+ 22) {
+ OpenRelativeToMouse = true,
+ EnableDragMove = true,
+ ClipToBounds = true
+ };
+ popup_adorner.attach();
+ popup_adorner.IsOpen = true;
+ row_editor.Focus();
+ _transaction = new CompositeDisposable(sec_hook) { destroy_popup };
+ // local methods
+ void commit_executed(object sender, ExecutedRoutedEventArgs e) {
+ vm.add_fill_cmd?.TryExecuteIfCan(row);
+ Disposable.dispose(ref _transaction);
+ }
+ void cancel_executed(object sender, ExecutedRoutedEventArgs e) {
+ row.revert();
+ Disposable.dispose(ref _transaction);
+ }
+ void destroy_popup() {
+ popup_adorner.IsOpen = false;
+ popup_adorner.detach();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsWindowFactory.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsWindowFactory.cs
new file mode 100644
index 000000000..56a3c86f4
--- /dev/null
+++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsWindowFactory.cs
@@ -0,0 +1,133 @@
+using bts.api;
+using bts.shell.manual_fills;
+using bts.spark;
+using mbts;
+using mbts.collections;
+using mbts.spark;
+using mbts.ui;
+using mbts.ui.controls;
+using mbts.ui.spark;
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+
+namespace bts.shell {
+ class ManualFillsWindowFactory : ShellWindowFactory {
+ public const string
+ window_type = "ManualFills",
+ window_name = "Manual Fills";
+ const double _window_min_width = 466;
+
+ readonly IBus _bus;
+ readonly OrdersModel _orders_model;
+ readonly ManualFillsConfig _manual_fills_conf = ManualFillsConfig.read();
+
+ public ManualFillsWindowFactory(IShellModule owner, IBus bus, OrdersModel orders_model) : base(owner, window_name) {
+ _bus = bus;
+ _orders_model = orders_model;
+ _dispose = bus.subscribe(SparkTags.ShowManualFillsTag).Subscribe(open_window);
+ //
+ async void open_window(ManualFillsSettings state) =>
+ _bus.post(SparkTags.ShowWindow, await load(state));
+ }
+
+ public override Task load(ManualFillsSettings settings) {
+ return Task.FromResult(SparkWindow.create(
+ window_type, window_name, _bus, this, Icons.DataEdit, _manual_fills_conf.thread_id, thread_init, _window_min_width));
+ //
+ (UIElement, IEnumerable, Func, IDisposable) thread_init() {
+ var vm = ManualFillsVM.create(_bus, _orders_model);
+ var view = new ManualFillsView { DataContext = vm };
+ view.data_grid.Sorting += on_sorting;
+ IReadOnlyList last_sorting_criterion = Array.Empty();
+ using (apply_sort()) {
+ var col_sort_tuples =
+ from sc in settings.sorting_criterion
+ join col in view.data_grid.Columns on sc.col_name equals _col_id(col)
+ select (col, sc);
+ foreach (var (col, sc) in col_sort_tuples) {
+ col.SortDirection = sc.direction();
+ vm.rows_view.SortDescriptions.Add(new SortDescription(col.SortMemberPath, sc.direction()));
+ }
+ }
+ var cmds = new[] {
+ new SparkCommandCommand("Add New", Icons.AddBoxes, _manual_fills_conf.modal_transactions ? new DelegateCommand(() => view.begin_add_fill()) : vm.add_fill_cmd) { group = CommandGroups.Add },
+ new SparkCommandCommand("Import Fills", Icons.Import, vm.import_fills_cmd) { group = CommandGroups.Add },
+ new SparkCommandCommand("Revert Selected", Icons.UndoCircular,vm.revert_selected_fills_cmd) { group = CommandGroups.Revert, show_in_toolbar = false },
+ new SparkCommandCommand("Revert All", Icons.UndoCircular, vm.revert_all_cmd) { group = CommandGroups.Revert },
+ new SparkCommandCommand("Save Selected", Icons.Disk, vm.commit_selected_fills_cmd) { group = CommandGroups.Save, show_in_toolbar = false },
+ new SparkCommandCommand("Save All", Icons.Disk, vm.commit_all_fills_cmd) { group = CommandGroups.Save },
+ new SparkCommandCommand("Delete Selected", Icons.Trash, vm.remove_selected_fills_cmd)
+ };
+ return (view, cmds, get_settings, Disposable.Create(
+ vm.rows_view.subscribe_sorting_criterion(sm => view.data_grid.Columns.TryGetFirst(dc => dc.SortMemberPath == sm, out DataGridColumn match) ? _col_id(match) : null)
+ .Subscribe(sc => last_sorting_criterion = sc),
+ vm));
+ //
+ void on_sorting(object sender, DataGridSortingEventArgs e) {
+ e.Handled = true;
+ using (apply_sort()) {
+ var new_sort_desc = new SortDescription(e.Column.SortMemberPath, e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending);
+ e.Column.SortDirection = new_sort_desc.Direction;
+ if (KeyboardExtensions.IsShiftDown()) {
+ if (vm.rows_view.SortDescriptions.TryGetFirst(sd => sd.PropertyName == e.Column.SortMemberPath, out var match, out int index)) {
+ vm.rows_view.SortDescriptions[index] = new_sort_desc;
+ } else {
+ vm.rows_view.SortDescriptions.Add(new_sort_desc);
+ }
+ } else {
+ vm.rows_view.SortDescriptions.Clear();
+ foreach (var col in view.data_grid.Columns.Except(new[] { e.Column }))
+ col.SortDirection = null;
+ vm.rows_view.SortDescriptions.Add(new_sort_desc);
+ }
+ }
+ }
+ /// Ensures that the primary sort description property (i.e., at index 0) is the placeholder_key.
+ /// This behavior has the effect of grouping placeholder rows at the bottom, without using (which is incompatible with row virtualization).
+ IDisposable apply_sort() =>
+ Disposable.Create(() => {
+ var pk_sort_desc = new SortDescription(nameof(ManualFillRow.placeholder_key), ListSortDirection.Ascending);
+ if (vm.rows_view.SortDescriptions.Count > 0) {
+ if (vm.rows_view.SortDescriptions[0].Equals(pk_sort_desc))
+ return;
+ vm.rows_view.SortDescriptions.removeFirst(sd => sd.PropertyName == pk_sort_desc.PropertyName);
+ }
+ vm.rows_view.SortDescriptions.Insert(0, pk_sort_desc);
+ });
+
+ ManualFillsSettings get_settings() =>
+ new ManualFillsSettings(last_sorting_criterion);
+ }
+ }
+
+ static string _col_id(DataGridColumn col) =>
+ DataGridEx.GetCellKey(col)?.ToString();
+
+ readonly struct ManualFillsConfig {
+ public readonly bool modal_transactions;
+ public readonly string thread_id;
+
+ ManualFillsConfig(string thread_id, bool modal_transactions) {
+ this.thread_id = thread_id;
+ this.modal_transactions = modal_transactions;
+ }
+
+ public static ManualFillsConfig read() => new ManualFillsConfig(
+ mbts.config.Configuration.get().manual_fills ? window_type : null,
+ mbts.config.Configuration.get().modal_transactions);
+ }
+
+ static class CommandGroups {
+ public const string
+ Add = "Add",
+ Save = "Save",
+ Revert = "Revert";
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs
index 85f7222d4..76daca299 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs
@@ -34,7 +34,7 @@ namespace mbts.spark {
// This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup.
interface ICVOrderBookColumn : IKeyedColumn, IGridColumn {
ListSortDirection? SortDirection { get; set; }
- IDataGridColumnFilter filter { get; }
+ IDataGridColumnFilter filter { get; }
IComparer comparer { get; }
}
@@ -70,7 +70,7 @@ namespace mbts.spark {
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable added, IEnumerable removed)> order_securities) {
// security
Add(security_column = new SecurityColumn(
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
order_securities,
ort => ort.security ?? SecurityDataHelper.Defaults.SecurityImmutable,
SecurityCriteria.from_securities,
@@ -85,7 +85,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Symbol,
r => r.symbol,
DefaultColumnWidths.Symbol,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(),
ort => ort.security?.Symbol ?? string.Empty,
nameof(OrderBookRowVM.symbol)
@@ -98,7 +98,7 @@ namespace mbts.spark {
"Time",
r => r.time_created_text,
DefaultColumnWidths.Time,
- new TimeFilterVM(
+ new TimeFilterVM(
ort => ort.order.created(),
nameof(OrderBookRowVM.time_created)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -109,7 +109,7 @@ namespace mbts.spark {
"Last Change",
r => r.last_change_text,
DefaultColumnWidths.Time,
- new TimeFilterVM(
+ new TimeFilterVM(
ort => ort.order.last_change(),
nameof(OrderBookRowVM.last_change)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -120,7 +120,7 @@ namespace mbts.spark {
DefaultColumnHeaders.User,
r => r.user,
DefaultColumnWidths.User,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
model.factory.subscribe_users().Select(d => d.Values),
ort => ort.order.user(),
nameof(OrderBookRowVM.user)),
@@ -132,7 +132,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Account,
r => r.account,
DefaultColumnWidths.Account,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
model.factory.subscribe_accounts().Select(d => d.Values),
ort => ort.order.account(),
vals => vals.ToArray(),
@@ -146,7 +146,7 @@ namespace mbts.spark {
DefaultColumnHeaders.Exchange,
r => r.exchange.ToString(),
DefaultColumnWidths.Exchange,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
EnumHelper.get_values_except(Venue.Unset).ToList(),
ort => ort.security.exchange_or_default(),
nameof(OrderBookRowVM.exchange)),
@@ -158,7 +158,7 @@ namespace mbts.spark {
DefaultColumnHeaders.TimeInForce,
r => r.time_in_force.ToString(),
DefaultColumnWidths.TimeInForce,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
EnumHelper.get_values().ToList(),
ort => ort.order.time_in_force(),
nameof(OrderBookRowVM.time_in_force)),
@@ -174,9 +174,8 @@ namespace mbts.spark {
nameof(OrderBookRowVM.badge_fill),
nameof(OrderBookRowVM.display_name),
_wrap_comparer(r => r.order_type),
- DiscreteValuesFilterVM.CreateTableUpdate(
+ DiscreteValuesFilterVM.CreateTableUpdate(
o => new AlgoDataVM(o.algo.GetValueOrDefault()),
- o => AlgoID.from_order_def(o.order.Def),
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;
@@ -187,9 +186,8 @@ namespace mbts.spark {
nameof(OrderBookRowVM.root_algo_badge_fill),
nameof(OrderBookRowVM.root_algo_display_name),
_wrap_comparer(r => r.order_tuple.root_algo.value.CustomCase),
- DiscreteValuesFilterVM.CreateTableUpdate(
+ DiscreteValuesFilterVM.CreateTableUpdate(
o => new AlgoDataVM(o.root_algo),
- o => AlgoID.from_algo_key(o.root_algo.key),
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));
@@ -201,7 +199,7 @@ namespace mbts.spark {
"Sub Type",
r => r.order_sub_type_text,
80,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
EnumHelper.get_values().ToList(),
ort => ort.order.sub_type(),
nameof(OrderBookRowVM.order_sub_type)),
@@ -209,27 +207,27 @@ namespace mbts.spark {
_wrap_comparer(r => r.order_sub_type)));
// side
Add(side_column = new SideColumn(
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
new[] { Side.Buy, Side.Sell },
- ort=> ort.order.side(),
+ ort => ort.order.side(),
nameof(OrderBookRowVM.side))));
// quantity
Add(qty_column = new SizeColumn(
- new UIntMinMax(ort => ort.order.quantity(), nameof(OrderBookRowVM.quantity))));
+ new UIntMinMax(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(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
+ new UIntMinMax(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
// price
Add(price_column = new SimpleTextColumn(
Columns.Price,
"Price",
r => r.price_text,
DefaultColumnWidths.Price,
- new PriceMinMax(
+ new PriceMinMax(
ort => ort.order.price(),
nameof(OrderBookRowVM.price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -245,7 +243,7 @@ namespace mbts.spark {
"Avg Price",
r => r.avg_price_text,
DefaultColumnWidths.Price,
- new PriceMinMax(
+ new PriceMinMax(
ort => ort.order.avg_price(),
nameof(OrderBookRowVM.avg_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -256,18 +254,21 @@ namespace mbts.spark {
"Last Filled",
r => r.last_price_text,
DefaultColumnWidths.Price,
- new PriceMinMax(
+ new PriceMinMax(
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(ort => ort.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq))));
// status
Add(status_column = new SimpleTextColumn(
Columns.Status,
"Status",
r => r.status.ToString(),
80,
- DiscreteValuesFilterVM.Create(
+ DiscreteValuesFilterVM.Create(
EnumHelper.get_values().ToList(),
ort => ort.order.status(),
nameof(OrderBookRowVM.status)),
@@ -275,7 +276,7 @@ namespace mbts.spark {
_wrap_comparer(r => r.status)));
// last message
Add(last_message_column = new OrderBookLastMessageColumn(
- new RegexFilterVM(
+ new RegexFilterVM(
ort => ort.order.last_msg(),
nameof(OrderBookRowVM.last_msg))));
// security key
@@ -284,7 +285,7 @@ namespace mbts.spark {
DefaultColumnHeaders.SecurityKey,
r => r.security_key.ToString(),
DefaultColumnWidths.SecurityKey,
- new RegexFilterVM(
+ new RegexFilterVM(
ort => ort.order.security_key().ToString(),
nameof(OrderBookRowVM.security_key)),
DataGridFilterKnownTemplates.Regex,
@@ -295,7 +296,7 @@ namespace mbts.spark {
DefaultColumnHeaders.OrderKey,
r => r.order_key.ToString(),
DefaultColumnWidths.OrderKey,
- new RegexFilterVM(
+ new RegexFilterVM(
ort => ort.order.Key.ToString(),
nameof(OrderBookRowVM.order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -306,7 +307,7 @@ namespace mbts.spark {
"Parent Key",
r => r.parent_order_key.ToString(),
DefaultColumnWidths.ParentKey,
- new RegexFilterVM(
+ new RegexFilterVM(
ort => ort.order.ParentKey.ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -317,7 +318,7 @@ namespace mbts.spark {
DefaultColumnHeaders.AttachedTargetOrderKey,
r => r.order.attached_target_order_key().ToString(),
DefaultColumnWidths.AttachedTargetOrderKey,
- new RegexFilterVM(
+ new RegexFilterVM(
ort => ort.order.attached_target_order_key().ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -350,6 +351,7 @@ namespace mbts.spark {
public SimpleTextColumn order_key_column { get; }
public SimpleTextColumn parent_key_column { get; }
public SimpleTextColumn attached_target_order_key_column { get; }
+ public PiqColumn piq_column { get; }
public FilterStates create_filter_states() =>
new FilterStates {
@@ -374,7 +376,8 @@ namespace mbts.spark {
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()
+ symbols = symbol_column.filter.get_state(),
+ piq = piq_column.filter.get_state()
};
public (FilterStates filters, IReadOnlyList sorting) create() =>
@@ -404,6 +407,7 @@ 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);
+ piq_column.filter.load_state(fs.piq);
}
_active_comparers.Clear();
foreach (var col in this)
@@ -424,9 +428,9 @@ namespace mbts.spark {
}
}
- public Func get_filter() {
+ public Func get_filter() {
var active_filters = this.OfType().Where(c => c.filter.active.GetValueOrDefault()).Select(c => c.filter).ToArray();
- return active_filters.Length == 0 ? null : new Func(r => active_filters.All(f => f.filter(r)));
+ return active_filters.Length == 0 ? null : new Func(r => active_filters.All(f => f.filter(r)));
}
public OrderBookSortingData get_sorting_data() {
@@ -527,7 +531,7 @@ namespace mbts.spark {
GlyphContext _root_glyph_context, _child_glyph_context;
protected OrderbookColumnBase(Columns col_key, string header, Func get_text, double width,
- IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) : base(col_key) {
+ IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) : base(col_key) {
id = key.ToString();
Width = width;
Header = header;
@@ -544,10 +548,10 @@ namespace mbts.spark {
}
}
- public IDataGridColumnPersistentFilter filter { get; }
+ public IDataGridColumnPersistentFilter filter { get; }
public IComparer comparer { get; }
- IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
+ IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => _filter_template;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -561,7 +565,7 @@ namespace mbts.spark {
public class SimpleTextColumn : OrderbookColumnBase, IRenderColumn {
public SimpleTextColumn(Columns key, string header, Func get_text, double width,
- IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer)
+ IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer)
: base(key, header, get_text, width, filter, filter_template, comparer) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -571,7 +575,7 @@ namespace mbts.spark {
#region Explicit Column Defs
public class SideColumn : OrderbookColumnBase, IRenderColumn {
- public SideColumn(IDataGridColumnPersistentFilter filter)
+ public SideColumn(IDataGridColumnPersistentFilter 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) =>
@@ -580,7 +584,7 @@ namespace mbts.spark {
}
public class SizeColumn : OrderbookColumnBase, IRenderColumn {
- public SizeColumn(IDataGridColumnPersistentFilter filter)
+ public SizeColumn(IDataGridColumnPersistentFilter 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) =>
@@ -589,7 +593,7 @@ namespace mbts.spark {
}
public class FilledColumn : OrderbookColumnBase, IRenderColumn {
- public FilledColumn(IDataGridColumnPersistentFilter filter)
+ public FilledColumn(IDataGridColumnPersistentFilter 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) =>
@@ -601,7 +605,7 @@ namespace mbts.spark {
readonly BindingBase _foreground_binding;
ListSortDirection? _cached_sort_direction;
- public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer row_comparer, IDataGridColumnPersistentFilter filter, string header = DefaultColumnHeaders.OrderType)
+ public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer row_comparer, IDataGridColumnPersistentFilter 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;
@@ -611,11 +615,11 @@ namespace mbts.spark {
this.comparer = row_comparer;
}
- public new IDataGridColumnPersistentFilter filter { get; }
+ public new IDataGridColumnPersistentFilter filter { get; }
public override string filter_template => DataGridFilterKnownTemplates.AlgoType;
public IComparer comparer { get; }
- IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
+ IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
public override FrameworkElement view_factory() {
@@ -633,7 +637,7 @@ namespace mbts.spark {
public class OrderBookLastMessageColumn : TextColumn, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
- public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter filter)
+ public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter filter)
: base(Columns.LastMessage, new Binding(nameof(OrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) {
id = key.ToString();
this.filter = filter;
@@ -642,10 +646,10 @@ namespace mbts.spark {
tooltip_binding = new Binding(nameof(OrderBookRowVM.last_msg));
}
- public new IDataGridColumnPersistentFilter filter { get; }
+ public new IDataGridColumnPersistentFilter filter { get; }
public IComparer comparer => _wrap_comparer(r => r.last_msg);
- IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
+ IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
@@ -654,6 +658,15 @@ namespace mbts.spark {
}
}
+ public class PiqColumn : OrderbookColumnBase, IRenderColumn {
+ public PiqColumn(IDataGridColumnPersistentFilter 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, 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 };
@@ -661,7 +674,7 @@ namespace mbts.spark {
ListSortDirection? _cached_sort_direction;
- public SecurityColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Security) {
+ public SecurityColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Security) {
id = key.ToString();
this.filter = filter;
_foreground_binding = RenderUtils.get_foreground_binding(this);
@@ -670,10 +683,10 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
- public IDataGridColumnPersistentFilter filter { get; }
+ public IDataGridColumnPersistentFilter filter { get; }
public IComparer comparer => _wrap_comparer(r => r.security, SecurityHelper.Comparer.InstanceImmutable.to_nullable());
- IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
+ IDataGridColumnFilter ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs
index 97314434b..e9a7d3b6b 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs
@@ -14,7 +14,7 @@ using System.Windows.Media;
using Columns = mbts.spark.OrderBookGridView.ColumnKeys;
namespace mbts.spark {
- partial class OrderBookRowVM : IEquatable, DIYGrid.IRowVM, IHierarchicalRow, INotifyPropertyChanged {
+ partial class OrderBookRowVM : IEquatable, DIYGrid.IRowVM, IHierarchicalRow, INotifyPropertyChanged {
const string _unknown_security_price_format_string = "0.#########";
const int _unknown_security_price_num_fractional_digits = 9;
readonly OrderBookVM _owner;
@@ -28,7 +28,7 @@ namespace mbts.spark {
uint _prospective_quantity;
double _prospective_price;
- public OrderBookRowVM(OrderBookVM owner, OrderSecurityAlgoMeta order_tuple, bool is_expanded) {
+ public OrderBookRowVM(OrderBookVM owner, OrderSecurity order_tuple, bool is_expanded) {
_owner = owner;
this.order_tuple = order_tuple;
is_visible = !is_child;
@@ -43,19 +43,19 @@ namespace mbts.spark {
//// when the OrderBookVM.selected_order_changes, this emulates the selected
//// order changing since the current_row setter invokes the selected_order_changed
//// handler
- public IObservable subscribe_data() {
- return Observable.FromEvent(
+ public IObservable subscribe_data() {
+ return Observable.FromEvent(
cb => () => cb(order_tuple),
cb => invalidated += cb,
cb => invalidated -= cb);
}
public event Action invalidated;
- public event Action<(OrderSecurityAlgoMeta oldval, OrderSecurityAlgoMeta newval)> updated;
+ public event Action<(OrderSecurity oldval, OrderSecurity newval)> updated;
public event PropertyChangedEventHandler PropertyChanged;
// Core
- public OrderSecurityAlgoMeta order_tuple { get; private set; }
+ public OrderSecurity order_tuple { get; private set; }
public OrderRecordImmutable order => order_tuple.order;
public OrderMetadata order_metadata => _owner.get_metadata(this);
public Brush badge_fill => _badge_fill ?? (_badge_fill = OrderUtils.badge_fill(order_tuple.meta, order_metadata));
@@ -91,6 +91,8 @@ namespace mbts.spark {
public uint quantity => order.quantity();
public uint filled_quantity => order.filled();
public string last_msg => order.last_msg();
+ public uint piq => order_tuple.piq ?? uint.MaxValue;
+ public string piq_text => piq == uint.MaxValue ? string.Empty : piq.ToString();
public bool is_non_terminal => order.is_non_terminal();
public bool is_attachable { get => _is_attachable; set => SetVisual(ref _is_attachable, value); }
public bool is_detachable { get => _is_detachable; set => SetVisual(ref _is_detachable, value); }
@@ -134,14 +136,14 @@ namespace mbts.spark {
}
}
}
- public bool is_qty_dirty => this.prospective_quantity != this.quantity;
+ public bool is_qty_dirty => this.prospective_quantity != this.quantity;
public bool is_price_dirty => this.prospective_price != this.price;
// Commands
public ICommand toggle_command => _toggle_expanded_cmd ?? (
_toggle_expanded_cmd = new DelegateCommand(() => is_expanded = !is_expanded));
- public ICommand show_order_modify_cmd =>
+ public ICommand show_order_modify_cmd =>
_show_order_modify_cmd ?? (_show_order_modify_cmd = new DelegateCommand(() => _owner.show_order_modify(this), () => status == OrderStatus.Working));
public ICommand cancel_command => _cancel_cmd ??
@@ -195,7 +197,7 @@ namespace mbts.spark {
public ICommand update_command => _update_command ?? (
_update_command = new DelegateCommand(() => {
- _select_me();
+ _select_me();
})
);
@@ -214,7 +216,7 @@ namespace mbts.spark {
bool IHierarchicalRow.is_parent => is_parent;
bool IHierarchicalRow.is_expanded => is_expanded;
int IHierarchicalRow.depth_level => depth_level;
- OrderSecurityAlgoMeta IHierarchicalRow.value => order_tuple;
+ OrderSecurity IHierarchicalRow.value => order_tuple;
void IHierarchicalRow.on_is_parent_changed(bool is_parent) => this.is_parent = is_parent;
/// Do NOT actually call the setter (it has side effects) - the row collection calls this method when the row is expanded/collapsed by some **external means, outside of this class.
@@ -226,7 +228,7 @@ namespace mbts.spark {
///
void IHierarchicalRow.on_is_expanded_changed(bool is_expanded) => Set(ref _is_expanded, is_expanded, nameof(is_expanded));
void IHierarchicalRow.on_depth_level_changed(int depth_level) => this.depth_level = depth_level;
- void IHierarchicalRow.on_value_changed(OrderSecurityAlgoMeta value) => update(value);
+ void IHierarchicalRow.on_value_changed(OrderSecurity value) => update(value);
#endregion
private void _unselect_me() {
@@ -244,7 +246,7 @@ namespace mbts.spark {
internal void expand_internal() => Set(ref _is_expanded, true, nameof(is_expanded));
internal void collapse_internal() => Set(ref _is_expanded, false, nameof(is_expanded));
- public void update(OrderSecurityAlgoMeta order_tuple) {
+ public void update(OrderSecurity order_tuple) {
Log.assert(order_tuple.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key.");
// _show_order_modify_cmd is lazy (instantiated in the default_command getter); it might be null, don't not force instantiation
bool? could_modify_execute = _show_order_modify_cmd?.CanExecute(null);
@@ -257,11 +259,11 @@ namespace mbts.spark {
// quantity
if ((Columns.Size & dirty) != 0)
RaisePropertyChanged(nameof(quantity), nameof(is_qty_dirty));
- // we need to update the prospective_quantity here b/c an update could have come in while the row was in edit mode
- // via the Mini OB update column mechanism (vs the EditableQty column)
- // prospecive price does not need to be updated in the same manner b/c if the price is changed, the whole
- // row will no longer match the filter
- prospective_quantity = quantity;
+ // we need to update the prospective_quantity here b/c an update could have come in while the row was in edit mode
+ // via the Mini OB update column mechanism (vs the EditableQty column)
+ // prospecive price does not need to be updated in the same manner b/c if the price is changed, the whole
+ // row will no longer match the filter
+ prospective_quantity = quantity;
// price
if ((Columns.Price & dirty) != 0) {
RaisePropertyChanged(nameof(price));
@@ -314,6 +316,9 @@ namespace mbts.spark {
// this will update the cancel column in the mini ob
cancel_command.TryRaiseCanExecuteChanged();
}
+ if ((Columns.Piq & dirty) != 0) {
+ RaisePropertyChanged(nameof(piq), nameof(piq_text));
+ }
// always refresh attach and detach b/c
// conditionally raise invalidated
if ((dirty & ViewRefresh.invalidate_mask) != 0)
@@ -374,13 +379,14 @@ namespace mbts.spark {
Columns.Status |
Columns.ParentKey |
Columns.AttachedTargetOrderKey |
- Columns.LastMessage,
+ Columns.LastMessage |
+ Columns.Piq,
filled_status_desc_mask =
Columns.Filled |
Columns.AvgFilled |
Columns.Status;
- public static Columns get_dirty_cells(OrderSecurityAlgoMeta oldval, OrderSecurityAlgoMeta newval) {
+ public static Columns get_dirty_cells(OrderSecurity oldval, OrderSecurity newval) {
var dirty = (Columns)0;
if (oldval.security != newval.security)
dirty |= Columns.Security;
@@ -404,8 +410,11 @@ namespace mbts.spark {
dirty |= Columns.Status;
if (oldval.order.last_msg() != newval.order.last_msg())
dirty |= Columns.LastMessage;
+ if (oldval.piq != newval.piq) {
+ dirty |= Columns.Piq;
+ }
return dirty;
}
}
}
-}
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs
index 45a77f7bc..cff54d5c4 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs
@@ -42,7 +42,7 @@ namespace mbts.spark {
readonly OrdersModel _model;
readonly Property _current_row;
readonly DelegateProperty _show_order_params, _show_ladder, _show_fills, _can_attach_selected_orders, _can_detach_selected_orders;
- readonly OperableHierarchicalCollection _row_collection;
+ readonly OperableHierarchicalCollection