diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs
index 5ac03d359..4158bd0c8 100644
--- a/src/client/spark/Images/Icons.cs
+++ b/src/client/spark/Images/Icons.cs
@@ -22,7 +22,9 @@ namespace mbts.ui {
AddBoxesGeometryKey = nameof(AddBoxesGeometryKey),
AddFileGeometryKey = nameof(AddFileGeometryKey),
AddFileThinGeometryKey = nameof(AddFileThinGeometryKey),
+ AttachAlgosGeometryKey = nameof(AttachAlgosGeometryKey),
CheckMarkGeometryKey = nameof(CheckMarkGeometryKey),
+ DetachAlgosGeometryKey = nameof(DetachAlgosGeometryKey),
DiskGeometryKey = nameof(DiskGeometryKey),
DiskFileGeometryKey = nameof(DiskFileGeometryKey),
DocumentGeometryKey = nameof(DocumentGeometryKey),
@@ -39,6 +41,7 @@ namespace mbts.ui {
PaymentGeometryKey = nameof(PaymentGeometryKey),
PencilGeometryKey = nameof(PencilGeometryKey),
PlayGeometryKey = nameof(PlayGeometryKey),
+ ProhibitedGeometryKey = nameof(ProhibitedGeometryKey),
StarGeometryKey = nameof(StarGeometryKey),
ToolsGeometryKey = nameof(ToolsGeometryKey),
TrashGeometryKey = nameof(TrashGeometryKey),
@@ -115,6 +118,7 @@ namespace mbts.ui {
public static ImageSource AddBoxes => create_icon(AddBoxesGeometryKey);
public static ImageSource AddEncircled { get { return load_resource_and_freeze("AddEncircled"); } }
public static ImageSource AddFile => create_icon(Smashicons.AddFileGeometryKey);
+ public static ImageSource AttachAlgos => create_icon(AttachAlgosGeometryKey);
public static ImageSource Beaker { get { return load_resource_and_freeze("Beaker"); } }
public static ImageSource Book { get { return load_resource_and_freeze("Book"); } }
@@ -139,6 +143,7 @@ namespace mbts.ui {
public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey);
public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } }
public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } }
+ public static ImageSource DetachAlgos => create_icon(DetachAlgosGeometryKey);
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"); } }
@@ -158,6 +163,7 @@ namespace mbts.ui {
public static ImageSource Knight { get { return load_resource_and_freeze("Knight"); } }
public static ImageSource Payment => create_icon(PaymentGeometryKey);
public static ImageSource Pencil => create_icon(PencilGeometryKey);
+ public static ImageSource Prohibited => create_icon(ProhibitedGeometryKey);
public static ImageSource RedoCircular => create_icon(UndoCircularGeometryKey, Brushes.Black, null, new ScaleTransform(-1, 1));
public static ImageSource Spawn { get { return load_resource_and_freeze("Spawn"); } }
public static ImageSource Star => create_icon(StarGeometryKey);
diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml
index 9cba2864c..906aab109 100644
--- a/src/client/spark/Images/Vector/Icons.xaml
+++ b/src/client/spark/Images/Vector/Icons.xaml
@@ -40,6 +40,69 @@
+
+
+
+ M51.173,3.801c-5.068-5.068-13.315-5.066-18.384,0l-9.192,9.192c-0.781,0.781-0.781,2.047,0,2.828
+ c0.781,0.781,2.047,0.781,2.828,0l9.192-9.192c1.691-1.69,3.951-2.622,6.363-2.622c2.413,0,4.673,0.932,6.364,2.623
+ s2.623,3.951,2.623,6.364c0,2.412-0.932,4.672-2.623,6.363L36.325,31.379c-3.51,3.508-9.219,3.508-12.729,0
+ c-0.781-0.781-2.047-0.781-2.828,0s-0.781,2.048,0,2.828c2.534,2.534,5.863,3.801,9.192,3.801s6.658-1.267,9.192-3.801
+ l12.021-12.021c2.447-2.446,3.795-5.711,3.795-9.192C54.968,9.512,53.62,6.248,51.173,3.801z
+
+
+ M27.132,40.57l-7.778,7.778c-1.691,1.691-3.951,2.623-6.364,2.623c-2.412,0-4.673-0.932-6.364-2.623
+ c-3.509-3.509-3.509-9.219,0-12.728L17.94,24.306c1.691-1.69,3.951-2.622,6.364-2.622c2.412,0,4.672,0.932,6.363,2.622
+ c0.781,0.781,2.047,0.781,2.828,0s0.781-2.047,0-2.828c-5.067-5.067-13.314-5.068-18.384,0L3.797,32.793
+ c-2.446,2.446-3.794,5.711-3.794,9.192c0,3.48,1.348,6.745,3.795,9.191c2.446,2.447,5.711,3.795,9.191,3.795
+ c3.481,0,6.746-1.348,9.192-3.795l7.778-7.778c0.781-0.781,0.781-2.047,0-2.828S27.913,39.789,27.132,40.57z
+
+
+
+
+
+
+ M462.557,77.627c-14.323-25.556-41.488-41.423-70.889-41.423c-13.835,0-27.54,3.585-39.602,10.364
+ l-152.557,85.635l17.55,31.279l152.565-85.635c6.747-3.78,14.371-5.779,22.069-5.779c16.428,0,31.596,8.852,39.594,23.11
+ c5.909,10.535,7.356,22.752,4.072,34.408c-3.268,11.656-10.876,21.346-21.411,27.255l-138.291,77.604
+ c-2.634-16.851-10.494-32.392-22.793-44.699c-21.687-21.663-56.063-29.328-84.935-18.964l-12.485,4.495l12.128,33.734
+ l12.534-4.471c16.127-5.869,35.319-1.496,47.406,10.567c6.974,6.982,11.388,15.826,12.786,25.41
+ c-0.585-0.138-1.171-0.285-1.731-0.447c-11.681-3.284-21.354-10.9-27.271-21.476l-6.519-11.518l-31.303,17.59l6.56,11.518
+ c10.6,18.915,27.93,32.571,48.836,38.44c0.723,0.187,1.455,0.39,2.187,0.561c-1.105,1.398-2.284,2.731-3.536,3.983
+ l-114.32,114.328c-8.551,8.543-19.931,13.241-32.035,13.241c-12.112,0-23.492-4.698-32.027-13.241
+ c-8.535-8.543-13.233-19.907-13.233-32.027c0-12.112,4.698-23.483,13.233-32.018l99.291-99.282l-25.369-25.369l-99.282,99.282
+ C8.446,319.427,0,339.806,0,361.468c0,21.679,8.446,42.049,23.776,57.396c15.339,15.339,35.709,23.768,57.388,23.768
+ s42.049-8.429,57.388-23.768l114.345-114.32c8.372-8.405,14.81-18.566,18.842-29.71c6.625-1.764,12.924-4.3,18.777-7.6
+ l140.99-79.115c18.875-10.608,32.514-27.946,38.375-48.828C475.749,118.4,473.148,96.493,462.557,77.627z
+
+
+ M173.171,141.769c4.503-0.821,7.511-5.145,6.69-9.657l-17.103-94.942
+ c-0.821-4.519-5.162-7.527-9.665-6.722c-4.511,0.821-7.527,5.145-6.706,9.673l17.111,94.925
+ C164.311,139.575,168.644,142.574,173.171,141.769z
+
+
+ M43.561,191.776l94.934-17.119c4.519-0.821,7.527-5.145,6.706-9.657
+ c-0.821-4.528-5.145-7.543-9.649-6.722L40.61,175.405c-4.503,0.797-7.519,5.145-6.698,9.657
+ C34.717,189.582,39.058,192.589,43.561,191.776z
+
+
+
+
+
+ M32.759,0C14.696,0,0,14.695,0,32.759s14.695,32.759,32.759,32.759s32.759-14.695,32.759-32.759S50.822,0,32.759,0z
+ M6,32.759C6,18.004,18.004,6,32.759,6c6.648,0,12.734,2.443,17.419,6.472L12.472,50.178C8.443,45.493,6,39.407,6,32.759z
+ M32.759,59.518c-5.948,0-11.447-1.953-15.895-5.248l37.405-37.405c3.295,4.448,5.248,9.947,5.248,15.895
+ C59.518,47.514,47.514,59.518,32.759,59.518z
+
+
4
@@ -559,71 +557,14 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ />
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs
index 2cfd8b971..95214f635 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs
@@ -1,8 +1,6 @@
using mbts.spark;
using mbts.ui.converters;
-using mbts.ui.extensions;
using System;
-using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
@@ -18,26 +16,11 @@ namespace mbts.ui.spark {
public AlgoStudioView() {
InitializeComponent();
DataContextChanged += (s, e) => set_controller();
- content_host.PreviewMouseMove += content_host_PreviewMouseMove;
- content_host.MouseEnter += content_host_MouseEnter;
- content_host.MouseLeave += content_host_MouseLeave;
set_controller();
// local methods
void set_controller() => Disposable.replace(ref _controller, AlgoStudioViewControllerFactory.create(DataContext, _tree_view, name_text_box, custom_badge_color_picker_button, custom_badge_color_picker_popup));
- void content_host_PreviewMouseMove(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
- void content_host_MouseEnter(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
- void content_host_MouseLeave(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
- void refresh_is_mouse_over_content_host(MouseEventArgs e) => content_host.set_current_if_changed(IsMouseOverNodeContentProperty, this.ChildAtPoint(e.GetPosition(this)) == content_host);
}
- #region IsMouseOverNodeContent
- public static readonly DependencyProperty IsMouseOverNodeContentProperty =
- DependencyProperty.RegisterAttached("IsMouseOverNodeContent", typeof(bool), typeof(AlgoStudioView), new PropertyMetadata(false));
-
- public static bool GetIsMouseOverNodeContent(DependencyObject d) => (bool)d.GetValue(IsMouseOverNodeContentProperty);
- public static void SetIsMouseOverNodeContent(DependencyObject d, bool value) => d.SetValue(IsMouseOverNodeContentProperty, value);
- #endregion
-
public new AlgoStudioVM DataContext {
get => base.DataContext as AlgoStudioVM;
set => base.DataContext = value;
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs
index d3dd820fb..73ec53f5a 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs
@@ -13,7 +13,7 @@ using System.Windows;
using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData;
namespace mbts.spark {
- internal class AlgoStudioWindow : SparkWindow, IShellWindow {
+ internal class AlgoStudioWindow : SparkWindow, ISharedWindow {
public const string
NAME = "Algo Studio",
TemplatesEnabledKey = nameof(TemplatesEnabledKey),
@@ -37,7 +37,7 @@ namespace mbts.spark {
: base(NAME, bus, factory, SparkCommands.ShowAlgoStudio.icon) {
_model = model;
_state = state;
- thread_init();
+ thread_id = config.Configuration.get().algo_studio ? "AlgoStudio" : null;
}
public override StartupData SaveState => _state = _vm.create();
@@ -45,12 +45,12 @@ namespace mbts.spark {
public override string window_type => NAME;
public override UIElement Content => _view;
public override IEnumerable Commands => _commands;
- public string thread_id => NAME;
public override double MinWidth =>
SPARK_MENU_COLLAPSED_WIDTH +
LAUNCHER_BUTTON_BORDER_WIDTH +
DEFAULT_CONTENT_WIDTH;
public override double MinHeight => DEFAULT_CONTENT_HEIGHT;
+ public string thread_id { get; }
bts.config.AlgoStudioOptions _ui_configuration => _model.algo_model.ui_configuration;
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs
index fb2c0666e..e45184344 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs
@@ -1,8 +1,9 @@
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
-using ProtoBuf;
+using mbts.ui.utility;
using System;
+using System.Collections.Generic;
using System.Linq;
namespace mbts.spark {
@@ -10,12 +11,6 @@ namespace mbts.spark {
public readonly string name;
public readonly AlgoStructureKey structure;
- public AlgoNameStructureKey(CustomOrderDefinitionImmutable definition)
- : this(definition.CustomCase.type_id(), definition) { }
-
- public AlgoNameStructureKey(string name, CustomOrderDefinitionImmutable definition)
- : this(name, new AlgoStructureKey(definition)) { }
-
public AlgoNameStructureKey(CustomOrderDefinition.CustomOneofCase base_type)
: this(base_type.type_id(), new AlgoStructureKey(base_type)) { }
@@ -31,31 +26,22 @@ namespace mbts.spark {
public static bool operator !=(AlgoNameStructureKey a, AlgoNameStructureKey b) => !a.Equals(b);
}
- [ProtoContract]
struct AlgoStructureKey : IEquatable {
- [ProtoMember(1)]
readonly int[] _structure;
public AlgoStructureKey(CustomOrderDefinition.CustomOneofCase base_type)
: this(new[] { (int)base_type }) { }
- public AlgoStructureKey(CustomOrderDefinitionImmutable definition) {
- int[] s = new[] { (int)definition.CustomCase };
- _build_structure(definition, ref s, 1);
- _structure = s;
- }
+ public AlgoStructureKey(CustomOrderDefinitionImmutable definition, IMaskIndexInt32 dynamic_type_index) =>
+ _structure = AlgoStructureSerializer.to_array(definition, dynamic_type_index);
public AlgoStructureKey(int[] structure) =>
_structure = structure;
- public CustomOrderDefinitionImmutable build_def() {
- int pos = 0;
- var mdef = new CustomOrderDefinition();
- _build_def(_structure, ref pos, ref mdef);
- return new CustomOrderDefinitionImmutable(mdef);
- }
+ public IReadOnlyList structure => _structure ?? Array.Empty();
public bool Equals(AlgoStructureKey other) =>
+ /// is not optimized to check Count/Length, since the args are .
_structure.Length == other._structure.Length &&
_structure.SequenceEqual(other._structure);
@@ -67,35 +53,105 @@ namespace mbts.spark {
public static bool operator ==(AlgoStructureKey a, AlgoStructureKey b) => a.Equals(b);
public static bool operator !=(AlgoStructureKey a, AlgoStructureKey b) => !a.Equals(b);
+ }
- static void _build_structure(CustomOrderDefinitionImmutable definition, ref int[] structure, int pos) =>
- _build_structure(definition.CloneToMutable(), ref structure, pos);
+ static class AlgoStructureSerializer {
+ const int
+ _dynamic_mask = 1 << 31,
+ _child_mask_offset = 30;
- static void _build_structure(CustomOrderDefinition algo, ref int[] structure, int pos) {
- var cad = OrderDataHelper.get_child_algo_data(algo);
- for (int di = 0; di < cad.Count; di++) {
- if (cad[di].get_child(algo) is CustomOrderDefinition child_algo) {
- ArrayHelper.ensure_capacity(ref structure, pos + 1);
- int del_mask = 1 << (31 - di);
- structure[pos++] = (int)child_algo.CustomCase | del_mask;
- _build_structure(child_algo, ref structure, pos);
- break;
- }
- }
- ArrayHelper.trim(ref structure, pos);
+ public static CustomOrderDefinitionImmutable build_algoi(this AlgoStructureKey structure_key, DynamicOrderHelper dynamic_helper) =>
+ parsei(structure_key.structure, dynamic_helper);
+
+ public static CustomOrderDefinitionImmutable build_algo(this AlgoStructureKey structure_key, DynamicOrderHelper dynamic_helper) =>
+ parsei(structure_key.structure, dynamic_helper);
+
+ public static AlgoStructureKey structure_key(CustomOrderDefinitionImmutable algo, IMaskIndexInt32 dynamic_type_index) =>
+ new AlgoStructureKey(to_array(algo, dynamic_type_index));
+
+ public static AlgoStructureKey structure_key(CustomOrderDefinition algo, IMaskIndexInt32 dynamic_type_index) =>
+ new AlgoStructureKey(to_array(algo, dynamic_type_index));
+
+ public static int[] to_array(CustomOrderDefinitionImmutable algo, IMaskIndexInt32 dynamic_type_index) =>
+ to_array(algo.CloneToMutable(), dynamic_type_index);
+
+ public static int[] to_array(CustomOrderDefinition algo, IMaskIndexInt32 dynamic_type_index) {
+ int[] s = new[] { (int)algo.CustomCase };
+ _build_structure(algo, ref s, dynamic_type_index);
+ return s;
}
- static void _build_def(int[] structure, ref int pos, ref CustomOrderDefinition algo) {
- for (int i = pos; i < structure.Length; i++) {
+ public static CustomOrderDefinitionImmutable from_array(int[] structure, DynamicOrderHelper dynamic_helper) =>
+ parsei(structure, dynamic_helper);
+
+ public static CustomOrderDefinitionImmutable parsei(IReadOnlyList structure, DynamicOrderHelper dynamic_helper) =>
+ new CustomOrderDefinitionImmutable(parse(structure, dynamic_helper));
+
+ public static CustomOrderDefinition parse(IReadOnlyList structure, DynamicOrderHelper dynamic_helper) {
+ if (structure == null || structure.Count == 0)
+ return new CustomOrderDefinition();
+ int pos = 1;
+ var mdef = OrderDataHelper.create_algo((CustomOrderDefinition.CustomOneofCase)structure[0]);
+ _build_def(structure, ref pos, ref mdef, dynamic_helper);
+ return mdef;
+ }
+
+ static void _build_structure(CustomOrderDefinition algo, ref int[] structure, IMaskIndexInt32 dynamic_type_index) {
+ if (structure == null || structure.Length == 0)
+ structure = new int[1];
+ structure[0] = (int)algo.CustomCase;
+ int p = 1;
+ _build_structure(algo, ref structure, ref p, dynamic_type_index);
+ ArrayHelper.trim(ref structure, p);
+ }
+
+ static void _build_structure(CustomOrderDefinition algo, ref int[] structure, ref int pos, IMaskIndexInt32 dynamic_type_index) {
+ IEnumerable<(CustomOrderDefinition child_algo, int field_pos)> children;
+ if (algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
+ ArrayHelper.ensure_capacity(ref structure, pos + 1);
+ structure[pos++] = dynamic_type_index.to_int(algo.Dynamic.DynamicOrderType) | _dynamic_mask;
+ children = algo.Dynamic.OrderParams.Where(kv => kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef).Select((kv, i) => (kv.Value.AsOrderDef, i));
+ } else {
var cad = OrderDataHelper.get_child_algo_data(algo);
- for (int di = 0; di < cad.Count; di++) {
- int mask = 1 << (31 - di);
- if ((structure[i] & mask) == mask) {
- var type = (CustomOrderDefinition.CustomOneofCase)(structure[i] ^ mask);
- var child_algo = OrderDataHelper.Defaults.CustomOrderDefinition(type);
- pos++;
- _build_def(structure, ref pos, ref child_algo);
- cad[di].assign_child(algo, child_algo);
+ children = cad.Select((c, i) => (c.get_child(algo), i));
+ children = children.Where(c => c.child_algo != null);
+ }
+ foreach ((var child, int field_pos) in children) {
+ ArrayHelper.ensure_capacity(ref structure, pos + 1);
+ structure[pos++] = EnumMaskIndexInt32.to_int(child.CustomCase) | _child_algo_mask(field_pos);
+ _build_structure(child, ref structure, ref pos, dynamic_type_index);
+ }
+ }
+
+ ///
+ /// Gets a mask for a particular child-algo field of a particular algo definition.
+ ///
+ /// The index wrt the deterministic enumeration of child algos for a particular definition (e.g., Hedge = 0, Child = 1).
+ static int _child_algo_mask(int field_pos) => 1 << (_child_mask_offset - field_pos);
+
+ static void _build_def(IReadOnlyList structure, ref int pos, ref CustomOrderDefinition algo, DynamicOrderHelper dynamic_helper) {
+ var local_algo = algo;
+ IEnumerable<(Action assign_child, int field_pos)> children;
+ if (algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic) {
+ var dyn_def = algo.Dynamic;
+ dyn_def.DynamicOrderType = dynamic_helper.dynamic_type_index.from_int(structure[pos++] ^ _dynamic_mask);
+ dynamic_helper.add_dynamic_params(ref dyn_def);
+ children = dyn_def.OrderParams
+ .Where(kv => kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef)
+ .Select((kv, i) => (new Action(child_algo => kv.Value.AsOrderDef = child_algo), i));
+ } else {
+ children = OrderDataHelper.get_child_algo_data(algo)
+ .Select((c, i) => (new Action(child_algo => c.assign_child(local_algo, child_algo)), i));
+ }
+ using (var children_en = children.GetEnumerator()) {
+ while (pos < structure.Count && children_en.MoveNext()) {
+ (var assign_child, int field_pos) = children_en.Current;
+ int mask = _child_algo_mask(field_pos);
+ if ((structure[pos] & mask) == mask) {
+ var type = EnumMaskIndexInt32.from_int(structure[pos++] ^ mask);
+ var child_algo = OrderDataHelper.create_algo(type);
+ _build_def(structure, ref pos, ref child_algo, dynamic_helper);
+ assign_child(child_algo);
}
}
}
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Utils/AlgoCollectionHelper.cs b/src/client/spark/Modules/Trading/AlgoStudio/Utils/AlgoCollectionHelper.cs
index 27b9a9756..977153509 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/Utils/AlgoCollectionHelper.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/Utils/AlgoCollectionHelper.cs
@@ -34,6 +34,18 @@ namespace mbts.spark {
}
}
+ public static void update_persisted_definition_wrappers(ObservableKeyedCollection target, TableUpdate update, Func factory) {
+ foreach (var d in update.removed)
+ target.Remove(d.key);
+ foreach (var d in update.changed)
+ target[d.key].load_from(d.value);
+ foreach (var d in update.added) {
+ if (target.TryGetValue(d.key, out IAlgoVM def)) {
+ def.load_from(d.value);
+ } else target.Add(new AlgoVMWrapper(factory(d)));
+ }
+ }
+
static class _CompareUtils {
public static int compare_modes(AlgoDefinitionVM a, AlgoDefinitionVM b) =>
_compare_modes(a.key.mode, b.key.mode);
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs
index a21904a6b..8b3fc0d53 100644
--- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs
+++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs
@@ -46,7 +46,8 @@ namespace mbts.spark {
readonly DeferrableActionWrapper _refresh_on_local_changes;
readonly ReactiveThresholdMonitor _any_templates_dirty_monitor = new ReactiveThresholdMonitor(t => t.observe_is_dirty());
readonly Property _selected_format;
- AlgoEditingPermissions _editing_permissions;
+ readonly EnumMaskInt32 _permissions_mask = new EnumMaskInt32();
+
int? _favorite_index;
Brush _badge_fill;
Snapshot? _committed;
@@ -54,29 +55,43 @@ namespace mbts.spark {
TableUpdateBuffer _template_update_buffer;
bool _connected;
- public static AlgoDefinitionVM create(OrdersModel model, AlgoData data, bool connect = false, AlgoFormats init_format = AlgoFormats.Exchange) {
- var rv = new AlgoDefinitionVM(model, data, init_format);
+ public static AlgoDefinitionVM create(OrdersModel model, AlgoData data, bool connect = false, AlgoFormats init_format = AlgoFormats.Exchange, AlgoEditingPermissions editing_permissions = (AlgoEditingPermissions)int.MaxValue) {
+ var rv = new AlgoDefinitionVM(model, data, init_format, editing_permissions);
if (connect)
rv.connect();
return rv;
}
public static AlgoDefinitionVM create_placeholder(OrdersModel model, CustomOrderDefinitionImmutable def, string name, AlgoFormats init_format) =>
- new AlgoDefinitionVM(model, new AlgoData(def, name, new AlgoKey(Guid.NewGuid())), init_format);
+ new AlgoDefinitionVM(model, new AlgoData(def, name, new AlgoKey(Guid.NewGuid())), init_format, (AlgoEditingPermissions)int.MaxValue);
- AlgoDefinitionVM(OrdersModel model, AlgoData def_data, AlgoFormats init_format = AlgoFormats.Exchange) {
+ AlgoDefinitionVM(OrdersModel model, AlgoData def_data, AlgoFormats init_format, AlgoEditingPermissions init_permissions) {
// init core data
_model = model;
+ _permissions_mask.mask = init_permissions;
+ _permissions_mask.raw = init_permissions;
+ var resources = new CompositeDisposable();
+ if (!model.algo_model.ui_configuration.can_modify_definition_values)
+ editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowSaveValues);
+ if (!model.algo_model.ui_configuration.can_modify_definition_structure)
+ editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure);
+ else if (model.algo_model.templates_enabled()) {
+ resources.Add(_templates.Subscribe((s, e) => {
+ if (_templates.Count == 0) {
+ editing_permissions_mask |= AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure;
+ } else {
+ editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure);
+ }
+ }));
+ }
key = def_data.key;
algos_view = ObservableAutoWrapper.create_sorted_wrapper(_algo_roots, AlgoCollectionHelper.algo_vm_comparer);
_template_update_buffer = new TableUpdateBuffer(t => t.key);
_templates_with_custom = new ObservableAppendCollection(templates);
templates_view = (ListCollectionView)CollectionViewSource.GetDefaultView(_templates_with_custom);
custom_badge_color_palettes.AddRange(ColorPalette.all_presets(model.factory).Select(p => new ColorPaletteVM(p)));
- _editing_permissions = _get_permissions();
_version = new VersionContainer(_snapshot);
var conf = _model.algo_model.ui_configuration;
- var resources = new CompositeDisposable();
// init backing props
_name = backing(nameof(name), def_data.name);
_abbreviation = backing(nameof(abbreviation), string.Empty);
@@ -87,7 +102,7 @@ namespace mbts.spark {
_is_selected = backing(nameof(is_selected), true);
_is_dirty = backing(nameof(is_dirty), () => key.mode == AlgoKey.Mode.Unpersisted || !_committed.HasValue || !_committed.Value.Equals(_version.value));
var factory_def_data = def_data.key.mode == AlgoKey.Mode.Factory ? def_data : new AlgoData(def_data.value);
- _algo_root = backing(nameof(algo_root), _algo_roots.GetOrAdd(factory_def_data.key, _ => OrderTypeVMFactory.create(factory_def_data, _editing_permissions)));
+ _algo_root = backing(nameof(algo_root), _algo_roots.GetOrAdd(factory_def_data.key, _ => OrderTypeVMFactory.create(factory_def_data)));
_visible_algo_root = backing(nameof(visible_algo_root));
_can_redo = backing(nameof(can_redo), () => _edit_stack.get_can_redo(_version.value));
_can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value));
@@ -113,7 +128,6 @@ namespace mbts.spark {
as_demuxer().subscribe_many(_refresh_on_local_changes.execute, nameof(this.name), nameof(abbreviation), nameof(badge_fill)),
_edit_pane_vs_model.add_source(VisualStateNames.BadgeSelector.GroupName, custom_badge_color.observe_nullable(true).Select(t => t.HasValue ? VisualStateNames.BadgeSelector.Active : VisualStateNames.BadgeSelector.Inactive)),
_edit_pane_vs_model.add_source(VisualStateNames.Abbreviation.GroupName, _abbreviation.observe_current(true).Select(a => string.IsNullOrEmpty(a) ? VisualStateNames.Abbreviation.Unpopulated : VisualStateNames.Abbreviation.Populated)),
- templates.ObserveSelf().Select(_ => _get_permissions()).DistinctUntilChanged().OnDispatcher().Subscribe(on_editing_permissions),
_algo_root.observe_current(true).SubscribeHookLatest(vm => {
if (vm == null)
return Disposable.empty;
@@ -152,16 +166,22 @@ namespace mbts.spark {
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive);
break;
}
- resources.Add(_selected_format.observe_current(true).SubscribeHookLatest(f => {
- using (_refresh_on_local_changes.defer_execution()) {
- var algo_data = model.factory.default_algos(f);
- var default_algo = new AlgoKey(OrderDataHelper.get_default_algo(f));
- return this.load_algo_data_recursive(algo_data, default_algo);
- }
- }));
+ var permission_src = _permissions_mask.observe_result();
+ resources.Add(_selected_format.observe_current(true).CombineLatest(permission_src, (fmt, perms) => (fmt, perms))
+ .SubscribeHookLatest(t => {
+ if ((t.perms & AlgoEditingPermissions.AllowEditStructure) != 0) {
+ using (_refresh_on_local_changes.defer_execution()) {
+ var algo_data = model.factory.default_algos(t.fmt);
+ var default_algo = new AlgoKey(OrderDataHelper.get_default_algo(t.fmt));
+ return this.load_algo_data_recursive(algo_data, default_algo);
+ }
+ }
+ return Disposable.empty;
+ }));
+ resources.Add(permission_src.Subscribe(_ => RaisePropertyChanged(nameof(editing_permissions))));
+ resources.Add(this.connect_data(permission_src));
resources.Add(this.connect_data(Observable.Return(model)));
_dispose = resources;
- on_editing_permissions(_get_permissions());
await algo_root.load_from_async(def_data.value);
_version.increment_version();
_edit_stack.reset(_version.value);
@@ -169,11 +189,6 @@ namespace mbts.spark {
}
}
// local methods
- void on_editing_permissions(AlgoEditingPermissions eps) {
- _editing_permissions = eps;
- foreach (var vm in algo_roots)
- vm.set_permissions(eps);
- }
void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke();
void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke();
void on_local_changed() {
@@ -230,6 +245,9 @@ namespace mbts.spark {
// visual states
public ObservableCollection edit_pane_visual_states => _edit_pane_vs_model.states;
public ObservableCollection tree_view_visual_states => _tree_view_vs_model.states;
+ // editing permissions
+ public AlgoEditingPermissions editing_permissions_mask { get => _permissions_mask.mask; set => _permissions_mask.mask = value; }
+ public AlgoEditingPermissions editing_permissions => _permissions_mask.result;
#region IAlgoSelector
event PropertyChange IAlgoSelector.selected_algo_changed { add => algo_root_changed += value; remove => algo_root_changed -= value; }
@@ -248,7 +266,7 @@ namespace mbts.spark {
void _load_algo_data(IReadOnlyDictionary algo_data, AlgoKey? default_algo) {
var orig_algo = algo_root?.id;
- _algo_roots.SyncWithDictionary(algo_data, d => OrderTypeVMFactory.create(d, _editing_permissions, true));
+ _algo_roots.SyncWithDictionary(algo_data, d => OrderTypeVMFactory.create(d, is_expanded: true));
if (!try_select(orig_algo) && !try_select(default_algo))
algo_root = algo_roots.FirstOrDefault();
//
@@ -298,6 +316,19 @@ namespace mbts.spark {
public IDisposable buffer_updates() => _template_update_buffer.buffer_updates();
+ public void load_def(CustomOrderDefinitionImmutable def) {
+ var key = OrderDataHelper.get_shallow_factory_key(def);
+ if (algo_root?.id == key) {
+ algo_root.load_from(def);
+ } else if (_algo_roots.TryGetValue(key, out IAlgoVM vm)) {
+ vm.load_from(def);
+ algo_root = vm;
+ } else {
+ algo_roots.Add(vm = _mk_algo_root(def));
+ algo_root = vm;
+ }
+ }
+
public void load(AlgoData data) {
_assert_can_load(data.key);
if (algo_root != null)
@@ -309,7 +340,7 @@ namespace mbts.spark {
// pass a copy of the persisted state - rather than use local values - because if something goes wrong, it is better to be in sync with data fresh from the server/api.
public AlgoDefinitionVM to_persisted(AlgoData def) =>
- new AlgoDefinitionVM(_model, def);
+ new AlgoDefinitionVM(_model, def, selected_format, editing_permissions_mask);
public AlgoData create_algo_def() =>
new AlgoData(algo_root.definition, name, key);
@@ -322,16 +353,6 @@ namespace mbts.spark {
public override int GetHashCode() => key.GetHashCode();
public override string ToString() => algo_root == null ? $"!:{name}" : $"{algo_root.order_type}:{name}";
- AlgoEditingPermissions _get_permissions() {
- var permissions = AlgoEditingPermissions.None;
- if (_model.algo_model.ui_configuration.can_modify_definition_values) {
- permissions |= AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowSaveValues;
- }
- if (_model.algo_model.ui_configuration.can_modify_definition_structure || (_model.algo_model.templates_enabled() && _templates.Count == 0))
- permissions |= AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure;
- return permissions;
- }
-
void _assert_can_load(AlgoKey data_key) {
if (key.mode != data_key.mode)
throw new InvalidOperationException($"{typeof(AlgoDefinitionVM)} '{nameof(key)}.{nameof(AlgoKey.mode)}' must be {data_key.mode} (actually {key.mode}), to load specified data.");
@@ -362,7 +383,7 @@ namespace mbts.spark {
}
IAlgoVM _mk_algo_root(CustomOrderDefinitionImmutable definition) =>
- OrderTypeVMFactory.create(new AlgoData(definition), editing_permissions: _editing_permissions, true);
+ OrderTypeVMFactory.create(new AlgoData(definition), is_expanded: true);
void _on_metadata(AlgoDefinitionMetadata metadata) {
using (_refresh_on_local_changes.supress_execution()) {
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs
new file mode 100644
index 000000000..569e4d1cb
--- /dev/null
+++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs
@@ -0,0 +1,198 @@
+using bts.api;
+using bts.api.orderman;
+using bts.spark;
+using mbts.spark.utilities;
+using mbts.ui;
+using mbts.ui.controls;
+using mbts.ui.shell;
+using mbts.utils;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Reactive.Disposables;
+using System.Reactive.Linq;
+using System.Threading.Tasks;
+using System.Windows.Input;
+
+namespace mbts.spark {
+ class AlgoVMWrapper : DisposableViewModelBase, IAlgoVM,
+ IObserver,
+ IObserver,
+ IObserver,
+ IObserver {
+ static readonly HashSet
+ _algo_root_echo_props = new HashSet {
+ nameof(is_expanded),
+ nameof(editing_permissions),
+ nameof(definition),
+ nameof(display_name)
+ },
+ _value_echo_props = new HashSet {
+ nameof(AlgoDefinitionVM.name),
+ nameof(AlgoDefinitionVM.abbreviation),
+ nameof(AlgoDefinitionVM.badge_fill),
+ nameof(AlgoDefinitionVM.can_undo),
+ nameof(AlgoDefinitionVM.can_redo)
+ };
+ readonly ObservableAggregateCollection _child_algo_selectors = new ObservableAggregateCollection();
+ readonly DisposableContainer _value_hooks = new DisposableContainer();
+ Action _definition_changed = () => { };
+ _ObservedData? _data_cache;
+ AlgoDefinitionVM _value;
+
+ public AlgoVMWrapper(AlgoDefinitionVM algo_definition_vm) {
+ value = algo_definition_vm;
+ _dispose = new CompositeDisposable(_value_hooks) {
+ _child_algo_selectors.clear_collections,
+ () => _value?.Dispose()
+ };
+ }
+
+ public event Action definition_changed { add => _definition_changed += value; remove => _definition_changed -= value; }
+
+ public AlgoDefinitionVM value {
+ get => _value;
+ set {
+ if (_value != value) {
+ _value?.Dispose();
+ _value = value;
+ _value_hooks.replace(_set_hooks(value));
+ RaisePropertyChanged(nameof(value));
+ }
+ }
+ }
+ public AlgoKey id => _value.key;
+ public CustomOrderDefinition.CustomOneofCase order_type => _algo_root?.order_type ?? CustomOrderDefinition.CustomOneofCase.None;
+ public bool is_bts_type => _algo_root?.is_bts_type ?? false;
+ public OrderMetadata meta {
+ get {
+ if (_value != null) {
+ if (_value.custom_badge_color.enabled)
+ return new OrderMetadata { Color = value.custom_badge_color.value.rgb_color(), KeyBinding = value.abbreviation.if_null_or_empty(value.name) };
+ else if (_value.algo_root != null)
+ return _value.algo_root.meta;
+ }
+ return OrderDataHelper.get_metadata(order_type);
+ }
+ }
+ public AlgoEditingPermissions editing_permissions => _value?.editing_permissions ?? AlgoEditingPermissions.None;
+ public bool can_expand => _algo_root?.can_expand ?? false;
+ public bool is_expanded {
+ get => _value.algo_root?.is_expanded ?? false;
+ set {
+ if (_value != null)
+ _value.is_expanded = value;
+ }
+ }
+ public string display_name => _value?.name ?? string.Empty;
+ public CustomOrderDefinitionImmutable definition => _algo_root?.definition ?? new CustomOrderDefinitionImmutable(new CustomOrderDefinition());
+ public ObservableCollection child_algo_selectors => _child_algo_selectors;
+ public dynamic children_vm => _algo_root?.children_vm;
+
+ IAlgoVM _algo_root => _value?.algo_root;
+
+ public void assign_to(CustomOrderDefinition value) => _algo_root?.assign_to(value);
+ public bool key_match(KeyEventArgs e) => _algo_root?.key_match(e) ?? false;
+ public void load_from(CustomOrderDefinitionImmutable value) => _algo_root?.load_from(value);
+ public Task load_from_async(CustomOrderDefinitionImmutable definition) => _algo_root is IAlgoVM vm ? vm.load_from_async(definition) : Task.FromResult(null);
+
+ IDisposable _set_hooks(AlgoDefinitionVM vm) {
+ var algo_root_subs = new DisposableContainer();
+ vm.PropertyChanged += on_value_prop_changed;
+ return new CompositeDisposable(
+ vm.observe_algo_root().Subscribe(r => {
+ algo_root_subs.replace(null);
+ _child_algo_selectors.clear_collections();
+ if (r != null) {
+ if (_data_cache.HasValue) {
+ _data_cache.Value.forward_to(r);
+ }
+ _child_algo_selectors.add_collection(r.child_algo_selectors);
+ ((INotifyPropertyChanged)r).PropertyChanged += on_algo_root_prop_changed;
+ algo_root_subs.replace(new CompositeDisposable(
+ r.subscribe_definition().Subscribe(_ => _definition_changed?.Invoke())) {
+ () => ((INotifyPropertyChanged)r).PropertyChanged -= on_algo_root_prop_changed
+ });
+ }
+ }),
+ algo_root_subs) {
+ () => vm.PropertyChanged -= on_value_prop_changed
+ };
+ void on_algo_root_prop_changed(object sender, PropertyChangedEventArgs e) {
+ if (_algo_root_echo_props.Contains(e.PropertyName))
+ RaisePropertyChanged(e.PropertyName);
+ }
+ void on_value_prop_changed(object sender, PropertyChangedEventArgs e) {
+ if (_value_echo_props.Contains(e.PropertyName))
+ RaisePropertyChanged(e.PropertyName);
+ }
+ }
+
+ // permissions
+ void IObserver.OnNext(AlgoEditingPermissions value) {
+ _data_cache = _data_cache?.with(value) ?? new _ObservedData(value, default, default, default);
+ (_algo_root as IObserver)?.OnNext(value);
+ }
+ void IObserver.OnError(Exception error) { }
+ void IObserver.OnCompleted() { }
+ // model
+ void IObserver.OnNext(OrdersModel value) {
+ _data_cache = _data_cache?.with(value) ?? new _ObservedData(default, value, default, default);
+ (_algo_root as IObserver)?.OnNext(value);
+ }
+ void IObserver.OnError(Exception error) { }
+ void IObserver.OnCompleted() { }
+ // security
+ void IObserver.OnNext(SecurityImmutable? value) {
+ _data_cache = _data_cache?.with(value) ?? new _ObservedData(default, default, value, default);
+ (_algo_root as IObserver)?.OnNext(value);
+ }
+ void IObserver.OnError(Exception error) { }
+ void IObserver.OnCompleted() { }
+ // security md
+ void IObserver.OnNext(SecurityMD? value) {
+ _data_cache = _data_cache?.with(value) ?? new _ObservedData(default, default, default, value);
+ (_algo_root as IObserver)?.OnNext(value);
+ }
+ void IObserver.OnError(Exception error) { }
+ void IObserver.OnCompleted() { }
+
+ struct _ObservedData {
+ public readonly AlgoEditingPermissions permissions;
+ public readonly OrdersModel model;
+ public readonly SecurityImmutable? security;
+ public readonly SecurityMD? security_md;
+
+ public _ObservedData(AlgoEditingPermissions permissions, OrdersModel model, SecurityImmutable? security, SecurityMD? security_md) {
+ this.permissions = permissions;
+ this.model = model;
+ this.security = security;
+ this.security_md = security_md;
+ }
+
+ public void forward_to(IAlgoVM recipient) {
+ (recipient as IObserver)?.OnNext(permissions);
+ if (model != null)
+ (recipient as IObserver)?.OnNext(model);
+ if (security_md.HasValue)
+ (recipient as IObserver)?.OnNext(security_md);
+ if (security.HasValue)
+ (recipient as IObserver)?.OnNext(security);
+ }
+
+ public _ObservedData with(AlgoEditingPermissions? permissions) =>
+ new _ObservedData(permissions ?? this.permissions, model, security, security_md);
+
+ public _ObservedData with(OrdersModel model) =>
+ new _ObservedData(permissions, model, security, security_md);
+
+ public _ObservedData with(SecurityImmutable? security) =>
+ new _ObservedData(permissions, model, security, security_md);
+
+ public _ObservedData with(SecurityMD? security_md) =>
+ new _ObservedData(permissions, model, security, security_md);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml
new file mode 100644
index 000000000..1336d487a
--- /dev/null
+++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml
@@ -0,0 +1,119 @@
+
+
+
+
+
+
+
+
+ 4
+ 8
+ 12
+ 4
+ 8
+ 12
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ AllowEditStructure
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml.cs
new file mode 100644
index 000000000..00ba8a70c
--- /dev/null
+++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml.cs
@@ -0,0 +1,28 @@
+using mbts.ui.extensions;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace mbts.ui.spark {
+ partial class AlgoEditorView : UserControl {
+ public AlgoEditorView() {
+ InitializeComponent();
+ content_host.PreviewMouseMove += content_host_PreviewMouseMove;
+ content_host.MouseEnter += content_host_MouseEnter;
+ content_host.MouseLeave += content_host_MouseLeave;
+ // local methods
+ void content_host_PreviewMouseMove(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
+ void content_host_MouseEnter(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
+ void content_host_MouseLeave(object sender, MouseEventArgs e) => refresh_is_mouse_over_content_host(e);
+ void refresh_is_mouse_over_content_host(MouseEventArgs e) => content_host.set_current_if_changed(IsMouseOverNodeContentProperty, this.ChildAtPoint(e.GetPosition(this)) == content_host);
+ }
+
+ #region IsMouseOverNodeContent
+ public static readonly DependencyProperty IsMouseOverNodeContentProperty =
+ DependencyProperty.RegisterAttached("IsMouseOverNodeContent", typeof(bool), typeof(AlgoEditorView), new PropertyMetadata(false));
+
+ public static bool GetIsMouseOverNodeContent(DependencyObject d) => (bool)d.GetValue(IsMouseOverNodeContentProperty);
+ public static void SetIsMouseOverNodeContent(DependencyObject d, bool value) => d.SetValue(IsMouseOverNodeContentProperty, value);
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/Fills/FillsVM.cs b/src/client/spark/Modules/Trading/Fills/FillsVM.cs
index 80ae73adb..523ea62c8 100644
--- a/src/client/spark/Modules/Trading/Fills/FillsVM.cs
+++ b/src/client/spark/Modules/Trading/Fills/FillsVM.cs
@@ -14,10 +14,13 @@ using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
+using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
+using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Windows.Data;
@@ -42,7 +45,7 @@ namespace mbts.spark {
public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IWindowSettingsManager settings_manager)
: this(bus, model, state_obs, _get_observable(bus, model, state_obs), settings_manager) { }
- FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IConnectableObservable> fills_source, IWindowSettingsManager settings_manager) {
+ public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IObservable> fills_source, IWindowSettingsManager settings_manager) {
_model = model;
_settings_manager = settings_manager;
/// Columns
@@ -98,16 +101,17 @@ namespace mbts.spark {
// grid settings
grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, rows);
// this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.)
- grid_settings_manager.load_from(settings_manager.current_settings());
+ if (_settings_manager != null)
+ grid_settings_manager.load_from(_settings_manager.current_settings());
//
- _dispose = Disposable.Create(
+ _dispose = new CompositeDisposable(
ObservableAutoWrapper.connect(col_tups, columns, ct => ct.col),
fills_source.OnDispatcher().Subscribe(t => {
_rows.update(t);
Set(ref _total_row_count, t.state.Count, nameof(total_row_count));
}),
state_obs.OnDispatcher().Subscribe(s => {
- if (s.grid != null) {
+ if (s.grid != null && _settings_manager != null) {
// this means we are not using defaults,
// Note: settings_manager in turn notifies grid_settings_manager of this update
_settings_manager.instance_settings = s.grid;
@@ -120,8 +124,8 @@ namespace mbts.spark {
};
rows_manager.on_settings(fs, s.sorting_criterion);
}),
- settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager),
- fills_source.Connect()
+ settings_manager == null ? Disposable.empty : settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager),
+ (fills_source as IConnectableObservable>)?.Connect() ?? Disposable.empty
);
// local methods
void add_col(Columns col_key, string header, Func get_text, IDataGridColumnPersistentFilter filter, string filter_template, double width) =>
@@ -153,12 +157,12 @@ namespace mbts.spark {
public IEnumerable get_sorting_criterion() =>
_sort_manager.create();
+ public void on_sorting(object sender, DIYGridSortingEventArgs e) =>
+ _sort_manager.on_sorting(e);
+
static Columns _col_key(ColumnBase column) =>
((IKeyedColumn)column).key;
- void IHandleGridSorting.on_sorting(object sender, DIYGridSortingEventArgs e) =>
- _sort_manager.on_sorting(e);
-
public FilterStates get_filters() =>
_filters_manager.create();
diff --git a/src/client/spark/Modules/Trading/Fills/FillsVMContainer.cs b/src/client/spark/Modules/Trading/Fills/FillsVMContainer.cs
new file mode 100644
index 000000000..48a165171
--- /dev/null
+++ b/src/client/spark/Modules/Trading/Fills/FillsVMContainer.cs
@@ -0,0 +1,49 @@
+using mbts.ui;
+using mbts.ui.controls;
+using System;
+
+namespace mbts.spark {
+ ///
+ /// This class provides a stable DataContext for a fills view, with an internal that may be disposed and recreated as needed.
+ ///
+ class FillsVMContainer : IHandleGridSorting, IDisposable, IWillLetYouKnowWhenIDispose {
+ bool _disposed;
+ FillsVM _value;
+
+ public event Action OnDisposed;
+
+ public FillsVM value {
+ get => _value;
+ set {
+ if (value != _value) {
+ if (_disposed)
+ throw new ObjectDisposedException(nameof(FillsVMContainer));
+ Disposable.replace(ref _value, value);
+ if (_value != null) {
+ rows.add_collection(_value.rows);
+ columns.add_collection(_value.columns);
+ } else {
+ rows.clear_collections();
+ columns.clear_collections();
+ }
+ }
+ }
+ }
+
+ public ObservableAggregateCollection rows { get; } = new ObservableAggregateCollection();
+ public ObservableAggregateCollection columns { get; } = new ObservableAggregateCollection();
+
+ public void Dispose() {
+ if (_disposed)
+ throw new ObjectDisposedException(nameof(FillsVMContainer));
+ value = null;
+ OnDisposed?.Invoke(true);
+ _disposed = true;
+ }
+
+ public void on_sorting(object sender, DIYGridSortingEventArgs e) {
+ if (!_disposed)
+ _value?.on_sorting(sender, e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs
index a932cfbb3..a3a4781b2 100644
--- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs
+++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs
@@ -18,7 +18,6 @@ using StartupData = bts.shell.FillsWindowFactory.StartupData;
namespace mbts.spark {
class FillsWindow : SparkWindow, ISharedWindow {
public const string window_type_name = "Fills";
- const string _thread_id = "Fills";
readonly AllowOnce _init_guard = new AllowOnce("Fills");
readonly OrdersModel _orders_model;
readonly IWindowSettingsManager _settings_manager;
@@ -33,6 +32,7 @@ namespace mbts.spark {
_orders_model = orders_model;
_state = state;
_settings_manager = settings_manager;
+ thread_id = config.Configuration.get().fills ? "Fills" : null;
}
event Action _state_changed;
@@ -48,7 +48,7 @@ namespace mbts.spark {
+ LAUNCHER_BUTTON_BORDER_WIDTH
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
- public string thread_id => _thread_id;
+ public string thread_id { get; }
public void thread_init() {
_init_guard.check_access();
diff --git a/src/client/spark/Modules/Trading/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/LadderWindowFactory.cs
index 0cf81e9e1..33c8b36ec 100644
--- a/src/client/spark/Modules/Trading/LadderWindowFactory.cs
+++ b/src/client/spark/Modules/Trading/LadderWindowFactory.cs
@@ -33,7 +33,7 @@ namespace bts.shell {
_settings_hub = settings_hub;
_orders_model = orders_model;
_md_auxiliary_model = md_auxiliary_model;
- _ladder_conf = new LadderConfig(Configuration.get(), Configuration.get().enabled);
+ _ladder_conf = new LadderConfig(Configuration.get(), Configuration.get().ladder);
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s),
bus.subscribe(SparkTags.ShowLadderTag).OnDispatcher().Subscribe(s => show_windows(new[] { s })),
diff --git a/src/client/spark/Modules/Trading/OrderBook/MiniOrderBook/MiniOrderBookView.xaml b/src/client/spark/Modules/Trading/OrderBook/MiniOrderBook/MiniOrderBookView.xaml
index 627a2da4b..928a2ce88 100644
--- a/src/client/spark/Modules/Trading/OrderBook/MiniOrderBook/MiniOrderBookView.xaml
+++ b/src/client/spark/Modules/Trading/OrderBook/MiniOrderBook/MiniOrderBookView.xaml
@@ -95,7 +95,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs
index d0a878a08..62202b655 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs
@@ -2,27 +2,31 @@
using bts.api.orderman;
using bts.shell;
using bts.spark;
+using bts.view;
using mbts.persist;
using mbts.ui;
using mbts.ui.converters;
+using mbts.ui.extensions;
using mbts.ui.spark;
using mbts.ui.utility;
+using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Data;
+using System.Windows.Input;
using System.Windows.Media;
-//using IOrderBookWSM = mbts.persist.IWindowSettingsManager>;
using OrderBookGridSettings = bts.shell.OrderBookWindowFactory.OrderBookGridSettings;
using OrderBookGridSettingsVM = mbts.spark.GridSettingsVM;
namespace mbts.spark {
internal class OrderBookWindow : SparkWindow, ISharedWindow {
- const string _window_type = "OrderBook", ORDERBOOK_THREAD_ID = "OrderBook", _default_title = "Order Book";
+ const string _window_type = "OrderBook", _default_title = "Order Book";
readonly INotificationService _notification_service;
readonly IWindowSettingsManager _settings_manager;
+ IDisposable _attachment_exit_sub;
OrderBookWindowFactory.OrderBookStartupData _state;
OrdersModel _model;
OrderBookVM _vm;
@@ -30,17 +34,6 @@ namespace mbts.spark {
OrderBookWindowFactory _factory;
SparkCommand[] _commands;
- SparkCommand _show_fills_command
- , _modify_order_command
- , _cancel_buy_orders_command
- , _cancel_sell_orders_command
- , _cancel_all_orders_command
- , _cancel_selected_orders_command
- , _recreate_selected_orders_command
- , _toggle_collapse_all_command
- , _toggle_expand_all_command
- , _show_grid_settings_command;
-
public OrderBookWindow(OrdersModel model, OrderBookWindowFactory factory, IBus bus, INotificationService notification_service,
OrderBookWindowFactory.OrderBookStartupData state, ImageSource icon, IWindowSettingsManager settings_manager)
: base(_default_title, bus, factory, SparkCommands.ShowOrders.icon) {
@@ -49,6 +42,7 @@ namespace mbts.spark {
_notification_service = notification_service;
_state = state;
_settings_manager = settings_manager;
+ thread_id = config.Configuration.get().order_book ? "OrderBook" : null;
}
public override OrderBookWindowFactory.OrderBookStartupData SaveState => _state = _vm?.create();
@@ -61,10 +55,11 @@ namespace mbts.spark {
+ SPARK_MENU_COLLAPSED_WIDTH
+ LAUNCHER_BUTTON_BORDER_WIDTH
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
- public string thread_id => ORDERBOOK_THREAD_ID;
+ public string thread_id { get; }
public override void Dispose() {
_commands.OfType().DisposeAll();
+ Disposable.dispose(ref _attachment_exit_sub);
Disposable.dispose(ref _vm);
}
@@ -73,54 +68,62 @@ namespace mbts.spark {
_vm.load_from(_state);
_view = new OrderBookView(_vm);
- _show_fills_command = SparkCommands.ShowFills.complete(() => new FillsWindowFactory.StartupData(_vm.selected_orders.Select(r => r.Key).ToArray()));
+ var show_fills_command = SparkCommands.ShowFills.complete(() => new FillsWindowFactory.StartupData(_vm.selected_orders.Select(r => r.Key).ToArray()));
- _modify_order_command = SparkCommands.ShowModifyOrder.complete(
- () => _vm.current_order.Value.Key,
- can_execute: () => {
- if (_vm.current_order.HasValue) {
- return _vm.current_order.Value.State.Status == bts.api.orderman.OrderStatus.Working;
- }
- return false;
- }
- );
+ var toggle_right_panel_is_visible_command = new SparkCommandCommand(
+ get_toggle_algo_editor_cmd_title(),
+ Icons.ModifyOrder,
+ _vm.toggle_algo_editor_is_visible_cmd,
+ new KeyGesture(Key.M, ModifierKeys.Control | ModifierKeys.Shift));
- _cancel_buy_orders_command = SparkCommands.CancelBuyOrders.complete(
+ var cancel_buy_orders_command = SparkCommands.CancelBuyOrders.complete(
_model.working_orders.Select(os => os.Values.Where(o => o.order.side() == Side.Buy).Select(o => o.order.Key)),
wbids => wbids.Any()
);
- _cancel_sell_orders_command = SparkCommands.CancelSellOrders.complete(
+ var cancel_sell_orders_command = SparkCommands.CancelSellOrders.complete(
_model.working_orders.Select(os => os.Values.Where(o => o.order.side() == Side.Sell).Select(o => o.order.Key)),
wasks => wasks.Any()
);
- _cancel_all_orders_command = SparkCommands.CancelOrders.complete(
+ var cancel_all_orders_command = SparkCommands.CancelOrders.complete(
_model.working_orders.Select(os => os.Select(o => o.Key)),
worders => worders.Any()
);
- _cancel_selected_orders_command = SparkCommands.CancelSelectedOrders.complete(
+ var cancel_selected_orders_command = SparkCommands.CancelSelectedOrders.complete(
() => _vm.selected_orders.Where(x => x.status() == OrderStatus.Working).Select(x => x.Key),
can_execute: () => _vm.selected_orders.Any(x => x.status() == OrderStatus.Working)
);
- _recreate_selected_orders_command = SparkCommands.RecreateSelectedOrders.complete(
+ var recreate_selected_orders_command = SparkCommands.RecreateSelectedOrders.complete(
() =>
- _vm.selected_orders.Where(x => _passes_recreate_search_criteria(x))
+ _vm.selected_orders.Where(x => passes_recreate_search_criteria(x))
.Select(x => (x.Def, x.State.Price, x.State.Quantity - x.State.FilledQuantity)),
- can_execute: () => _vm.selected_orders.Any(x => _passes_recreate_search_criteria(x))
+ can_execute: () => _vm.selected_orders.Any(x => passes_recreate_search_criteria(x))
);
- _toggle_collapse_all_command = new SparkCommandCommand("Collapse All",
+ var attach_selected_orders_command = new SparkCommandCommand(
+ "Attach To Selected Orders",
+ Icons.AttachAlgos,
+ new DelegateCommand(_vm.begin_attach_algos, () => _vm.selected_rows.Count > 0),
+ new KeyGesture(Key.A, ModifierKeys.Control | ModifierKeys.Shift));
+
+ var detach_selected_orders_command = new SparkCommandCommand(
+ "Detach And Cancel Selected Orders",
+ Icons.DetachAlgos,
+ new DelegateCommand(_vm.detach_selected_algos, () => _vm.selected_rows.Count > 0),
+ new KeyGesture(Key.D, ModifierKeys.Control | ModifierKeys.Shift));
+
+ var toggle_collapse_all_command = new SparkCommandCommand("Collapse All",
Icons.RightArrow,
_vm.collapse_all_rows_command);
- _toggle_expand_all_command = new SparkCommandCommand("Expand All",
+ var toggle_expand_all_command = new SparkCommandCommand("Expand All",
Icons.DownArrow,
_vm.expand_all_rows_command);
- _show_grid_settings_command = SparkCommands.window_settings_command(new DialogCommand(() => {
+ var show_grid_settings_command = SparkCommands.window_settings_command(new DialogCommand(() => {
var gs_vm = new WindowSettingsDialogVM(
_settings_manager,
us => us.order_book_grid,
@@ -145,31 +148,44 @@ namespace mbts.spark {
return dialog;
}));
- _commands = new SparkCommand[] {
- _show_fills_command,
- _modify_order_command,
- _cancel_selected_orders_command,
- _cancel_buy_orders_command,
- _cancel_sell_orders_command,
- _cancel_all_orders_command,
- _recreate_selected_orders_command,
- _toggle_collapse_all_command,
- _toggle_expand_all_command,
- _show_grid_settings_command
+ _commands = new SparkCommand[] {
+ show_fills_command,
+ toggle_right_panel_is_visible_command,
+ cancel_selected_orders_command,
+ cancel_buy_orders_command,
+ cancel_sell_orders_command,
+ cancel_all_orders_command,
+ recreate_selected_orders_command,
+ attach_selected_orders_command,
+ detach_selected_orders_command,
+ toggle_collapse_all_command,
+ toggle_expand_all_command,
+ show_grid_settings_command
};
- _vm.selected_order_changed += _vm_selected_order_changed;
+ _vm.as_demuxer().subscribe(nameof(OrderBookVM.algo_editor_is_visible))
+ .Subscribe(_ => toggle_right_panel_is_visible_command.title = get_toggle_algo_editor_cmd_title());
+ _vm.selected_order_changed += vm_selected_order_changed;
+ // local methods
+ string get_toggle_algo_editor_cmd_title() =>
+ $"{(_vm.algo_editor_is_visible ? "Hide" : "Show")} Order Params";
+
+ bool passes_recreate_search_criteria(OrderRecordImmutable record) =>
+ (record.status() == OrderStatus.Canceled || record.status() == OrderStatus.Error) &&
+ !record.has_parent() &&
+ record.State.Quantity > record.State.FilledQuantity;
+
+ void vm_selected_order_changed(OrderRecordImmutable? e) {
+ cancel_selected_orders_command.raiseCanExecuteChanged();
+ recreate_selected_orders_command.raiseCanExecuteChanged();
+ attach_selected_orders_command.raiseCanExecuteChanged();
+ detach_selected_orders_command.raiseCanExecuteChanged();
+ }
}
- private bool _passes_recreate_search_criteria(OrderRecordImmutable record) {
- return (record.status() == OrderStatus.Canceled || record.status() == OrderStatus.Error)
- && !record.has_parent()
- && record.State.Quantity > record.State.FilledQuantity;
- }
-
- private void _vm_selected_order_changed(OrderRecordImmutable? e) {
- _modify_order_command.raiseCanExecuteChanged();
- _cancel_selected_orders_command.raiseCanExecuteChanged();
- _recreate_selected_orders_command.raiseCanExecuteChanged();
- }
+ protected override void OnParentViewCreated(SparkWindowView parent_view) =>
+ Disposable.replace(ref _attachment_exit_sub, parent_view.SubscribePreviewKeyDown((s, e) => {
+ if (e.Key == Key.Escape || (e.Key == Key.Z && KeyboardExtensions.IsCtrlDown()))
+ _vm.is_attaching_algos = false;
+ }));
}
}
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs
index 5101a4149..83578cb44 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs
@@ -12,10 +12,11 @@ using mbts.ui.settings;
using ProtoBuf;
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
-using static mbts.spark.OrderBookView;
+using Columns = mbts.spark.OrderBookGridView.ColumnKeys;
namespace bts.shell {
internal class OrderBookWindowFactory : ShellWindowFactory {
@@ -49,24 +50,57 @@ namespace bts.shell {
[ProtoContract]
public class OrderBookStartupData {
- //[ProtoMember(5)]
- //public readonly List sort_criteria;
+ const bool _default_algo_editor_is_visible = true;
+ const double
+ _default_right_panel_width = 400,
+ _default_fills_slave_grid_height = 138;
+ // ALREADY USED TAGS
+ // [ProtoMember(5)]
+ // public readonly List sort_criteria;
+
+ // filters
[ProtoMember(10)]
public FilterStates filters;
+ // grid
[ProtoMember(15)]
[Obsolete]
public GridSettings grid;
+ // algo editor is visible
+ [ProtoMember(16)]
+ [DefaultValue(_default_algo_editor_is_visible)]
+ public bool algo_editor_is_visible { get; set; }
+ // right panel width
+ [ProtoMember(17)]
+ [DefaultValue(_default_right_panel_width)]
+ public double right_panel_width { get; set; }
+ // fills slave grid height
+ [ProtoMember(18)]
+ [DefaultValue(_default_fills_slave_grid_height)]
+ public double fills_slave_grid_height { get; set; }
+ // fills slave grid is visible
+ [ProtoMember(19)]
+ public bool fills_slave_grid_is_visible { get; set; }
+ // predicate animations
[ProtoMember(20)]
[Obsolete]
List _predicate_animations;
+ // use defaults
[ProtoMember(25)]
public bool use_defaults;
- public OrderBookStartupData() { }
+ public OrderBookStartupData() {
+ algo_editor_is_visible = _default_algo_editor_is_visible;
+ right_panel_width = _default_right_panel_width;
+ fills_slave_grid_height = _default_fills_slave_grid_height;
+ }
- public OrderBookStartupData(FilterStates filters, GridSettings grid = default, IEnumerable predicate_animations = null, bool use_defaults = false) {
+ public OrderBookStartupData(FilterStates filters, GridSettings grid = default, bool algo_editor_is_visible = false, double right_panel_width = 0, double fills_slave_grid_height = 0, bool fills_slave_grid_is_visible = false, IEnumerable predicate_animations = null, bool use_defaults = false) {
this.filters = filters;
this.use_defaults = use_defaults;
+ this.algo_editor_is_visible = algo_editor_is_visible;
+ this.right_panel_width = right_panel_width;
+ this.fills_slave_grid_height = fills_slave_grid_height;
+ this.fills_slave_grid_is_visible = fills_slave_grid_is_visible;
#pragma warning disable CS0612 // Type or member is obsolete
this.grid = grid;
_predicate_animations = new List();
@@ -83,9 +117,12 @@ namespace bts.shell {
public static OrderBookStartupData Default =>
new OrderBookStartupData(
- new FilterStates {
- statuses = new[] { OrderStatus.Working }
- }, _default_general_grid, use_defaults: true);
+ new FilterStates { statuses = new[] { OrderStatus.Working } },
+ _default_general_grid,
+ _default_algo_editor_is_visible,
+ _default_right_panel_width,
+ _default_fills_slave_grid_height,
+ use_defaults: true);
public static OrderBookGridSettings DefaultGrid => new OrderBookGridSettings(_default_general_grid);
@@ -115,6 +152,7 @@ namespace bts.shell {
public static GridColumnSettings security_key => new GridColumnSettings(Columns.SecurityKey.ToString(), DIYGrid.DefaultColumnHeaders.SecurityKey, is_visible: false, width: DIYGrid.DefaultColumnWidths.SecurityKey);
public static GridColumnSettings order_key => new GridColumnSettings(Columns.OrderKey.ToString(), DIYGrid.DefaultColumnHeaders.OrderKey, width: DIYGrid.DefaultColumnWidths.OrderKey);
public static GridColumnSettings parent_key => new GridColumnSettings(Columns.ParentKey.ToString(), "Parent Key", width: DIYGrid.DefaultColumnWidths.ParentKey);
+ public static GridColumnSettings attached_target_order_key => new GridColumnSettings(Columns.AttachedTargetOrderKey.ToString(), DIYGrid.DefaultColumnHeaders.AttachedTargetOrderKey, width: DIYGrid.DefaultColumnWidths.ParentKey);
public static IEnumerable sorting_criterion {
get {
@@ -145,11 +183,12 @@ namespace bts.shell {
yield return security_key;
yield return order_key;
yield return parent_key;
+ yield return attached_target_order_key;
}
}
private static HashSet _mini_mode_columns_to_hide = new HashSet {
- time_created, exchange, sub_type, quantity, price, avg_price, last_price, status, last_message, security_key, order_key, parent_key
+ time_created, exchange, sub_type, quantity, price, avg_price, last_price, status, last_message, security_key, order_key, parent_key, attached_target_order_key
};
public static IEnumerable mini {
@@ -208,11 +247,17 @@ namespace bts.shell {
public api.orderman.OrderSubType[] order_sub_types;
[ProtoMember(20)]
public string[] symbols;
+ [ProtoMember(21)]
+ public string parent_key_regex;
+ [ProtoMember(22)]
+ public string attached_target_order_key_regex;
public bool Equals(FilterStates other) =>
other != null &&
security_criteria.safe_equals(other.security_criteria) &&
order_key_regex == other.order_key_regex &&
+ parent_key_regex == other.parent_key_regex &&
+ attached_target_order_key_regex == other.attached_target_order_key_regex &&
time_created.Equals(other.time_created) &&
EqualityComparer.safe_sequence_equals(users, other.users) &&
EqualityComparer.safe_sequence_equals(accounts, other.accounts) &&
@@ -230,6 +275,32 @@ namespace bts.shell {
last_change.Equals(other.last_change) &&
EqualityComparer.safe_sequence_equals(order_sub_types, other.order_sub_types) &&
EqualityComparer.safe_sequence_equals(symbols, other.symbols);
+
+ public override bool Equals(object obj) => Equals(obj as FilterStates);
+
+ public override int GetHashCode() =>
+ EqualityComparer.aggregate_hash(
+ security_criteria?.GetHashCode() ?? 0,
+ order_key_regex?.GetHashCode() ?? 0,
+ parent_key_regex?.GetHashCode() ?? 0,
+ attached_target_order_key_regex?.GetHashCode() ?? 0,
+ time_created.GetHashCode(),
+ EqualityComparer.safe_aggregate_hash(users),
+ EqualityComparer.safe_aggregate_hash(accounts),
+ EqualityComparer.safe_aggregate_hash(exchanges),
+ EqualityComparer.safe_aggregate_hash(tifs),
+ EqualityComparer.safe_aggregate_hash(order_types),
+ EqualityComparer.safe_aggregate_hash(sides),
+ qty?.GetHashCode() ?? 0,
+ price?.GetHashCode() ?? 0,
+ qty_filled?.GetHashCode() ?? 0,
+ avg_price?.GetHashCode() ?? 0,
+ last_price?.GetHashCode() ?? 0,
+ EqualityComparer.safe_aggregate_hash(statuses),
+ exchange_message_regex?.GetHashCode() ?? 0,
+ last_change.GetHashCode(),
+ EqualityComparer.safe_aggregate_hash(order_sub_types),
+ EqualityComparer.safe_aggregate_hash(symbols));
}
[ProtoContract]
@@ -240,7 +311,7 @@ namespace bts.shell {
List _predicate_animations;
public OrderBookGridSettings() { }
- public OrderBookGridSettings(GridSettings general = default, IEnumerable predicate_animations = null) {
+ public OrderBookGridSettings(GridSettings general = default, IEnumerable predicate_animations = null, double right_panel_width = double.NaN) {
this.general = general;
_predicate_animations = new List();
if (predicate_animations != null)
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookAttachmentTargetAdorner.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookAttachmentTargetAdorner.cs
new file mode 100644
index 000000000..ff71d046b
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookAttachmentTargetAdorner.cs
@@ -0,0 +1,63 @@
+using mbts.ui;
+using mbts.ui.controls;
+using mbts.ui.controls.adorners;
+using mbts.ui.extensions;
+using System;
+using System.Reactive.Linq;
+using System.Windows;
+using System.Windows.Input;
+
+namespace mbts.spark {
+ partial class OrderBookView {
+ public class OrderBookAttachmentTargetAdorner : DIYGridRowHighlighterAdorner, IDisposable {
+ IDisposable _attach_op;
+ bool _is_active, _is_disposed;
+
+ #region IsActive
+ public static readonly DependencyProperty IsActiveProperty =
+ WPFHelper.create_dp(
+ nameof(IsActive),
+ FrameworkPropertyMetadataOptions.AffectsRender,
+ (o, v) => {
+ o._is_active = v;
+ Disposable.dispose(ref o._attach_op);
+ if (v && !o._is_disposed) {
+ o.IsHitTestVisible = true;
+ o._attach_op = Disposable.Create(
+ o.SubscribePreviewMouseDown((s, e) => {
+ if (e.ChangedButton == MouseButton.Left) {
+ if (e.ClickCount > 1 && o.TargetRow is OrderBookRowVM r) {
+ e.Handled = true;
+ o._raise_target_row_selected(r);
+ }
+ }
+ }),
+ o.AdornedElement.SubscribeMouseHoverRow().Subscribe(row => o.TargetRow = row));
+ } else {
+ o.IsHitTestVisible = false;
+ o.TargetRow = null;
+ }
+ },
+ false);
+
+ public bool IsActive {
+ get => (bool)GetValue(IsActiveProperty);
+ set => SetValue(IsActiveProperty, value);
+ }
+
+ public event Action TargetRowSelected;
+ #endregion
+
+ public OrderBookAttachmentTargetAdorner(DIYGrid grid) : base(grid) { }
+
+ public void Dispose() {
+ if (!_is_disposed) {
+ _is_disposed = true;
+ Disposable.dispose(ref _attach_op);
+ }
+ }
+
+ void _raise_target_row_selected(OrderBookRowVM row) => TargetRowSelected?.Invoke(row);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml
new file mode 100644
index 000000000..10493f539
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml
@@ -0,0 +1,132 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookView.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs
similarity index 54%
rename from src/client/spark/Modules/Trading/OrderBook/OrderBookView.xaml.cs
rename to src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs
index 8fb0a43c9..945a5eb9f 100644
--- a/src/client/spark/Modules/Trading/OrderBook/OrderBookView.xaml.cs
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs
@@ -1,11 +1,7 @@
using mbts.ui.controls;
-using System.Windows.Controls;
namespace mbts.spark {
- internal partial class OrderBookView : UserControl {
- // IMPORTANT: these enums are stored as strings in the general-purpose GridColumnSettings proto, and are used to ID THE COLUMNS!
- // Do NOT RENAME them! However, if you must, be sure to write an IShellWindowMigrationRule or something to account for backwards compatability.
- public enum Columns { Security, Symbol, Time, LastChange, User, Account, Exchange, TimeInForce, OrderType, SubType, Side, Size, Price, Filled, AvgFilled, LastPrice, Status, LastMessage, SecurityKey, OrderKey, ParentKey, Cancel, EditableQty, EditablePrice }
+ internal partial class OrderBookGridView : DIYGrid {
public const string
SubTypeFilterTemplateKey = "SubTypeFilterTemplate",
ExpandCollapseToggleStyleKey = "ExpandCollapseToggleStyle",
@@ -14,13 +10,41 @@ namespace mbts.spark {
CVRowStyleKey = "CVRowStyle",
CVRowTemplateKey = "CVRowTemplateKey";
- public OrderBookView(OrderBookVM vm) {
- InitializeComponent();
- DataContext = vm;
+ // IMPORTANT: these enums are stored as strings in the general-purpose GridColumnSettings proto, and are used to ID THE COLUMNS!
+ // Do NOT RENAME them! However, if you must, be sure to write an IShellWindowMigrationRule or something to account for backwards compatability.
+ public enum ColumnKeys {
+ Security,
+ Symbol,
+ Time,
+ LastChange,
+ User,
+ Account,
+ Exchange,
+ TimeInForce,
+ OrderType,
+ SubType,
+ Side,
+ Size,
+ Price,
+ Filled,
+ AvgFilled,
+ LastPrice,
+ Status,
+ LastMessage,
+ SecurityKey,
+ OrderKey,
+ ParentKey,
+ AttachedTargetOrderKey,
+ Cancel,
+ EditableQty,
+ EditablePrice
}
+
+ public OrderBookGridView() =>
+ InitializeComponent();
}
- class OrderBookRowView : DIYGrid.HighPerformanceRow {
+ class OrderBookRowView : DIYGrid.HighPerformanceRow {
public OrderBookRowView() : base() { }
}
}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml
new file mode 100644
index 000000000..bb11c6804
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml
@@ -0,0 +1,407 @@
+
+
+
+
+
+
+
+ 5
+ 64
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs
new file mode 100644
index 000000000..47f721fa6
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs
@@ -0,0 +1,151 @@
+//#define EXPAND_ATTACHMENT_PANEL
+using mbts.ui;
+using mbts.ui.converters;
+using mbts.ui.extensions;
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+
+namespace mbts.spark {
+ internal partial class OrderBookView : UserControl {
+ public const double
+ GridSplitterWidth = 5,
+ GridSplitterHeight = 5,
+ MinAlgoEditorHeight = 64,
+ MinAttachOrderParamsPanelWidth = 340,
+ AttachOrderParamsPanelWidthRatio = 0.33;
+
+ public static readonly IValueConverter
+ OrderDescriptionConverter = ValueConverter.create(row => row == null ? string.Empty : row.order.short_description(row.security)),
+ FillsSlaveGridMaxHeightConverter = ValueConverter.create(right_panel_height => right_panel_height - (GridSplitterHeight + MinAlgoEditorHeight)),
+ FillsPanelVisualStateConverter = ValueConverter.create(show => show ? VisualStateNames.FillsPanel.Active : VisualStateNames.FillsPanel.Inactive),
+ AttachmentTargetCursorConverter = ValueConverter.create(is_active => is_active ? Cursors.Pen : Cursors.Arrow);
+
+ public static readonly IMultiValueConverter
+ RightPanelVisualStateConverter = ValueConverter.create((is_modifying, is_attaching) =>
+ is_attaching ? VisualStateNames.RightPanel.AttachOrders :
+ (is_modifying ? VisualStateNames.RightPanel.ModifyOrders : VisualStateNames.RightPanel.Normal)),
+ RightPanelDialogSkirtLeftAnchorConverter = ValueConverter.create((canvas_width, skirt_width) => canvas_width - skirt_width + GridSplitterWidth),
+ FillsSlaveGridStateConverter = ValueConverter.create((is_fills_grid_visible, is_attaching) => is_fills_grid_visible && !is_attaching ? VisualStateNames.FillsPanel.Active : VisualStateNames.FillsPanel.Inactive);
+
+ public OrderBookView(OrderBookVM vm) {
+ InitializeComponent();
+ DataContext = vm;
+#if EXPAND_ATTACHMENT_PANEL
+ (RightPanelState right_panel, IDisposable hooks)? attach_op = null;
+ vm.begin_attaching += on_begin_attaching;
+ vm.end_attaching += on_end_attaching;
+ vm.SubscribeDisposed(() => {
+ if (attach_op.HasValue) {
+ vm.right_panel_width = attach_op.Value.right_panel.raw_width;
+ vm.fills_slave_grid_is_visible = attach_op.Value.right_panel.fills_slave_grid_is_visible;
+ }
+ vm.begin_attaching -= on_begin_attaching;
+ vm.end_attaching -= on_end_attaching;
+ });
+ const int delay_ms = 25;
+ async void on_begin_attaching() {
+ if (attach_op.HasValue) {
+ // begin-attaching is already underway (prob won't happen in practice as this event is triggered by user interaction)
+ return;
+ }
+ attach_op = (new RightPanelState(vm.right_panel_is_visible, vm.fills_slave_grid_is_visible, vm.raw_right_panel_width), orders_grid.SubscribePreviewMouseDown(cancel_on_grid_click));
+ vm.fills_slave_grid_is_visible = false;
+ vm.algo_editor_is_visible = true;
+ double target_width = Math.Max(ActualWidth * AttachOrderParamsPanelWidthRatio, MinAttachOrderParamsPanelWidth);
+ if (vm.right_panel_width < target_width) {
+ foreach (double incr in _get_incremental_widths(attach_op.Value.right_panel.is_visible ? attach_op.Value.right_panel.raw_width : 0, target_width)) {
+ vm.right_panel_width = incr;
+ await Task.Delay(delay_ms);
+ if (!attach_op.HasValue)
+ break;
+ }
+ }
+ }
+ async void on_end_attaching() {
+ if (!attach_op.HasValue) {
+ // end-attaching is already underway (prob won't happen in practice as this event is triggered by user interaction)
+ return;
+ }
+ attach_op.Value.hooks.Dispose();
+ var incr_widths = _get_incremental_widths(vm.right_panel_width, attach_op.Value.right_panel.raw_width);
+ vm.algo_editor_is_visible = attach_op.Value.right_panel.is_visible;
+ vm.fills_slave_grid_is_visible = attach_op.Value.right_panel.fills_slave_grid_is_visible;
+ vm.right_panel_width = attach_op.Value.right_panel.raw_width;
+ attach_op = null;
+ foreach (double incr in incr_widths) {
+ vm.right_panel_width = incr;
+ await Task.Delay(delay_ms);
+ if (attach_op.HasValue)
+ break;
+ }
+ }
+#else
+ IDisposable attach_op = null;
+ vm.begin_attaching += on_begin_attaching;
+ vm.end_attaching += on_end_attaching;
+ void on_begin_attaching() => Disposable.replace(ref attach_op, orders_grid.SubscribePreviewMouseDown(cancel_on_grid_click));
+ void on_end_attaching() => Disposable.dispose(ref attach_op);
+#endif
+ void cancel_on_grid_click(object sender, MouseButtonEventArgs e) {
+ if (!KeyboardExtensions.IsCtrlDown() && !KeyboardExtensions.IsShiftDown())
+ vm.is_attaching_algos = false;
+ }
+ }
+
+ static IEnumerable _get_incremental_widths(double from, double to) {
+ var list = new List { to };
+ int incr = 1;
+ if (from < to) {
+ do {
+ list.Add(to - (incr * 0.6666));
+ list.Add(to - incr);
+ from += incr;
+ incr += incr;
+ } while (from < to);
+ } else if (from > to) {
+ do {
+ list.Add(to + incr);
+ incr += incr;
+ to += incr;
+ } while (from > to);
+ }
+ for (int i = list.Count - 1; i >= 0; i--) {
+ yield return list[i];
+ }
+ }
+
+ struct RightPanelState {
+ public readonly bool is_visible, fills_slave_grid_is_visible;
+ public readonly double raw_width;
+
+ public RightPanelState(bool right_panel_is_visible, bool fills_slave_grid_is_visible, double raw_right_panel_width) {
+ this.is_visible = right_panel_is_visible;
+ this.fills_slave_grid_is_visible = fills_slave_grid_is_visible;
+ this.raw_width = raw_right_panel_width;
+ }
+ }
+
+ public static class VisualStateNames {
+ public static class RightPanel {
+ public const string GroupName = nameof(RightPanel);
+
+ public static readonly string
+ Normal = $"{GroupName}{nameof(Normal)}",
+ ModifyOrders = $"{GroupName}{nameof(ModifyOrders)}",
+ AttachOrders = $"{GroupName}{nameof(AttachOrders)}";
+ }
+
+ public static class FillsPanel {
+ public const string GroupName = nameof(FillsPanel);
+
+ public static readonly string
+ Active = $"{GroupName}{VisualStates.Active}",
+ Inactive = $"{GroupName}{VisualStates.Inactive}";
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml
new file mode 100644
index 000000000..8cf59f2dc
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml
@@ -0,0 +1,143 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml.cs
new file mode 100644
index 000000000..ed665c4e7
--- /dev/null
+++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml.cs
@@ -0,0 +1,188 @@
+using bts.api;
+using mbts.spark;
+using System;
+using System.Collections;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+
+namespace mbts.ui.spark {
+ class OrderParamsPanel : Control {
+ public const string
+ BestBidPriceButtonStyleKey = nameof(BestBidPriceButtonStyleKey),
+ BestBidSizeButtonStyleKey = nameof(BestBidSizeButtonStyleKey),
+ BestAskPriceButtonStyleKey = nameof(BestAskPriceButtonStyleKey),
+ BestAskSizeButtonStyleKey = nameof(BestAskSizeButtonStyleKey),
+ SizeCalculatorButtonStyleKey = nameof(SizeCalculatorButtonStyleKey);
+
+ public static readonly RoutedCommand SetPriceCommand = new RoutedCommand();
+
+ public static readonly ExecutedRoutedEventHandler SetPriceExecuted =
+ (s, e) => {
+ if (s is OrderParamsPanel opp)
+ opp.SetCurrentValue(PriceProperty, ConvertUtils.try_convert(e.Parameter, out double d) ? d : double.NaN);
+ };
+
+ public static readonly CanExecuteRoutedEventHandler
+ SetPriceCanExecute = (s, e) => e.CanExecute = e.Parameter is double,
+ SetSizeCanExecute = (s, e) => e.CanExecute = e.Parameter is uint;
+
+ static OrderParamsPanel() {
+ DefaultStyleKeyProperty.OverrideMetadata(typeof(OrderParamsPanel), new FrameworkPropertyMetadata(typeof(OrderParamsPanel)));
+ }
+
+ #region Price
+ public static readonly DependencyProperty PriceProperty =
+ WPFHelper.create_dp(nameof(Price), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, double.NaN);
+
+ public double Price {
+ get => (double)GetValue(PriceProperty);
+ set => SetValue(PriceProperty, value);
+ }
+ #endregion
+
+ #region Size
+ public static readonly DependencyProperty SizeProperty =
+ WPFHelper.create_dp(nameof(Size), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);
+
+ public uint? Size {
+ get => GetValue(SizeProperty) as uint?;
+ set => SetValue(SizeProperty, value);
+ }
+ #endregion
+
+ #region SizePresets
+ public static readonly DependencyProperty SizePresetsProperty =
+ WPFHelper.create_dp(nameof(SizePresets), Enumerable.Empty());
+
+ public IEnumerable SizePresets {
+ get => GetValue(SizePresetsProperty) as IEnumerable;
+ set => SetValue(SizePresetsProperty, value);
+ }
+ #endregion
+
+ #region BestBidPrice
+ public static readonly DependencyProperty BestBidPriceProperty =
+ WPFHelper.create_dp(nameof(BestBidPrice));
+
+ public double? BestBidPrice {
+ get => GetValue(BestBidPriceProperty) as double?;
+ set => SetValue(BestBidPriceProperty, value);
+ }
+ #endregion
+
+ #region BestBidSize
+ public static readonly DependencyProperty BestBidSizeProperty =
+ WPFHelper.create_dp(nameof(BestBidSize));
+
+ public uint? BestBidSize {
+ get => GetValue(BestBidSizeProperty) as uint?;
+ set => SetValue(BestBidSizeProperty, value);
+ }
+ #endregion
+
+ #region BestAskPrice
+ public static readonly DependencyProperty BestAskPriceProperty =
+ WPFHelper.create_dp(nameof(BestAskPrice));
+
+ public double? BestAskPrice {
+ get => GetValue(BestAskPriceProperty) as double?;
+ set => SetValue(BestAskPriceProperty, value);
+ }
+ #endregion
+
+ #region BestAskSize
+ public static readonly DependencyProperty BestAskSizeProperty =
+ WPFHelper.create_dp(nameof(BestAskSize));
+
+ public uint? BestAskSize {
+ get => GetValue(BestAskSizeProperty) as uint?;
+ set => SetValue(BestAskSizeProperty, value);
+ }
+ #endregion
+
+ #region Accounts
+ public static readonly DependencyProperty AccountsProperty =
+ WPFHelper.create_dp(nameof(Accounts), Enumerable.Empty());
+
+ public IEnumerable Accounts {
+ get => GetValue(AccountsProperty) as IEnumerable;
+ set => SetValue(AccountsProperty, value);
+ }
+ #endregion
+
+ #region SelectedAccount
+ public static readonly DependencyProperty SelectedAccountProperty =
+ WPFHelper.create_dp