Merge branch 'master' into SPARK-1992-position-limits-test

This commit is contained in:
Michael Harding committed 2019-02-22 13:42:35 -05:00
commit e0c090b8e5
242 files changed
+16125 -4348

No files matched your search

+5 -1
View File
@@ -7,6 +7,10 @@ insert_anchor_links = "right"
## 1.5.0
### User Visible Changes
#### New Features
- This release introduces a major new feature, the Algo Studio, a
set of tools allowing traders to create their own algos by
composing existing algos to express unique strategies.
#### User Interface Improvements
- Removed security key field from most grids
- Removed trade key field from time and sales grid
@@ -33,7 +37,7 @@ insert_anchor_links = "right"
- Fixed a bug in handling of built-in bts to user that could lead to failure to login as bts in old systems
- Improved market data subsystem to support security definition updates
- Fixed a startup race in market data that could lead to data corruption on startup
- Increased default order price precision to 8 digis as required by some CME products
## 1.4.11
### New Features
+23 -3
View File
@@ -9,6 +9,7 @@ using System.ComponentModel.Composition;
using System.Reactive.Linq;
using System.Windows.Threading;
using System.Windows;
using System.Threading.Tasks;
namespace bts.spark
{
@@ -48,8 +49,7 @@ namespace bts.spark
}
}
static class ErrorReporterExtensions
{
static class ErrorReporterExtensions {
public static bool handle_error<T, TError>(this ErrorReporter error_reporter, Result<T> result, string template, TError error, bool error_ok) =>
handle_error(error_reporter, result, template, error, error_ok, false, true);
@@ -81,5 +81,25 @@ namespace bts.spark
return (get_unsuccessful_rv(), result.error_message);
}
}
//public static async Task<Result<T>>
public static async Task<(T value, bool success)> safe_execute<T>(this ErrorReporter error_reporter, Func<Task<Result<T>>> execute, Func<T, bool> get_success, Func<T, string> get_error_msg, string desc) {
try {
var result = await execute();
if (!result.success) {
_report_error(result.error_message);
} else if (!get_success(result.value)) {
_report_error(get_error_msg(result.value));
} else {
return (result.value, true);
}
} catch (Exception ex) {
_report_error(ex.ToString());
}
return (default, false);
//
void _report_error(string msg) =>
error_reporter.report_error($"Error {desc}: {msg}", AlgoStudioWindow.NAME, MessageBoxImage.Warning);
}
}
}
}
@@ -39,8 +39,11 @@ namespace bts.shell {
public void Dispose() =>
Disposable.dispose(ref _dispose);
static void _show_order_window(Window window) =>
void _show_order_window(Window window) {
foreach (var kv in AlgoStudioModelUtils.get_dynamic_resources(_model.algo_model.ui_configuration))
window.Resources[kv.Key] = kv.Value;
window.Show(-200, -160, true);
}
void _show_order_ticket(SecurityMD smd) =>
_show_order_window(new OrderTicket {
+35 -2
View File
@@ -11,7 +11,7 @@ using bts.support;
using System.ComponentModel.Composition;
namespace Spark {
public class ShellServices {
class ShellServices {
[Export]
public ServiceContext context { get; } = new ServiceContext();
@@ -44,5 +44,38 @@ namespace Spark {
[Export]
public MarketDataRelay md_replay => context.locate<MarketDataRelay>();
//[Export]
//public AlgoService algo_service => context.locate<AlgoService>();
AlgoServiceWrapper _algo_service_wrapper;
[Export]
public AlgoServiceWrapper algo_service_wrapper => _algo_service_wrapper ?? (_algo_service_wrapper = new AlgoServiceWrapper(context));
}
}
class AlgoServiceWrapper {
public enum Mode {
None,
Hierarchical,
Flat
}
public AlgoServiceWrapper(ServiceContext context) {
var flat_model_options = mbts.config.Configuration.get<bts.config.AlgoStudioFlatDefinitionModelOptions>();
if (flat_model_options.enabled) {
flat = context.locate<bts.api.orderman.algo.AlgoDefinitionService>();
} else {
hierarhical = context.locate<AlgoService>();
}
}
public AlgoService hierarhical { get; }
public bts.api.orderman.algo.AlgoDefinitionService flat { get; }
public Mode mode {
get {
if (hierarhical != null) return Mode.Hierarchical;
if (flat != null) return Mode.Flat;
return Mode.None;
}
}
}
}
+61 -12
View File
@@ -8,15 +8,43 @@ using System.Windows.Media.Imaging;
namespace mbts.ui {
public class Icons {
public static class Smashicons {
public static readonly string
AddFileGeometryKey = _fmt("AddFile"),
EditDocumentGeometryKey = _fmt("EditDocument"),
DeleteDocumentGeometryKey = _fmt("DeleteDocument"),
SaveGeometryKey = _fmt("Save");
static string _fmt(string name) =>
$"{nameof(Smashicons)}.{name}.GeometryKey";
}
public const string
AddBoxesGeometryKey = nameof(AddBoxesGeometryKey),
AddFileGeometryKey = nameof(AddFileGeometryKey),
AddFileThinGeometryKey = nameof(AddFileThinGeometryKey),
CheckMarkGeometryKey = nameof(CheckMarkGeometryKey),
DiskGeometryKey = nameof(DiskGeometryKey),
DiskFileGeometryKey = nameof(DiskFileGeometryKey),
DocumentGeometryKey = nameof(DocumentGeometryKey),
DocumentBrokenGeometryKey = nameof(DocumentBrokenGeometryKey),
DocumentCopyGeometryKey = nameof(DocumentCopyGeometryKey),
DocumentEmptyGeometryKey = nameof(DocumentEmptyGeometryKey),
DocumentPairGeometryKey = nameof(DocumentPairGeometryKey),
DocumentStarGeometryKey = nameof(DocumentStarGeometryKey),
DraggableGeometryKey = nameof(DraggableGeometryKey),
EditDocumentAltGeometryKey = nameof(EditDocumentAltGeometryKey),
EditDocumentGeometryKey = nameof(EditDocumentGeometryKey),
GearGeometryKey = nameof(GearGeometryKey),
OrdersGeometryKey = nameof(OrdersGeometryKey),
PaymentGeometryKey = nameof(PaymentGeometryKey),
PencilGeometryKey = nameof(PencilGeometryKey),
PlayGeometryKey = nameof(PlayGeometryKey),
StarGeometryKey = nameof(StarGeometryKey),
ToolsGeometryKey = nameof(ToolsGeometryKey),
DraggableGeometryKey = nameof(DraggableGeometryKey);
TrashGeometryKey = nameof(TrashGeometryKey),
UndoCircularGeometryKey = nameof(UndoCircularGeometryKey);
public static Geometry PlayGeometry => Geometry.Parse(_get_geometric_path(PlayGeometryKey).FirstOrDefault() ?? string.Empty);
public static Geometry PlayGeometry => Geometry.Parse(get_geometric_path(PlayGeometryKey).FirstOrDefault() ?? string.Empty);
static readonly string base_uri = "pack://application:,,,/Images/Icons/";
private static ResourceDictionary _resources = (ResourceDictionary)Application.LoadComponent(new Uri("/Images/Vector/Icons.xaml", UriKind.RelativeOrAbsolute));
@@ -80,13 +108,13 @@ namespace mbts.ui {
public static ImageSource Bookmarks { get { return load_resource_and_freeze("Bookmarks"); } }
public static ImageSource Window { get { return load_resource_and_freeze("Window"); } }
public static ImageSource ActiveWindow { get { return load_resource_and_freeze("ActiveWindow"); } }
public static ImageSource Trash { get { return load_resource_and_freeze("Trash"); } }
public static ImageSource Trash2 { get { return load_resource_and_freeze("Trash2"); } }
public static ImageSource Crucible { get { return load_resource_and_freeze("Crucible"); } }
public static ImageSource Accounting { get { return load_resource_and_freeze("Accounting"); } }
public static ImageSource Add { get { return load_resource_and_freeze("Add"); } }
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 Beaker { get { return load_resource_and_freeze("Beaker"); } }
public static ImageSource Book { get { return load_resource_and_freeze("Book"); } }
@@ -108,10 +136,19 @@ namespace mbts.ui {
public static ImageSource CloneSynthetic { get { return load_resource_and_freeze("CloneSynthetic"); } }
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 Defrag { get { return load_resource_and_freeze("Defrag"); } }
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 DocumentBroken => create_icon(DocumentBrokenGeometryKey);
public static ImageSource DocumentCopy => create_icon(DocumentCopyGeometryKey);
public static ImageSource DocumentEmpty => create_icon(DocumentEmptyGeometryKey);
public static ImageSource DocumentPair => create_icon(DocumentPairGeometryKey);
public static ImageSource DocumentStar => create_icon(DocumentStarGeometryKey);
public static ImageSource Draggable => create_icon(DraggableGeometryKey);
public static ImageSource EditDocument => create_icon("Smashicons.EditDocument.GeometryKey");
public static ImageSource Export => load_resource_and_freeze("Export");
public static ImageSource Filter { get { return load_resource_and_freeze("Filter"); } }
public static ImageSource FilterActive { get { return load_resource_and_freeze("FilterActive"); } }
@@ -120,10 +157,15 @@ namespace mbts.ui {
public static ImageSource Import => load_resource_and_freeze("Import");
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 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);
public static ImageSource Target { get { return load_resource_and_freeze("Target"); } }
public static ImageSource Tetris { get { return load_resource_and_freeze("Tetris"); } }
public static ImageSource Tools => create_icon(ToolsGeometryKey);
public static ImageSource Trash => create_icon(TrashGeometryKey);
public static ImageSource UndoCircular => create_icon(UndoCircularGeometryKey);
public static ImageSource ViewSettings => load_resource_and_freeze("ViewSettings");
public static ImageSource Wrench { get { return load_resource_and_freeze("Wrench"); } }
public static ImageSource RightArrow { get { return (load_resource_and_freeze("RightArrow")); } }
@@ -131,29 +173,36 @@ namespace mbts.ui {
public static ImageSource Factory { get { return (load_resource_and_freeze("Factory")); } }
public static ImageSource DotsVertical { get { return (load_resource_and_freeze("DotsVertical")); } }
public static ImageSource HandPointingOverDocument => load_resource_and_freeze("HandPointingOverDocument");
public static ImageSource Support => load_resource_and_freeze("SupportIcon");␍
public static ImageSource Support => load_resource_and_freeze("SupportIcon");
public static ImageSource FloppyDisk => create_icon("FloppyDisk");
public static ImageSource create_icon(string geometric_path_key) =>
create_icon(geometric_path_key, Brushes.Black);
public static ImageSource create_icon(string geometric_path_key, Brush brush, Pen pen = null) =>
new DrawingImage(create_drawing(geometric_path_key, brush, pen));
public static ImageSource create_icon(string geometric_path_key, Brush brush, Pen pen = null, Transform transform = null) {
var rv = new DrawingImage(create_drawing(geometric_path_key, brush, pen, transform));
rv.Freeze();
return rv;
}
public static Drawing create_drawing(string geometric_path_key) =>
create_drawing(geometric_path_key, Brushes.Black);
public static Drawing create_drawing(string geometric_path_key, Brush brush, Pen pen = null) =>
create_drawing(_get_geometric_path(geometric_path_key), brush, pen);
public static Drawing create_drawing(string geometric_path_key, Brush brush, Pen pen = null, Transform transform = null) =>
create_drawing(get_geometric_path(geometric_path_key), brush, pen, transform);
public static Drawing create_drawing(IEnumerable<string> paths, Brush brush, Pen pen = null) {
public static Drawing create_drawing(IEnumerable<string> paths, Brush brush, Pen pen = null, Transform transform = null) {
var drawing_group = new DrawingGroup();
foreach (string p in paths) {
drawing_group.Children.Add(new GeometryDrawing(brush, pen, Geometry.Parse(p)));
}
if (transform != null)
drawing_group.Transform = transform;
return drawing_group;
}
static IEnumerable<string> _get_geometric_path(string geometric_path_key) {
public static IEnumerable<string> get_geometric_path(string geometric_path_key) {
object obj;
lock (_resources) {
obj = _resources[geometric_path_key];
@@ -169,4 +218,4 @@ namespace mbts.ui {
} else return null;
}
}
}
}
+292 -31
View File
@@ -5,6 +5,241 @@
xmlns:mbts="clr-namespace:mbts.ui"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<!--AddBoxes (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/gregor-cresnar
Ttile: Add free icon
Credit: Icon made by Gregor Cresnar from www.flaticon.com-->
<sys:String x:Key="{x:Static mbts:Icons.AddBoxesGeometryKey}">
M393,480.3c0-5-4.1-9.1-9.1-9.1H18.2V105.5c0-5-4.1-9.1-9.1-9.1S0,100.5,0,105.5v374.8c0,5,4.1,9.1,9.1,9.1h374.8 C388.9,489.4,393,485.3,393,480.3z
M373.9,187.5H302v-71.9c0-5-4.1-9.1-9.1-9.1s-9.1,4.1-9.1,9.1v71.9h-71.9c-5,0-9.1,4.1-9.1,9.1s4.1,9.1,9.1,9.1h71.9v71.9 c0,5,4.1,9.1,9.1,9.1s9.1-4.1,9.1-9.1v-71.9h71.9c5,0,9.1-4.1,9.1-9.1C382.9,191.5,378.9,187.5,373.9,187.5z
M105.5,393h374.8c5,0,9.1-4.1,9.1-9.1V9.1c0-5-4.1-9.1-9.1-9.1H105.5c-5,0-9.1,4.1-9.1,9.1v374.8 C96.4,388.9,100.5,393,105.5,393z M114.5,18.2h356.7v356.7H114.5V18.2z
</sys:String>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: Add file free icon
Credit: Icon made by Freepik from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.AddFileGeometryKey}" Type="sys:String">
<sys:String>
m95.332031 222.800781h192.800781c8.285157 0 15-6.714843 15-15 0-8.285156-6.714843-15-15-15h-192.800781c-8.28125 0-15 6.714844-15 15 0 8.285157 6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m95.332031 287.066406h192.800781c8.285157 0 15-6.714844 15-15s-6.714843-15-15-15h-192.800781c-8.28125 0-15 6.714844-15 15s6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m191.734375 321.332031h-96.402344c-8.28125 0-15 6.71875-15 15 0 8.285157 6.71875 15 15 15h96.402344c8.28125 0 15-6.714843 15-15 0-8.28125-6.71875-15-15-15zm0 0
</sys:String>
<sys:String>
m191.734375 385.601562h-96.402344c-8.28125 0-15 6.714844-15 15 0 8.28125 6.71875 15 15 15h96.402344c8.28125 0 15-6.71875 15-15 0-8.285156-6.71875-15-15-15zm0 0
</sys:String>
<sys:String>
m383.464844 290.214844v-243.082032c0-25.988281-21.144532-47.132812-47.132813-47.132812h-224.933593c-3.976563 0-7.792969 1.582031-10.605469 4.394531l-96.398438 96.398438c-2.8125 2.8125-4.394531 6.628906-4.394531 10.605469v353.46875c0 25.988281 21.144531 47.132812 47.132812 47.132812h321.332032c61.425781 0 111.402344-49.972656 111.402344-111.398438 0-56.339843-42.042969-103.039062-96.402344-110.386718zm-271-255.066406v60.1875c0 9.445312-7.683594 17.132812-17.132813 17.132812h-60.1875zm-65.332032 446.851562c-9.445312 0-17.132812-7.6875-17.132812-17.132812v-322.398438h65.332031c25.988281 0 47.132813-21.144531 47.132813-47.132812v-65.335938h193.867187c9.449219 0 17.132813 7.6875 17.132813 17.132812v243.082032c-54.355469 7.347656-96.398438 54.046875-96.398438 110.382812 0 32.09375 13.644532 61.054688 35.433594 81.402344zm321.332032 0c-44.882813 0-81.398438-36.515625-81.398438-81.398438 0-44.886718 36.515625-81.402343 81.398438-81.402343 44.886718 0 81.402344 36.515625 81.402344 81.402343 0 44.882813-36.515626 81.398438-81.402344 81.398438zm0 0
</sys:String>
<sys:String>
m400.601562 385.601562h-17.132812v-17.132812c0-8.285156-6.71875-15-15-15-8.285156 0-15 6.714844-15 15v17.132812h-17.136719c-8.28125 0-15 6.714844-15 15 0 8.28125 6.71875 15 15 15h17.132813v17.132813c0 8.28125 6.71875 15 15 15 8.285156 0 15-6.71875 15-15v-17.132813h17.132812c8.285156 0 15-6.71875 15-15 0-8.285156-6.714844-15-14.996094-15zm0 0
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/smashicons
Ttile: File free icon
Credit: Icon made by Smashicons from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.DocumentBrokenGeometryKey}" Type="sys:String">
<sys:String>
M36,22.001H11c-0.552,0-1,0.448-1,1s0.448,1,1,1h25c0.552,0,1-0.448,1-1S36.552,22.001,36,22.001z
M11,16.001h10c0.552,0,1-0.448,1-1s-0.448-1-1-1H11c-0.552,0-1,0.448-1,1S10.448,16.001,11,16.001z
M37,31.001c0-0.552-0.448-1-1-1H11c-0.552,0-1,0.448-1,1s0.448,1,1,1h25C36.552,32.001,37,31.553,37,31.001z
M29,39.001c0-0.552-0.448-1-1-1H11c-0.552,0-1,0.448-1,1s0.448,1,1,1h17C28.552,40.001,29,39.553,29,39.001z
M11,46.001c-0.552,0-1,0.448-1,1s0.448,1,1,1h14c0.552,0,1-0.448,1-1s-0.448-1-1-1H11z
M2,2.001h29v14h14v17h2V14.587L32.414,0.001H0v60h30v-2H2V2.001z M33,3.415l10.586,10.586H33V3.415z
M59.693,56.636L47.849,36.329c-0.406-0.695-1.128-1.11-1.934-1.11c-0.805,0-1.527,0.415-1.933,1.11L32.137,56.636
c-0.409,0.701-0.412,1.539-0.008,2.242c0.404,0.703,1.129,1.123,1.94,1.123h23.691c0.811,0,1.536-0.42,1.939-1.123
C60.104,58.175,60.102,57.336,59.693,56.636z M57.966,57.882c-0.03,0.055-0.092,0.119-0.205,0.119H34.07
c-0.114,0-0.175-0.065-0.206-0.119c-0.031-0.055-0.056-0.14,0.001-0.238L45.71,37.337c0.057-0.098,0.143-0.118,0.205-0.118
c0.063,0,0.148,0.021,0.206,0.118l11.845,20.306C58.022,57.742,57.998,57.827,57.966,57.882z
M46,42.001c-0.552,0-1,0.448-1,1v8c0,0.552,0.448,1,1,1s1-0.448,1-1v-8C47,42.448,46.552,42.001,46,42.001z
M45.29,54.291c-0.18,0.19-0.29,0.45-0.29,0.71c0,0.26,0.11,0.52,0.29,0.71c0.19,0.18,0.45,0.29,0.71,0.29
c0.27,0,0.52-0.11,0.71-0.29c0.18-0.19,0.29-0.45,0.29-0.71c0-0.26-0.11-0.52-0.29-0.71C46.33,53.921,45.67,53.921,45.29,54.291z
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/smashicons
Ttile: File free icon
Credit: Icon made by Smashicons from www.flaticon.com-->
<sys:String x:Key="Smashicons.AddFile.GeometryKey">
M12.5,24h25c0.552,0,1-0.448,1-1s-0.448-1-1-1h-25c-0.552,0-1,0.448-1,1S11.948,24,12.5,24z
M12.5,16h10c0.552,0,1-0.448,1-1s-0.448-1-1-1h-10c-0.552,0-1,0.448-1,1S11.948,16,12.5,16z
M12.5,32h25c0.552,0,1-0.448,1-1s-0.448-1-1-1h-25c-0.552,0-1,0.448-1,1S11.948,32,12.5,32z
M29.5,38h-17c-0.552,0-1,0.448-1,1s0.448,1,1,1h17c0.552,0,1-0.448,1-1S30.052,38,29.5,38z
M26.5,46h-14c-0.552,0-1,0.448-1,1s0.448,1,1,1h14c0.552,0,1-0.448,1-1S27.052,46,26.5,46z
M48.5,34.363V14.586L33.914,0H1.5v60h44c7.168,0,13-5.832,13-13C58.5,40.866,54.224,35.723,48.5,34.363z M34.5,3.414
L45.086,14H34.5V3.414z M38.578,58H3.5V2h29v14h14v18.044C46.158,34.015,45.826,34,45.5,34c-7.168,0-13,5.832-13,13
c0,0.399,0.025,0.792,0.06,1.183c0.008,0.091,0.017,0.181,0.027,0.272c0.043,0.382,0.098,0.76,0.173,1.131
c0.009,0.044,0.021,0.087,0.03,0.131c0.072,0.338,0.159,0.67,0.257,0.998c0.025,0.082,0.048,0.165,0.074,0.246
c0.113,0.352,0.239,0.698,0.38,1.037c0.027,0.064,0.057,0.126,0.084,0.189c0.129,0.296,0.269,0.585,0.419,0.869
c0.036,0.068,0.07,0.137,0.107,0.205c0.175,0.317,0.363,0.626,0.564,0.927c0.046,0.069,0.094,0.135,0.141,0.203
c0.183,0.264,0.375,0.521,0.576,0.77c0.038,0.047,0.074,0.096,0.113,0.143c0.231,0.278,0.475,0.544,0.728,0.801
c0.062,0.063,0.125,0.124,0.189,0.186c0.245,0.239,0.496,0.471,0.759,0.69c0.023,0.02,0.045,0.041,0.069,0.06
c0.282,0.232,0.577,0.449,0.879,0.658c0.073,0.051,0.147,0.1,0.221,0.149C38.427,57.897,38.501,57.951,38.578,58z M45.5,58
c-6.065,0-11-4.935-11-11s4.935-11,11-11c0.312,0,0.62,0.021,0.926,0.047c0.291,0.028,0.592,0.066,0.909,0.119l0.443,0.074
C52.753,37.293,56.5,41.716,56.5,47C56.5,53.065,51.565,58,45.5,58z
M51.5,46h-5v-5c0-0.552-0.448-1-1-1s-1,0.448-1,1v5h-5c-0.552,0-1,0.448-1,1s0.448,1,1,1h5v5c0,0.552,0.448,1,1,1
s1-0.448,1-1v-5h5c0.552,0,1-0.448,1-1S52.052,46,51.5,46z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.DiskGeometryKey}">
M403.213,20H0v472h512V128.787L403.213,20z M131,50h180v100h10h20h10V50h30v130H131V50z M381,462H131V315
c0-8.271,6.729-15,15-15h220c8.271,0,15,6.729,15,15V462z M482,462h-71V315c0-24.813-20.187-45-45-45H146
c-24.813,0-45,20.187-45,45v147H30V50h71v160h310V70.213l71,71V462z
</sys:String>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: Document free icon
Credit: Icon made by Freepik from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.DocumentCopyGeometryKey}" Type="sys:String">
<sys:String>
m150 166c5.519531 0 10-4.480469 10-10s-4.480469-10-10-10-10 4.480469-10 10 4.480469 10 10 10zm0 0
</sys:String>
<sys:String>
m290 146h-100c-5.523438 0-10 4.476562-10 10s4.476562 10 10 10h100c5.523438 0 10-4.476562 10-10s-4.476562-10-10-10zm0 0
</sys:String>
<sys:String>
m70 0c-5.523438 0-10 4.476562-10 10v101.855469l-57.070312 57.074219c-1.832032 1.832031-2.929688 4.371093-2.929688 7.070312v326c0 5.523438 4.476562 10 10 10h320c5.523438 0 10-4.476562 10-10v-56h50c5.523438 0 10-4.476562 10-10v-426c0-5.523438-4.476562-10-10-10zm30 100.140625v65.859375h-65.855469zm220 391.859375h-300v-306h90c5.523438 0 10-4.476562 10-10v-90h200zm60-66h-40v-350c0-5.523438-4.476562-10-10-10h-220c-2.738281 0-5.328125 1.183594-7.070312 2.929688l-22.929688 22.925781v-71.855469h300zm0 0
</sys:String>
<sys:String>
m270 226h-200c-5.523438 0-10 4.476562-10 10s4.476562 10 10 10h200c5.523438 0 10-4.476562 10-10s-4.476562-10-10-10zm0 0
</sys:String>
<sys:String>
m270 286h-200c-5.523438 0-10 4.476562-10 10s4.476562 10 10 10h200c5.523438 0 10-4.476562 10-10s-4.476562-10-10-10zm0 0
</sys:String>
<sys:String>
m270 346h-200c-5.523438 0-10 4.476562-10 10s4.476562 10 10 10h200c5.523438 0 10-4.476562 10-10s-4.476562-10-10-10zm0 0
</sys:String>
<sys:String>
m270 406h-200c-5.523438 0-10 4.476562-10 10s4.476562 10 10 10h200c5.523438 0 10-4.476562 10-10s-4.476562-10-10-10zm0 0
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: File free icon
Credit: Icon made by Freepik from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.DocumentEmptyGeometryKey}" Type="sys:String">
<sys:String>
m336.332031 0h-224.933593c-3.976563 0-7.792969 1.582031-10.605469 4.394531l-96.398438 96.398438c-2.8125 2.8125-4.394531 6.628906-4.394531 10.605469v353.46875c0 25.988281 21.144531 47.132812 47.132812 47.132812h289.199219c12.597657 0 24.4375-4.90625 33.328125-13.808594 8.902344-8.898437 13.804688-20.734375 13.804688-33.324218v-417.734376c0-12.589843-4.902344-24.425781-13.796875-33.320312-8.898438-8.90625-20.738281-13.8125-33.335938-13.8125zm-223.863281 35.144531v60.1875c0 9.449219-7.6875 17.132813-17.132812 17.132813h-60.191407zm241 429.722657c0 4.574218-1.785156 8.875-5.027344 12.117187-3.230468 3.234375-7.53125 5.015625-12.105468 5.015625h-289.203126c-9.445312 0-17.132812-7.6875-17.132812-17.132812v-322.398438h65.332031c25.988281 0 47.132813-21.144531 47.132813-47.132812v-65.335938h193.867187c4.578125 0 8.878907 1.78125 12.117188 5.023438 3.234375 3.234374 5.015625 7.535156 5.015625 12.109374v417.734376zm0 0
</sys:String>
</x:Array>
<x:Array x:Key="{x:Static mbts:Icons.DocumentPairGeometryKey}" Type="sys:String">
<sys:String>
m352.898438 64.265625h-17.132813v-17.132813c0-25.988281-21.144531-47.132812-47.132813-47.132812h-176.734374c-3.976563 0-7.792969 1.582031-10.605469 4.394531l-96.398438 96.398438c-2.8125 2.8125-4.394531 6.628906-4.394531 10.605469v289.203124c0 25.988282 21.144531 47.132813 47.132812 47.132813h17.132813v17.132813c0 12.597656 4.90625 24.433593 13.804687 33.316406 8.894532 8.910156 20.734376 13.816406 33.332032 13.816406h241c25.988281 0 47.132812-21.144531 47.132812-47.132812v-353.46875c0-25.988282-21.144531-47.132813-47.136718-47.132813zm-239.933594-29.121094v60.1875c0 9.449219-7.683594 17.132813-17.132813 17.132813h-60.183593zm-82.464844 365.457031v-258.132812h65.332031c25.988281 0 47.132813-21.144531 47.132813-47.132812v-65.335938h145.667968c9.445313 0 17.132813 7.6875 17.132813 17.132812v353.46875c0 9.445313-7.6875 17.132813-17.132813 17.132813h-241c-9.449218 0-17.132812-7.6875-17.132812-17.132813zm339.535156 64.265626c0 9.445312-7.6875 17.132812-17.132812 17.132812h-241c-4.578125 0-8.875-1.78125-12.121094-5.027344-3.234375-3.230468-5.015625-7.53125-5.015625-12.105468v-17.132813h193.867187c25.992188 0 47.132813-21.144531 47.132813-47.132813v-306.335937h17.136719c9.445312 0 17.132812 7.6875 17.132812 17.132813zm0 0
</sys:String>
<sys:String>
m95.832031 222.800781h144.601563c8.285156 0 15-6.714843 15-15 0-8.285156-6.714844-15-15-15h-144.601563c-8.28125 0-15 6.714844-15 15 0 8.285157 6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m95.832031 287.066406h144.601563c8.285156 0 15-6.714844 15-15s-6.714844-15-15-15h-144.601563c-8.28125 0-15 6.714844-15 15s6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m95.832031 351.332031h80.335938c8.28125 0 15-6.714843 15-15 0-8.28125-6.71875-15-15-15h-80.335938c-8.28125 0-15 6.71875-15 15 0 8.285157 6.71875 15 15 15zm0 0
</sys:String>
</x:Array>
<x:Array x:Key="{x:Static mbts:Icons.DocumentStarGeometryKey}" Type="sys:String">
<sys:String>
m302.570312 260.257812-63.65625-14.878906-33.84375-55.992187c-2.71875-4.492188-7.585937-7.238281-12.835937-7.238281-5.253906 0-10.121094 2.746093-12.839844 7.238281l-33.84375 55.992187-63.65625 14.878906c-5.113281 1.191407-9.230469 4.976563-10.851562 9.96875-1.621094 4.996094-.515625 10.476563 2.917969 14.449219l42.777343 49.46875-5.566406 65.179688c-.445313 5.234375 1.878906 10.320312 6.128906 13.410156 4.246094 3.085937 9.800781 3.730469 14.644531 1.6875l60.289063-25.410156 60.285156 25.410156c1.640625.691406 8.199219 2.996094 14.648438-1.6875 4.25-3.089844 6.570312-8.175781 6.125-13.410156l-5.566407-65.179688 42.777344-49.46875c3.433594-3.976562 4.542969-9.453125 2.917969-14.449219-1.621094-4.992187-5.738281-8.777343-10.851563-9.96875zm-61.675781 59.050782c-2.644531 3.058594-3.941406 7.058594-3.597656 11.085937l3.988281 46.738281-43.226562-18.222656c-2.167969-.914062-6.621094-2.121094-11.652344 0l-43.230469 18.222656 3.992188-46.738281c.34375-4.027343-.953125-8.027343-3.597657-11.085937l-30.6875-35.488282 45.648438-10.667968c3.933594-.917969 7.332031-3.386719 9.421875-6.84375l24.28125-40.164063 24.277344 40.164063c2.089843 3.457031 5.484375 5.925781 9.421875 6.84375l45.644531 10.667968zm0 0
</sys:String>
<sys:String>
m336.832031 0h-224.933593c-3.976563 0-7.792969 1.582031-10.605469 4.394531l-96.398438 96.398438c-2.8125 2.8125-4.394531 6.628906-4.394531 10.605469v353.46875c0 25.988281 21.144531 47.132812 47.132812 47.132812h289.199219c25.914063 0 47.132813-20.953125 47.132813-47.132812v-417.734376c0-25.914062-20.949219-47.132812-47.132813-47.132812zm-223.867187 35.144531v60.1875c0 9.449219-7.683594 17.132813-17.132813 17.132813h-60.1875zm241 429.722657c0 9.332031-7.542969 17.132812-17.132813 17.132812h-289.199219c-9.445312 0-17.132812-7.6875-17.132812-17.132812v-322.398438h65.332031c25.988281 0 47.132813-21.144531 47.132813-47.132812v-65.335938h193.867187c9.332031 0 17.132813 7.546875 17.132813 17.132812zm0 0
</sys:String>
</x:Array>
<x:Array Type="sys:String" x:Key="{x:Static mbts:Icons.DiskFileGeometryKey}">
<sys:String>
m507.605469 309.660156-48.199219-48.199218c-2.8125-2.8125-6.628906-4.394532-10.605469-4.394532h-65.332031v-209.933594c0-25.988281-21.148438-47.132812-47.136719-47.132812h-224.933593c-3.976563 0-7.792969 1.578125-10.605469 4.394531l-96.398438 96.398438c-2.816406 2.8125-4.394531 6.628906-4.394531 10.605469v353.46875c0 12.597656 4.90625 24.4375 13.808594 33.328124 8.902344 8.902344 20.738281 13.804688 33.324218 13.804688h449.867188c8.285156 0 15-6.714844 15-15v-176.734375c0-3.976563-1.578125-7.792969-4.394531-10.605469zm-172.339844-22.59375h82.46875v34.269532h-82.46875zm-222.796875-251.921875v60.1875c0 9.449219-7.6875 17.132813-17.136719 17.132813h-60.1875zm-77.453125 441.832031c-3.234375-3.230468-5.015625-7.53125-5.015625-12.109374v-322.398438h65.332031c25.988281 0 47.136719-21.144531 47.136719-47.132812v-65.335938h193.863281c9.449219 0 17.136719 7.6875 17.136719 17.132812v209.933594h-97.46875c-8.285156 0-15 6.714844-15 15v209.933594h-193.867188c-4.574218 0-8.875-1.78125-12.117187-5.023438zm300.25 5.023438v-66.398438h82.46875v66.398438zm146.734375 0h-34.265625v-81.398438c0-8.285156-6.71875-15-15-15h-112.46875c-8.28125 0-15 6.714844-15 15v81.398438h-34.265625v-194.933594h34.265625v49.269532c0 8.28125 6.71875 15 15 15h112.46875c8.285156 0 15-6.71875 15-15v-44.121094l34.265625 34.265625zm0 0
</sys:String>
<sys:String>
m384.53125 433.800781h-16.0625c-8.285156 0-15 6.714844-15 15 0 8.285157 6.714844 15 15 15h16.0625c8.285156 0 15-6.714843 15-15 0-8.285156-6.714844-15-15-15zm0 0
</sys:String>
<sys:String>
m95.332031 222.800781h192.800781c8.285157 0 15-6.714843 15-15 0-8.285156-6.714843-15-15-15h-192.800781c-8.28125 0-15 6.714844-15 15 0 8.285157 6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m95.332031 287.066406h96.402344c8.28125 0 15-6.714844 15-15s-6.71875-15-15-15h-96.402344c-8.28125 0-15 6.714844-15 15s6.71875 15 15 15zm0 0
</sys:String>
<sys:String>
m191.734375 321.332031h-96.402344c-8.28125 0-15 6.71875-15 15 0 8.285157 6.71875 15 15 15h96.402344c8.28125 0 15-6.714843 15-15 0-8.28125-6.714844-15-15-15zm0 0
</sys:String>
<sys:String>
m191.734375 385.601562h-96.402344c-8.28125 0-15 6.714844-15 15 0 8.28125 6.71875 15 15 15h96.402344c8.28125 0 15-6.71875 15-15 0-8.285156-6.714844-15-15-15zm0 0
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/smashicons
Ttile: File free icon
Credit: Icon made by Smashicons from www.flaticon.com-->
<!--<x:Array x:Key="{x:Static MemberType={mbts:Nested mbts:Icons.Smashicons}, Member=EditDocumentGeometryKey}" Type="sys:String">-->
<x:Array x:Key="Smashicons.EditDocument.GeometryKey" Type="sys:String">
<sys:String>
M36.719,22h-25c-0.552,0-1,0.448-1,1s0.448,1,1,1h25c0.552,0,1-0.448,1-1S37.271,22,36.719,22z
</sys:String>
<sys:String>
M11.719,16h10c0.552,0,1-0.448,1-1s-0.448-1-1-1h-10c-0.552,0-1,0.448-1,1S11.167,16,11.719,16z
</sys:String>
<sys:String>
M36.719,30h-25c-0.552,0-1,0.448-1,1s0.448,1,1,1h25c0.552,0,1-0.448,1-1S37.271,30,36.719,30z
</sys:String>
<sys:String>
M28.719,38h-17c-0.552,0-1,0.448-1,1s0.448,1,1,1h17c0.552,0,1-0.448,1-1S29.271,38,28.719,38z
</sys:String>
<sys:String>
M25.719,48c0.552,0,1-0.448,1-1s-0.448-1-1-1h-14c-0.552,0-1,0.448-1,1s0.448,1,1,1H25.719z
</sys:String>
<sys:String>
M2.719,2h29v14h14v18h2V14.586L33.133,0H0.719v60h29v-2h-27V2z M33.719,3.414L44.305,14H33.719V3.414z
</sys:String>
<!--Pencil-->
<sys:String>
M58.407,37.162l-2.849-2.85c-1.128-1.128-3.094-1.128-4.222,0l-15.391,15.39l-2.121,7.779L33.305,58
c-0.388,0.388-0.389,1.014-0.006,1.405l-0.005,0.02l0.02-0.005c0.194,0.19,0.446,0.287,0.698,0.287
c0.256,0,0.512-0.098,0.707-0.293l0.519-0.519l7.779-2.121l15.39-15.391c0.564-0.564,0.875-1.313,0.875-2.111
S58.971,37.725,58.407,37.162z M38.254,50.222l10.243-10.243l4.243,4.243L42.497,54.465L38.254,50.222z M37.351,52.147l3.22,3.22
l-4.427,1.207L37.351,52.147z M56.993,39.969l-2.839,2.839l-4.243-4.243l2.839-2.839c0.372-0.372,1.021-0.373,1.393,0l2.85,2.85
c0.186,0.186,0.289,0.433,0.289,0.696C57.281,39.535,57.179,39.783,56.993,39.969z
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: File free icon
Credit: Icon made by Freepik from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.EditDocumentGeometryKey}" Type="sys:String">
<sys:String>
m336.332031 0h-224.933593c-3.976563 0-7.792969 1.582031-10.605469 4.394531l-96.398438 96.398438c-2.8125 2.8125-4.394531 6.628906-4.394531 10.605469v353.46875c0 25.988281 21.144531 47.132812 47.132812 47.132812h289.199219c12.597657 0 24.4375-4.90625 33.328125-13.808594 8.902344-8.898437 13.804688-20.734375 13.804688-33.324218v-417.734376c0-12.589843-4.902344-24.425781-13.796875-33.320312-8.898438-8.90625-20.738281-13.8125-33.335938-13.8125zm-223.863281 35.144531v60.1875c0 9.449219-7.6875 17.132813-17.132812 17.132813h-60.191407zm241 429.722657c0 4.574218-1.785156 8.875-5.027344 12.117187-3.230468 3.234375-7.53125 5.015625-12.105468 5.015625h-289.203126c-9.445312 0-17.132812-7.6875-17.132812-17.132812v-322.398438h65.332031c25.988281 0 47.132813-21.144531 47.132813-47.132812v-65.335938h193.867187c4.578125 0 8.878907 1.78125 12.117188 5.023438 3.234375 3.234374 5.015625 7.535156 5.015625 12.109374v417.734376zm0 0
</sys:String>
<sys:String>
m288.132812 192.800781h-192.800781c-8.28125 0-15 6.714844-15 15 0 8.285157 6.71875 15 15 15h192.800781c8.285157 0 15-6.714843 15-15 0-8.285156-6.714843-15-15-15zm0 0
</sys:String>
<sys:String>
m288.132812 257.066406h-192.800781c-8.28125 0-15 6.714844-15 15s6.71875 15 15 15h192.800781c8.285157 0 15-6.714844 15-15s-6.714843-15-15-15zm0 0
</sys:String>
<sys:String>
m288.132812 321.332031h-192.800781c-8.28125 0-15 6.71875-15 15 0 8.285157 6.71875 15 15 15h192.800781c8.285157 0 15-6.714843 15-15 0-8.28125-6.714843-15-15-15zm0 0
</sys:String>
<sys:String>
m191.734375 385.601562h-96.402344c-8.28125 0-15 6.714844-15 15 0 8.28125 6.71875 15 15 15h96.402344c8.28125 0 15-6.71875 15-15 0-8.285156-6.714844-15-15-15zm0 0
</sys:String>
<sys:String>
m464.867188 0c-25.988282 0-47.132813 21.144531-47.132813 47.132812v313.75c0 49.324219 11.660156 98.710938 33.71875 142.824219 2.539063 5.082031 7.734375 8.292969 13.414063 8.292969 5.683593 0 10.875-3.210938 13.417968-8.292969 22.054688-44.113281 33.714844-93.503906 33.714844-142.824219v-313.75c0-25.988281-21.144531-47.132812-47.132812-47.132812zm0 30c9.445312 0 17.132812 7.6875 17.132812 17.132812v33.199219h-34.265625v-33.199219c0-9.445312 7.683594-17.132812 17.132813-17.132812zm17.132812 323.46875h-34.265625v-243.136719h34.265625zm-17.132812 105.4375c-8.71875-24.277344-14.1875-49.734375-16.222657-75.4375h32.445313c-2.035156 25.707031-7.507813 51.160156-16.222656 75.4375zm0 0
</sys:String>
</x:Array>
<sys:String x:Key="{x:Static mbts:Icons.CheckMarkGeometryKey}">
F1M9.97498,1.22334L4.6983,9.09834 4.52164,9.09834 0,5.19331 1.27664,3.52165 4.255,6.08833 8.33331,1.52588E-05 9.97498,1.22334z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.GearGeometryKey}">
M16.000015,9.6000061C12.500012,9.6000061 9.5999844,12.5 9.5999844,16 9.5999844,19.5 12.500012,22.399994 16.000015,22.399994 19.500019,22.399994 22.400015,19.5 22.400015,16 22.400015,12.5 19.500019,9.6000061 16.000015,9.6000061z M14.199995,0L17.800005,0C18.199999,0,18.599993,0.29998779,18.599993,0.79998779L18.599993,4.7999878C19.900013,5.1000061,21.000019,5.6000061,22.099997,6.2999878L25.000023,3.3999939C25.099999,3.2999878 25.300011,3.1999817 25.500025,3.1999817 25.700007,3.1999817 25.900019,3.2999878 26.000025,3.3999939L28.600033,6C28.900021,6.2999878,28.900021,6.7999878,28.600033,7.1000061L25.700007,10C26.400019,11.100006,26.900019,12.299988,27.200007,13.5L31.20001,13.5C31.600037,13.5,31.999998,13.799988,31.999998,14.299988L31.999998,17.899994C31.999998,18.299988,31.700012,18.699982,31.20001,18.699982L27.200007,18.699982C26.900019,20,26.400019,21.100006,25.700007,22.199982L28.600033,25.100006C28.700009,25.199982 28.799984,25.399994 28.799984,25.600006 28.799984,25.799988 28.700009,26 28.600033,26.100006L26.000025,28.600006C25.900019,28.699982 25.700007,28.799988 25.500025,28.799988 25.300011,28.799988 25.099999,28.699982 25.000023,28.600006L22.099997,25.699982C21.000019,26.399994,19.800007,26.899994,18.599993,27.199982L18.599993,31.199982C18.599993,31.600006,18.300005,32,17.800005,32L14.199995,32C13.8,32,13.400006,31.699982,13.400006,31.199982L13.400006,27.199982C12.099987,26.899994,11.000011,26.399994,9.9000027,25.699982L7.0000064,28.600006C6.9000003,28.699982 6.6999881,28.799988 6.5000059,28.799988 6.2999937,28.799988 6.099981,28.699982 6.0000054,28.600006L3.3999967,26C3.0999784,25.699982,3.0999784,25.199982,3.3999967,24.899994L6.2999937,22C5.5999805,20.899994,5.0999801,19.699982,4.7999923,18.5L0.79998828,18.5C0.39999409,18.5,-1.933513E-07,18.199982,0,17.699982L0,14.100006C-1.933513E-07,13.699982,0.2999879,13.299988,0.79998828,13.299988L4.7999923,13.299988C5.0999801,12,5.5999805,10.899994,6.2999937,9.7999878L3.3999967,7C3.2999908,6.8999939 3.1999845,6.6999817 3.1999845,6.5 3.1999845,6.2999878 3.2999908,6.1000061 3.3999967,6L6.0000054,3.3999939C6.099981,3.2999878 6.2999937,3.1999817 6.5000059,3.1999817 6.6999881,3.1999817 6.9000003,3.2999878 7.0000064,3.3999939L9.9000027,6.2999878C11.000011,5.6000061,12.199993,5.1000061,13.400006,4.7999878L13.400006,0.79998779C13.400006,0.29998779,13.8,0,14.199995,0z
</sys:String>
@@ -17,15 +252,69 @@
M28.000001,6.0000026L28.000001,15 6.0010006,15 6.0010006,17.000003 30.001,17.000003 30.001,6.0000026z M14.231,2.9540056L14.979999,2.9540056 14.979999,3.987005C15.704998,4.009005,16.200997,4.178005,16.550998,4.3600049L16.248998,5.0620046C15.994998,4.9340047 15.499998,4.7010047 14.725999,4.7010047 13.796,4.7010047 13.445001,5.1900046 13.445001,5.6160046 13.445001,6.1710043 13.893,6.4470041 14.943999,6.8310037 16.187998,7.2780037 16.816998,7.8320036 16.816998,8.7800031 16.816998,9.6210027 16.151998,10.409003 14.907999,10.591002L14.907999,11.698002 14.146,11.698002 14.146,10.622003C13.445001,10.611002,12.720001,10.420002,12.297002,10.154003L12.587001,9.4400029C13.022001,9.696003 13.651,9.8980026 14.328,9.8980026 15.185999,9.8980026 15.765998,9.4620028 15.765998,8.8540034 15.765998,8.2680035 15.293999,7.9060035 14.4,7.5870035 13.167001,7.1610038 12.406001,6.6710041 12.406001,5.7440041 12.406001,4.8600047 13.119,4.189005 14.231,4.0290052z M2,2.0000002L2,13 26.000001,13 26.000001,2.0000002z M0,0L28.000001,0 28.000001,4.0000031 32.001,4.0000031 32.001,19.000003 4.0010006,19.000003 4.0010006,15 0,15z
</sys:String>
<!--Pencil (the icon is free to use if we include this information in our credit/about section)
Source: https://www.flaticon.com/authors/gregor-cresnar
Ttile: Pencil free icon
Credit: Icon made by Gregor Cresnar from www.flaticon.com-->
<sys:String x:Key="{x:Static mbts:Icons.PencilGeometryKey}">
M170.5,395.3c0,2.2,0.7,4.3,2,6l64.4,84.4c1.9,2.5,4.8,3.9,7.9,3.9c3.1,0,6-1.4,7.9-3.9l64.4-84.4
c1.3-1.7,2-3.8,2-6V124.2c0-5.5-4.4-9.9-9.9-9.9s-9.9,4.4-9.9,9.9V392l-54.5,71.4L190.3,392V124.7c0-5.5-4.4-9.9-9.9-9.9
s-9.9,4.4-9.9,9.9L170.5,395.3L170.5,395.3z
M234.9,124.7v249c0,5.5,4.4,9.9,9.9,9.9s9.9-4.4,9.9-9.9v-249c0-5.5-4.4-9.9-9.9-9.9
S234.9,119.2,234.9,124.7z
M170.5,38.9v44.3c0,5.5,4.4,9.9,9.9,9.9h128.7c5.5,0,9.9-4.4,9.9-9.9V38.9
C319,17.5,301.6,0,280.1,0h-70.7C188,0,170.5,17.4,170.5,38.9z M299.3,38.9v34.4h-109V38.9c0-10.5,8.6-19.1,19.1-19.1h70.7
C290.7,19.8,299.3,28.3,299.3,38.9z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.PlayGeometryKey}">
M0,0L25.194,16 0,32z
</sys:String>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/smashicons
Ttile: File free icon
Credit: Icon made by Smashicons from www.flaticon.com-->
<!--<x:Array x:Key="{x:Static MemberType={mbts:Nested mbts:Icons.Smashicons}, Member=SaveGeometryKey}" Type="sys:String">-->
<x:Array x:Key="Smashicons.Save.GeometryKey" Type="sys:String">
<sys:String>
M39.914,0H37.5h-28h-9v49h7h33h8V8.586L39.914,0z M35.5,2v14h-24V2H35.5z M9.5,47V28h29v19H9.5z M46.5,47h-6V26h-33v21h-5 V2h7v16h28V2h1.586L46.5,9.414V47z
</sys:String>
<sys:String>
M13.5,33h7c0.553,0,1-0.447,1-1s-0.447-1-1-1h-7c-0.553,0-1,0.447-1,1S12.947,33,13.5,33z
</sys:String>
<sys:String>
M23.5,35h-10c-0.553,0-1,0.447-1,1s0.447,1,1,1h10c0.553,0,1-0.447,1-1S24.053,35,23.5,35z
</sys:String>
<sys:String>
M25.79,35.29c-0.181,0.189-0.29,0.45-0.29,0.71s0.109,0.52,0.29,0.71C25.979,36.89,26.229,37,26.5,37 c0.26,0,0.52-0.11,0.71-0.29c0.18-0.19,0.29-0.45,0.29-0.71s-0.11-0.521-0.29-0.71C26.84,34.92,26.16,34.92,25.79,35.29z
</sys:String>
<sys:String>
M33.5,4h-6v10h6V4z M31.5,12h-2V6h2V12z
</sys:String>
</x:Array>
<sys:String x:Key="{x:Static mbts:Icons.StarGeometryKey}">
M1540.22,2082.07L1546.95,2102.78 1568.73,2102.78 1551.11,2115.58 1557.84,2136.29 1540.22,2123.49 1522.6,2136.29 1529.33,2115.58 1511.71,2102.78 1533.49,2102.78 1540.22,2082.07z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.ToolsGeometryKey}">
M4.9629898,25.440168C4.564003,25.440168 4.0650101,25.640182 3.7659989,25.939165 3.0680008,26.638176 3.0680008,27.635191 3.7659989,28.3342 4.4639969,29.032204 5.4620133,29.032204 6.1600113,28.3342 6.8589859,27.635191 6.8589859,26.638176 6.1600113,25.939165 5.760994,25.640182 5.3620072,25.440168 4.9629898,25.440168z M18.432014,18.457121L22.422005,22.447138 24.816994,22.946165 29.107002,29.431192 27.509987,31.027212 21.025002,26.737175 20.526985,24.343178 16.535988,20.352123z M8.1560135,18.357115L13.643013,23.84415C11.048988,26.638176 8.9539872,28.932196 7.9560013,29.930189 6.359993,31.526207 3.6659928,31.626215 2.070015,29.930189 0.47400668,28.3342 0.47400668,25.640182 2.070015,24.044165z M2.967995,6.7840408C2.768013,6.7840408 2.5690079,6.8840479 2.4690018,6.9840545 2.1699906,7.2830371 2.1699906,7.7820638 2.4690018,8.0810469L11.746986,17.359123C12.047005,17.659113 12.544991,17.659113 12.845009,17.359123 13.14399,17.06011 13.14399,16.561113 12.845009,16.2621L3.5659867,6.9840545C3.3670121,6.8840479,3.1669998,6.7840408,2.967995,6.7840408z M5.2620011,4.4890431C5.0629959,4.4890431 4.8630143,4.5890192 4.7640152,4.6890262 4.3649979,4.9880394 4.3649979,5.4870356 4.7640152,5.8860554L14.042,15.164101C14.341011,15.46409 14.840004,15.46409 15.139015,15.164101 15.439003,14.865087 15.439003,14.366092 15.139015,14.067109L5.8610001,4.6890262C5.661995,4.5890192,5.4620133,4.4890431,5.2620011,4.4890431z M4.3649979,2.3940283C5.4620133,2.3940281,6.5589981,2.7930175,7.3580094,3.5920337L19.328987,15.46409 13.342995,21.450153 1.2720107,9.6770657C-0.42400357,7.9810704 -0.42400357,5.2880291 1.2720107,3.6910337 2.1699906,2.7930175 3.267006,2.3940281 4.3649979,2.3940283z M24.217995,0C25.31501,-8.5992724E-08,26.312996,0.20001344,27.211006,0.59900296L23.021004,4.7890328C22.223,5.5870422,22.223,6.7840408,23.021004,7.4820436L24.617012,9.079069C25.414986,9.8770789,26.612007,9.8770789,27.311012,9.079069L31.501015,4.9880394C31.799995,5.8860554 32.000008,6.7840408 32.000008,7.7820638 32.000008,12.07207 28.508003,15.564097 24.217995,15.564097 19.927986,15.564097 16.436012,12.07207 16.436012,7.7820638 16.436012,3.4920272 19.927986,-8.5992724E-08 24.217995,0z
</sys:String>
<!--
<sys:String x:Key="{x:Static mbts:Icons.TrashGeometryKey}">
M0,12.568994L23.662999,12.568994 20.910989,31.999999 2.7520113,31.999999z M8.0689915,1.6269979L8.0689915,4.6679968 15.594984,4.6679968 15.594984,1.6269979z M6.4420097,0L17.221997,0 17.221997,4.6679968 23.662999,4.6679968 23.662999,8.7949938 0,8.7949938 0,4.6679968 6.4420097,4.6679968z
</sys:String>
<!--UndoCircular (the icon is free to use if we include this information in our credit/about section)
Source: https://www.flaticon.com/authors/google
Ttile: Undo button free icon
Credit: Icon made by Google from www.flaticon.com-->
<sys:String x:Key="{x:Static mbts:Icons.UndoCircularGeometryKey}">
M248.625,89.25V0l-127.5,127.5l127.5,127.5V140.25c84.15,0,153,68.85,153,153c0,84.15-68.85,153-153,153
c-84.15,0-153-68.85-153-153h-51c0,112.2,91.8,204,204,204s204-91.8,204-204S360.825,89.25,248.625,89.25z
</sys:String>
<!--
'y' for equilateral triangle of side length x:
(x/2)^2 + Y^2 = x^2
Y^2 = x^2 - (x^2)/4
@@ -48,7 +337,7 @@
</sys:String>
<Geometry x:Key="arrow_geometry">
F1 M 78.1398,324.18L 52.5865,298.626C 51.6892,297.728 50.3385,297.459 49.1678,297.946C 47.9971,298.43 47.2305,299.574 47.2305,300.843L 60.6385,326.398L 47.2305,351.952C 47.2305,353.223 47.9971,354.364 49.1678,354.848C 49.5558,355.011 49.9638,355.09 50.3678,355.09C 51.1838,355.09 51.9852,354.77 52.5865,354.171L 78.1398,328.616C 78.7238,328.032 79.0598,327.224 79.0598,326.398C 79.0598,325.572 78.7238,324.764 78.1398,324.18 Z
F1 M 78.1398,324.18L 52.5865,298.626C 51.6892,297.728 50.3385,297.459 49.1678,297.946C 47.9971,298.43 47.2305,299.574 47.2305,300.843L 60.6385,326.398L 47.2305,351.952C 47.2305,353.223 47.9971,354.364 49.1678,354.848C 49.5558,355.011 49.9638,355.09 50.3678,355.09C 51.1838,355.09 51.9852,354.77 52.5865,354.171L 78.1398,328.616C 78.7238,328.032 79.0598,327.224 79.0598,326.398C 79.0598,325.572 78.7238,324.764 78.1398,324.18 Z
</Geometry>
<DrawingImage x:Key="Bookmarks">
@@ -106,34 +395,6 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z">
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="Trash">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Black" Geometry="M33.978,27.679999L33.978,58.098995 41.374,58.098995 41.374,27.679999z M14.841001,27.679999L14.841001,58.098995 22.237,58.098995 22.237,27.679999z M4.0320003,22.430001L52.183002,22.430001 52.183002,63.995998 4.0320003,63.995998z M15.974001,0L40.194999,0 40.194999,7.7200003 56.166999,7.7200003 56.166999,15.995 0,15.995 0,7.7200003 15.974001,7.7200003z">
<!--<GeometryDrawing.Pen>
<Pen Thickness="1" Brush="Black" />
</GeometryDrawing.Pen>-->
</GeometryDrawing>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="Trash2">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Transparent" Geometry="M0,12.568994L23.662999,12.568994 20.910989,31.999999 2.7520113,31.999999z M8.0689915,1.6269979L8.0689915,4.6679968 15.594984,4.6679968 15.594984,1.6269979z M6.4420097,0L17.221997,0 17.221997,4.6679968 23.662999,4.6679968 23.662999,8.7949938 0,8.7949938 0,4.6679968 6.4420097,4.6679968z">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="2"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="Undo">
<DrawingImage.Drawing>
<DrawingGroup>
@@ -795,7 +1056,7 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z">
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="DownArrow" x:Shared="False">
<DrawingImage.Drawing>
<DrawingGroup>
@@ -9,7 +9,7 @@ namespace mbts.spark {
[Export]
class MarketDataAuxiliaryModel : IDisposable {
readonly MarketDataAuxiliaryService _service;
readonly TableUpdateDemuxer<VolumeAtPriceLevelImmutable, int, uint> _security_orders_demuxer;
readonly LegacyTableUpdateDemuxer<VolumeAtPriceLevelImmutable, int, uint> _security_orders_demuxer;
IDisposable _dispose;
[ImportingConstructor]
@@ -18,7 +18,7 @@ namespace mbts.spark {
var scheduler = ThreadPoolScheduler.Instance;
var interval = TimeSpan.FromMilliseconds(100);
volume_at_price = service.subscribei_volume_at_price().Naggle(interval, scheduler).Table().Cache();
_security_orders_demuxer = new TableUpdateDemuxer<VolumeAtPriceLevelImmutable, int, uint>(o => o.RecordId, v => v.SecurityId);
_security_orders_demuxer = new LegacyTableUpdateDemuxer<VolumeAtPriceLevelImmutable, int, uint>(o => o.RecordId, v => v.SecurityId);
_dispose = volume_at_price.AddRemoveOnly().Subscribe(_security_orders_demuxer);
}
@@ -255,14 +255,15 @@ namespace mbts.ui.spark {
}
protected override void OnRender(DrawingContext drawing_context) {
if (_vm == null) return;
const double y_offset = 10;
string leg_count_msg = _vm.GetErrors(nameof(SyntheticEditorVM.leg_count)).Cast<string>().FirstOrDefault();
if (leg_count_msg != null) {
this.draw_relative_text(RelativePosition.Below, leg_count_msg, drawing_context, _name_text_box.value, new SolidColorBrush(BTSColors.MarketData.driver_background), 0, y_offset);
} else {
if (_vm != null && _vm.GetErrors(nameof(SyntheticEditorVM.name)).Cast<string>().Any())
if (_vm.GetErrors(nameof(SyntheticEditorVM.name)).Cast<string>().Any())
this.draw_border(drawing_context, _name_text_box.value, null, new Pen(Brushes.Red, 1));
if (_vm != null && _vm.GetErrors(nameof(SyntheticEditorVM.tick_factors)).Cast<string>().Any())
if (_vm.GetErrors(nameof(SyntheticEditorVM.tick_factors)).Cast<string>().Any())
this.draw_border(drawing_context, _tick_factors_picker.value, null, new Pen(Brushes.Red, 1));
string error_text = string.Join(", ", _vm.AllErrors);
this.draw_relative_text(RelativePosition.Below, error_text, drawing_context, _name_text_box.value, BTSColors.header_error_text_brush, 0, y_offset);
+20 -9
View File
@@ -1,13 +1,12 @@
using bts.api;
using bts.utils;
using mbts.collections;
using mbts.ui.controls;
using mbts.ui.spark;
using mbts.utils;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Disposables;
using System.Windows;
namespace mbts.spark {
@@ -20,8 +19,9 @@ namespace mbts.spark {
}
internal class RowVM : DataGridExRow<Security>, IParameterRowVM, IDisposable {
readonly ObservantDictionary<Security, ICell, LegSpreaderParamsTuple> _cells;
readonly ObservableKeyedCollection<KeyValuePair<uint, (ICell cell, LegSpreaderParamsTuple leg)>, uint> _cells = new ObservableKeyedCollection<KeyValuePair<uint, (ICell cell, LegSpreaderParamsTuple leg)>, uint>(kv => kv.Key);
readonly Property<bool> _has_errors;
IDisposable _dispose;
public RowVM(IRowModel model, ObservableCollection<LegSpreaderParamsTuple> legs) {
display_name = model.display_name;
@@ -32,11 +32,22 @@ namespace mbts.spark {
read_only = model.read_only;
font_weight = model is IHaveFontParams fps ? fps.font_weight : FontWeights.Normal;
_has_errors = backing(nameof(has_errors), false);
_cells = ObservantDictionary.Create(legs, l => l.leg.Security, model.create_cell, EqualityComparer.Create<Security, uint>(s => s.Id));
_cells.ValueDestroyed += c => (c as IDisposable)?.Dispose();
foreach (var c in _cells.Values) c.value_changed += () => _has_errors.set(model.has_errors(legs));
_dispose = Disposable.Create(
ObservableAutoWrapper.connect(legs, _cells, lt => new KeyValuePair<uint, (ICell cell, LegSpreaderParamsTuple leg)>(lt.SecurityKey, (model.create_cell(lt), lt))),
ObservableAutoWrapper.connect_item_hooks(_cells, kv => {
kv.Value.cell.value_changed += raise_cell_value_changed;
return new CompositeDisposable {
Disposable.Create(() => kv.Value.cell.value_changed -= raise_cell_value_changed),
kv.Value.cell as IDisposable ?? Disposable.empty
};
void raise_cell_value_changed() =>
cell_value_changed?.Invoke(kv.Value.cell, kv.Value.leg);
}, true));
}
public event Action<ICell, LegSpreaderParamsTuple> cell_value_changed;
public string display_name { get; }
public string help_text { get; }
public FontWeight font_weight { get; }
@@ -46,13 +57,13 @@ namespace mbts.spark {
public bool has_errors => _has_errors.Value;
public override object get_cell(Security col_key) =>
_cells.TryGetValue(col_key, out ICell value) ? value : null;
_cells.TryGetValue(col_key.Id, out KeyValuePair<uint, (ICell cell, LegSpreaderParamsTuple leg)> kv) ? kv.Value.cell : null;
public ParameterSection this[string section_no] =>
int.TryParse(section_no, out int i) && i < section_path.Length ? section_path[i] : null;
public void Dispose() =>
_cells.Values.OfType<IDisposable>().DisposeAll();
Disposable.dispose(ref _dispose);
}
}
}
@@ -235,11 +235,27 @@ namespace mbts.spark {
post_hedge_opposite_market_based_cross_cross_ticks
}.Select(m => new RowVM(m, leg_tuples)).ToList();
set_synthetic(synthetic, strategy);
var strategy_publisher = Observable.Create<ExecutionStrategyImmutable>(o => {
o.OnNext(get_strategy());
foreach (var r in rows)
r.cell_value_changed += on_cell_value_changed;
return Disposable.Create(() => {
foreach (var r in rows)
r.cell_value_changed -= on_cell_value_changed;
});
void on_cell_value_changed(ICell cell, LegSpreaderParamsTuple leg) =>
o.OnNext(get_strategy());
}).DistinctUntilChanged()
.Publish();
strategy_observable = strategy_publisher;
_resources.Add(strategy_publisher.Connect());
}
public event EventHandler RequestClose;
public event Action RequestUpdate;
public IObservable<ExecutionStrategyImmutable> strategy_observable { get; }
public string title { get; }
public ImageSource icon { get; }
public string name {
@@ -0,0 +1,112 @@
using bts.api.core;
using bts.collections;
using mbts.collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace mbts.spark {
/// <summary>
/// This class's primary purpose is to handle async AlgoService persistence calls for the AlgoStudioVM/OrderPropertiesEditorVM.
/// When a new definition/template item is persisted for the first time, it's corresponding viewmodel (<see cref="AlgoDefinitionVM"/>, <see cref="AlgoDefinitionTemplateVM"/>)
/// must be removed and replaced with a new one that has the brand new persisted id (<see cref="AlgoKey"/>). As part of its duty, this class makes sure that the new persisted items are inserted into the same index as their unpersisted predecessor.
/// </summary>
static class AlgoPersistenceHelper {
public static (int? def_index, int? tmp_index) selection_snapshot(IList<AlgoDefinitionVM> definitions, AlgoDefinitionVM selected_definition, AlgoDefinitionTemplateVM selected_template) {
var def = selected_definition;
var tmp = selected_template;
int? def_index = def == null ? (int?)null : definitions.IndexOf(def);
int? tmp_index = tmp == null ? (int?)null : tmp.owner.templates.IndexOf(tmp);
return (def_index, tmp_index);
}
public static async Task<IReadOnlyDictionary<AlgoKey, AlgoKey>> persist_definition(OrdersModel model, IList<AlgoDefinitionVM> definitions, AlgoDefinitionVM definition) {
int def_index = definitions.IndexOf(definition);
return await persist(model, definitions.WrapSubRange(def_index, 1).WrapSelector(def => (def, definition.templates.AsList()), t => t.def));
}
public static async Task<IReadOnlyDictionary<AlgoKey, AlgoKey>> persist_template(OrdersModel model, IList<AlgoDefinitionVM> definitions, AlgoDefinitionTemplateVM template) {
switch (template.owner.key.mode) {
case AlgoKey.Mode.Unpersisted: return await persist_definition(model, definitions, template.owner);
case AlgoKey.Mode.Persisted:
int def_index = definitions.IndexOf(template.owner);
int tmp_index = template.owner.templates.IndexOf(template);
return await persist(model, definitions.WrapSubRange(def_index, 1).WrapSelector(def => (def, def.templates.WrapSubRange(tmp_index, 1)), t => t.def));
default: return DictionaryHelper.empty<AlgoKey, AlgoKey>();
}
}
public static async Task<IReadOnlyDictionary<AlgoKey, AlgoKey>> persist_all(OrdersModel model, ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey> definitions) =>
await persist(model, definitions.WrapSelector(def => (def, def.templates.AsList()), t => t.def));
/// <summary>
/// Persists each pair of definition/templates, then returns a map of non-persisted keys to persisted ones (<see cref="AlgoKey"/>, <see cref="AlgoDefinitionVM.key"/>, <see cref="AlgoDefinitionTemplateVM.key"/>).
/// The key-map gives callers the ability to replace unpersisted items with persisted ones before the next update arrives.
/// <para>Note: use a <see cref="mbts.utils.TableUpdateBuffer{T, TKey}"/> to suspend updates while awaiting this task; don't resume them until all unpersisted items have been replaced.
/// <see cref="AlgoDefinitionCollection"/> caters to this pre-emptive adding behavior, in it's <see cref="TableUpdate{T, TKey}"/> callback, it checks if added items are already present, and if so, treats them as changes instead.</para>
/// <para>PS: the reason for all this madness is so newly persisted items are inserted in the same index as their placeholder counterpart. The only way to connect the non-persisted keys with their persisted counterparts
/// is to await each save-op individually, and build a map with the results..hence the returned key-map.</para>
/// </summary>
/// <param name="model"></param>
/// <param name="definition_templates"></param>
/// <returns>An AlgoKey->AlgoKey map of old placeholder ids to newly persisted ones.</returns>
public static async Task<IReadOnlyDictionary<AlgoKey, AlgoKey>> persist(OrdersModel model, IList<(AlgoDefinitionVM definition, IList<AlgoDefinitionTemplateVM> templates)> definition_templates) {
var placeholder_to_persisted_keys = new Dictionary<AlgoKey, AlgoKey>();
for (int i = 0; i < definition_templates.Count; i++) {
(var def, var templates) = definition_templates[i];
var persisted_def = def;
if (def.is_dirty) {
var def_record = await model.algo_model.save_definition(def.create_algo_def());
if (def_record.HasValue) {
switch (def.key.mode) {
case AlgoKey.Mode.Factory:
case AlgoKey.Mode.Unpersisted:
persisted_def = def.to_persisted(def_record.Value);
foreach (var tmp in templates) {
AlgoDefinitionTemplateVM persisted_tmp;
var tmp_record = await model.algo_model.save_template(tmp.create(def_record.Value));
if (tmp_record.HasValue) {
persisted_def.templates.Add(persisted_tmp = tmp.to_persisted(persisted_def, new AlgoData(tmp_record.Value.value, tmp_record.Value.name, tmp_record.Value.key)));
} else {
/// If the save-op fails, the unpersisted template is cloned and added to the persisted def's template items, so the user may try to save it again without having to re-enter all the templated-values.
/// Q: "why don't we just re-add the same template to the persisted def, the save-op failed, so nothing changed...why do we need a new one?"
/// A: "A new template vm must be created because its owner has changed (it's a readonly prop, <see cref="AlgoDefinitionTemplateVM.owner"/>)."
persisted_def.templates.Add(persisted_tmp = new AlgoDefinitionTemplateVM(persisted_def, model, tmp.create_def_data()));
}
placeholder_to_persisted_keys[tmp.key] = persisted_tmp.key;
}
persisted_def.connect();
if (def.key.mode == AlgoKey.Mode.Unpersisted) {
definition_templates[i] = (persisted_def, persisted_def.templates);
} else {
definition_templates.Add((persisted_def, persisted_def.templates));
}
placeholder_to_persisted_keys[def.key] = persisted_def.key;
break;
}
}
} else {
// so the def isn't dirty, but it still might have dirty templates
using (persisted_def.buffer_updates()) {
for (int j = 0; j < templates.Count; j++) {
var tmp = templates[j];
if (!tmp.is_dirty)
continue;
var tmp_record = await model.algo_model.save_template(tmp.create());
if (tmp_record.HasValue) {
switch (tmp.key.mode) {
case AlgoKey.Mode.Unpersisted:
var persisted_tmp = tmp.to_persisted(persisted_def, new AlgoData(tmp_record.Value.value, tmp_record.Value.name, tmp_record.Value.key));
templates[j] = persisted_tmp;
placeholder_to_persisted_keys[tmp.key] = persisted_tmp.key;
break;
}
}
}
}
}
}
return placeholder_to_persisted_keys;
}
}
}
@@ -0,0 +1,643 @@
<UserControl
x:Class="mbts.ui.spark.AlgoStudioView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sp="clr-namespace:mbts.spark"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cp="clr-namespace:mbts.ui.controls.color_picker"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:uag="clr-namespace:mbts.ui.spark.algo"
xmlns:uspcv="clr-namespace:mbts.ui.spark.converters"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
u:StateManager.VisualState="{Binding content_source.algo_root, Converter={x:Static usp:AlgoStudioView.EditPaneVisualStateConverter}}"
Background="{StaticResource CommonBackground}"
>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Controls/Order/AlgoTemplateTreeView.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoPickerNodeView.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoContentTemplateSelector.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!--Primitive Constants-->
<sys:Double x:Key="HorizontalPush1">4</sys:Double>
<sys:Double x:Key="HorizontalPush2">8</sys:Double>
<sys:Double x:Key="HorizontalPush3">12</sys:Double>
<sys:Double x:Key="VerticalPush1">4</sys:Double>
<sys:Double x:Key="VerticalPush2">8</sys:Double>
<sys:Double x:Key="VerticalPush3">12</sys:Double>
<Thickness x:Key="Margin.LP1" Left="{StaticResource HorizontalPush1}"/>
<Thickness x:Key="Margin.LP2" Left="{StaticResource HorizontalPush2}"/>
<Thickness x:Key="Margin.LP3" Left="{StaticResource HorizontalPush3}"/>
<Thickness x:Key="Margin.TP1" Top="{StaticResource VerticalPush1}"/>
<Thickness x:Key="Margin.TP2" Top="{StaticResource VerticalPush2}"/>
<!--Converters-->
<cv:ValueMap x:Key="AlgoTemplateFavoriteToggleButtonToolTipConverter" Default="Add to Favorites">
<cv:KeyValue Key="{u:True}" Value="Remove from Favorites"/>
</cv:ValueMap>
<sys:String x:Key="AlgoAbbreviationActiveState">AbbreviationActive</sys:String>
<sys:String x:Key="AlgoAbbreviationInactiveState">AbbreviationInactive</sys:String>
<cv:ValueMap x:Key="AlgoAbbreviationVisualStateConverter" Default="{StaticResource AlgoAbbreviationActiveState}">
<cv:KeyValue Key="{x:Null}" Value="{StaticResource AlgoAbbreviationInactiveState}"/>
<cv:KeyValue Key="{x:Static sys:String.Empty}" Value="{StaticResource AlgoAbbreviationInactiveState}"/>
</cv:ValueMap>
<uspcv:OrderTypeBrushConverter x:Key="OrderTypeBrushConverter" DefaultBrush="Transparent"/>
<!--Default Styles-->
<Style x:Key="ContentHostGroupBoxStyle" TargetType="GroupBox">
<Setter Property="Padding" Value="8"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="u:TextBoxBehavior.EnterKeyBehavior" Value="CommitAndRelease"/>
<Setter Property="u:TextBoxBehavior.ReleaseOnEscape" Value="True"/>
</Style>
<!--Custom Styles-->
<Style x:Key="RectangleBadgeStyle" TargetType="Rectangle">
<Setter Property="Width" Value="17"/>
<Setter Property="Height" Value="12"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="RadiusX" Value="{x:Static c:Badge.DefaultCornerRadius}"/>
<Setter Property="RadiusY" Value="{x:Static c:Badge.DefaultCornerRadius}"/>
<Setter Property="Stroke" Value="Black"/>
<Setter Property="StrokeThickness" Value="2"/>
</Style>
<Style x:Key="CustomBadgeColorPickerPopupRootStyle" TargetType="Border">
<Setter Property="BorderBrush" Value="DarkGray"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Background" Value="{StaticResource CommonBackground}"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="MinWidth" Value="100"/>
<Setter Property="u:Behavior.EatMouseDown" Value="True"/>
</Style>
<Style x:Key="CustomBadgeColorPickerButtonStyle" TargetType="Button">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Width" Value="17"/>
<Setter Property="Height" Value="12"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="2"
Opacity="{TemplateBinding Opacity}"
Padding="{TemplateBinding Padding}"
>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
<DiscreteColorKeyFrame KeyTime="0" Value="#FF7EB4EA"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
<DiscreteColorKeyFrame KeyTime="0" Value="{StaticResource Button.MousePressed.BackgroundColor}"/>
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border">
<DiscreteColorKeyFrame KeyTime="0" Value="{StaticResource Button.MousePressed.BorderColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Border">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:Double 0.5}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="AlgoTemplateFavoriteToggleButtonStyle" TargetType="ToggleButton">
<Setter Property="Background" Value="LightGray"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="IsThreeState" Value="False"/>
<Setter Property="IsChecked" Value="{Binding is_favorite}"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="Width" Value="16"/>
<Setter Property="Height" Value="16"/>
<Setter Property="ToolTip" Value="{Binding IsChecked, RelativeSource={RelativeSource Self}, Converter={x:Static uag:AlgoTemplateToolBar.FavoriteToggleButtonToolTipConverter}}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Grid UseLayoutRounding="{TemplateBinding UseLayoutRounding}">
<Ellipse x:Name="ellipse" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="{TemplateBinding Background}" Width="0" Height="0"/>
<Image SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" UseLayoutRounding="{TemplateBinding UseLayoutRounding}" MaxHeight="13" MaxWidth="13">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Geometry="{Binding Source={StaticResource ResourceKey={x:Static u:Icons.StarGeometryKey}}}" Brush="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}" >
<GeometryDrawing.Pen>
<Pen
Brush="{Binding BorderBrush, RelativeSource={RelativeSource TemplatedParent}}"
Thickness="{Binding BorderThickness.Left, RelativeSource={RelativeSource TemplatedParent}}"
/>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Foreground" Value="Gold"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ellipse" Storyboard.TargetProperty="Width" To="16" Duration="0:0:0.03" />
<DoubleAnimation Storyboard.TargetName="ellipse" Storyboard.TargetProperty="Height" To="16" Duration="0:0:0.03" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ellipse" Storyboard.TargetProperty="Width" To="0" Duration="0:0:0.0" />
<DoubleAnimation Storyboard.TargetName="ellipse" Storyboard.TargetProperty="Height" To="0" Duration="0:0:0.0" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="uag:AlgoPickerNodeView" BasedOn="{StaticResource {x:Type uag:AlgoPickerNodeView}}">
<Setter Property="DropDownStyleKey" Value="{Binding DataContext.content_source, RelativeSource={RelativeSource AncestorType=usp:AlgoStudioView}, Converter={x:Static usp:AlgoContentTemplateSelector.AlgoDropDownStyleKeyConverter}}"/>
</Style>
</ResourceDictionary>
</UserControl.Resources>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.EditPane}}">
<VisualState Name="{x:Static u:VisualStates.Active}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="edit_pane" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static u:VisualStates.Inactive}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="edit_pane" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Hidden}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<AdornerDecorator>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TreeView
x:Name="_tree_view"
u:TreeViewEx.SelectedItemChangedHandler="{Binding}"
ItemsSource="{Binding definitions_view}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
MinWidth="180"
Background="Transparent"
Style="{StaticResource AlgoTemplateTreeViewStyle}"
>
<TreeView.CommandBindings>
<CommandBinding Command="{x:Static u:EditableCollectionViewEx.AddNewItemCommand}" Executed="{x:Static u:EditableCollectionViewEx.AddNewItemExecuted}" CanExecute="{x:Static u:EditableCollectionViewEx.AddNewItemCanExecute}"/>
<CommandBinding Command="{x:Static u:EditableCollectionViewEx.CommitAnyCommand}" Executed="{x:Static u:EditableCollectionViewEx.CommitAnyExecuted}"/>
</TreeView.CommandBindings>
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type sp:AlgoDefinitionVM}" ItemsSource="{Binding templates_view}">
<Grid u:StateManager.VisualStateCollection="{Binding tree_view_visual_states}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.TreeViewBadge}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.TreeViewBadge}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.TreeViewBadge}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="badge" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle
x:Name="badge"
Fill="{Binding badge_fill}"
Style="{StaticResource RectangleBadgeStyle}"
Visibility="{DynamicResource ResourceKey={x:Static usp:AlgoStudioView.BadgesInTreeViewVisibilityKey}}"
/>
<TextBlock x:Name="text_view" Grid.Column="1" Margin="{StaticResource Margin.LP1}" Text="{Binding name}"/>
</Grid>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding is_dirty}" Value="True">
<Setter TargetName="text_view" Property="Text" Value="{Binding name, StringFormat='{}{0}*'}"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type sp:AlgoDefinitionTemplateVM}">
<Grid u:StateManager.VisualStateCollection="{Binding tree_view_visual_states}" Margin="-6,0,0,0">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="favorite_toggle" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ToggleButton x:Name="favorite_toggle" Grid.Column="1" Margin="4,0,0,0" Style="{StaticResource AlgoTemplateFavoriteToggleButtonStyle}"/>
</Grid>
<TextBlock x:Name="text_view" Grid.Column="1" Margin="{StaticResource Margin.LP1}" Text="{Binding name}" ToolTip="Double click to set as default"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Value="{u:True}">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource OrConverter}">
<Binding Path="is_dirty"/>
<Binding Path="is_persisted" Converter="{StaticResource NotConverter}"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter TargetName="text_view" Property="Text" Value="{Binding name, StringFormat='{}{0}*'}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</TreeView.Resources>
</TreeView>
<ScrollViewer Grid.Column="1" Grid.IsSharedSizeScope="True" Margin="8,4">
<Grid x:Name="edit_pane">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid u:StateManager.VisualStateCollection="{Binding content_visual_states}" Margin="{StaticResource Margin.TP1}" >
<VisualStateManager.VisualStateGroups>
<!--Name-->
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static CannotRenameDefinition, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(TextBox.ToolTip)">
<DiscreteObjectKeyFrame KeyTime="0" Value="Cannot rename definitions."/>
</ObjectAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static CannotRenameDefinitionWhileTemplatesPresent, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(TextBox.ToolTip)">
<DiscreteObjectKeyFrame KeyTime="0" Value="Cannot rename definition while templates present."/>
</ObjectAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static CannotRenameTemplate, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Name}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(TextBox.ToolTip)">
<DiscreteObjectKeyFrame KeyTime="0" Value="Cannot rename templates."/>
</ObjectAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<!--Abbreviation-->
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<VisualState Name="{x:Static Populated, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_active_tooltip" Storyboard.TargetProperty="(FrameworkElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Unpopulated, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_active_tooltip" Storyboard.TargetProperty="(FrameworkElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_label" Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)">
<DiscreteColorKeyFrame KeyTime="0" Value="Gray"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static NotSupportedForTemplates, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_root" Storyboard.TargetProperty="(ToolTipService.ShowOnDisabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_root" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_label" Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)">
<DiscreteColorKeyFrame KeyTime="0" Value="Gray"/>
</ColorAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_not_supported_for_templates_tooltip" Storyboard.TargetProperty="(FrameworkElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<!--Badge Selector-->
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.BadgeSelector}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.BadgeSelector}}">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="default_badge" Storyboard.TargetProperty="(UIElement.Opacity)">
<DiscreteDoubleKeyFrame KeyTime="0" Value="0.5"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.BadgeSelector}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="custom_badge_color_picker_button" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="default_badge_radio_button" Storyboard.TargetProperty="(ToggleButton.IsChecked)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="param_name_col"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Name:</TextBlock>
<TextBox
x:Name="name_text_box"
Grid.Column="1"
ToolTipService.ShowOnDisabled="True"
Margin="{StaticResource Margin.LP1}"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Text="{Binding content_source.name, UpdateSourceTrigger=PropertyChanged, Delay=25}"
/>
<Grid x:Name="abbreviation_root" Grid.Column="2">
<Grid.ToolTip>
<Grid>
<TextBlock x:Name="abbreviation_active_tooltip" Visibility="Collapsed">
<TextBlock.Inlines>
<Run>Specify an abbreviation for this algo to use in ladder algo 'favorite' buttons.</Run>
<LineBreak/>
<Run FontStyle="Italic">Hint: To add/remove algos from 'favorites', open the ladder settings dialog and select the 'Algo Favorites' tab.</Run>
</TextBlock.Inlines>
</TextBlock>
<TextBlock x:Name="abbreviation_not_supported_for_templates_tooltip" Visibility="Collapsed">
Not supported for templates.
</TextBlock>
</Grid>
</Grid.ToolTip>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="abbreviation_label" FontStyle="Italic" Margin="{StaticResource Margin.LP1}" VerticalAlignment="Center">Abbrev.</TextBlock>
<TextBox Grid.Column="1" Margin="{StaticResource Margin.LP1}" Text="{Binding content_source.abbreviation, UpdateSourceTrigger=PropertyChanged, Delay=25}"/>
</Grid>
</Grid>
<Grid x:Name="badge_selector_radio_button_root" Grid.Row="1" Margin="{StaticResource Margin.TP2}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="param_name_col"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock>Icon:</TextBlock>
<RadioButton
x:Name="default_badge_radio_button"
Grid.Column="1"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Margin="{StaticResource Margin.LP1}"
GroupName="Badge"
>
<RadioButton.ToolTip>
<ToolTip DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<StackPanel Orientation="Vertical">
<TextBlock>Use the default icon color for this algo.</TextBlock>
<StackPanel TextElement.FontStyle="Italic" Orientation="Horizontal">
<TextBlock>Hint: the default color is that of the algo-root (</TextBlock>
<usp:OrderTypeItem
Margin="2,0"
BadgeFill="{Binding content_source.algo_root.meta.Color, Converter={StaticResource ColorToBrushConverter}}"
DisplayName="{Binding content_source.algo_root.display_name}"
/>
<TextBlock>).</TextBlock>
</StackPanel>
</StackPanel>
</ToolTip>
</RadioButton.ToolTip>
<Grid x:Name="default_badge_content_root">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock>Default</TextBlock>
<Rectangle
x:Name="default_badge"
Grid.Column="1"
Margin="{StaticResource Margin.LP1}"
Fill="{Binding content_source.algo_root.meta.Color, Converter={StaticResource ColorToBrushConverter}}"
Style="{StaticResource RectangleBadgeStyle}"
/>
</Grid>
</RadioButton>
<RadioButton
Grid.Column="2"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Margin="{StaticResource Margin.LP2}"
IsChecked="{Binding content_source.custom_badge_color.enabled}"
GroupName="Badge"
>
<RadioButton.ToolTip>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.ColumnSpan="3">Specify a custom icon color for this algo.</TextBlock>
<TextBlock Grid.Row="1" FontStyle="Italic">Hint: Click</TextBlock>
<Rectangle
Grid.Row="1"
Grid.Column="1"
Margin="3,0"
Fill="{Binding content_source.custom_badge_color.value, Converter={StaticResource ColorToBrushConverter}}"
Style="{StaticResource RectangleBadgeStyle}"
/>
<TextBlock Grid.Row="1" Grid.Column="2" FontStyle="Italic">to open the color picker popup.</TextBlock>
</Grid>
</RadioButton.ToolTip>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock>Custom</TextBlock>
<Button
x:Name="custom_badge_color_picker_button"
Grid.Column="1"
Background="{Binding content_source.custom_badge_color.value, Converter={StaticResource ColorToBrushConverter}}"
Margin="{StaticResource Margin.LP1}"
Style="{StaticResource CustomBadgeColorPickerButtonStyle}"
/>
<Popup x:Name="custom_badge_color_picker_popup" StaysOpen="False" PlacementTarget="{Binding ElementName=custom_badge_color_picker_button}" Placement="Right">
<Border Style="{StaticResource CustomBadgeColorPickerPopupRootStyle}">
<cp:ColorPickerControl
Background="Transparent"
Palettes="{Binding DataContext.content_source.custom_badge_color_palettes, RelativeSource={RelativeSource AncestorType=Popup}}"
SelectedColor="{Binding DataContext.content_source.custom_badge_color.value, RelativeSource={RelativeSource AncestorType=Popup}, Mode=TwoWay}"
/>
</Border>
</Popup>
</Grid>
</RadioButton>
</Grid>
<GroupBox
x:Name="content_host"
Grid.Row="2"
Background="Transparent"
BorderBrush="{Binding content_source.algo_root, Converter={StaticResource OrderTypeBrushConverter}}"
Margin="0,6,0,0"
Padding="12,8"
>
<GroupBox.Style>
<Style TargetType="GroupBox" BasedOn="{StaticResource ContentHostGroupBoxStyle}">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Style.Triggers>
<Trigger Property="BorderBrush" Value="Transparent">
<Setter Property="BorderThickness" Value="0"/>
</Trigger>
<Trigger Property="usp:AlgoStudioView.IsMouseOverNodeContent" Value="True">
<Setter Property="BorderThickness" Value="2"/>
</Trigger>
</Style.Triggers>
</Style>
</GroupBox.Style>
<GroupBox.Header>
<ComboBox
Grid.Column="3"
ToolTipService.ShowOnDisabled="True"
SelectedItem="{Binding selected_definition.algo_root}"
ItemsSource="{Binding selected_definition.algos_view}"
Margin="{StaticResource Margin.LP1}"
Width="140"
>
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding content_source}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
<DataTrigger Binding="{Binding selected_definition.templates.Count, Converter={StaticResource IntIsZeroConverter}, FallbackValue={u:False}}" Value="{u:True}">
<Setter Property="IsEnabled" Value="True"/>
</DataTrigger>
<DataTrigger Binding="{Binding selected_definition.templates.Count, Converter={StaticResource IntIsZeroConverter}, FallbackValue={u:False}}" Value="{u:False}">
<Setter Property="IsEnabled" Value="False"/>
<Setter Property="ToolTip" Value="Cannot change structure while templates are present."/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
<ComboBox.ItemTemplate>
<DataTemplate>
<usp:OrderTypeItem DisplayName="{Binding display_name}" BadgeFill="{Binding meta.Color, Converter={StaticResource ColorToBrushConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</GroupBox.Header>
<ContentControl
Grid.IsSharedSizeScope="True"
Content="{Binding selected_definition.algo_root}"
ContentTemplateSelector="{StaticResource AlgoTemplateSelector}"
Margin="{StaticResource Margin.TP1}"
>
<ContentControl.Resources>
<Style TargetType="GroupBox" BasedOn="{StaticResource ContentHostGroupBoxStyle}"/>
</ContentControl.Resources>
</ContentControl>
</GroupBox>
<c:DialogSkirt Grid.Row="3" Margin="{StaticResource Margin.TP2}" Background="Transparent">
<c:DialogSkirt.RightItems>
<x:ArrayExtension Type="{x:Type Button}">
<Button ToolTipService.ShowOnDisabled="True" Command="{Binding save_cmd}" CommandParameter="{Binding content_source}" Width="100" Style="{StaticResource {x:Static c:DialogSkirt.DialogSkirtButtonStyleKey}}" ToolTip="{Binding save_cmd_tooltip}" IsDefault="True">
<TextBlock Text="{Binding selected_definition.name, StringFormat='{}Save {0}'}"/>
</Button>
<Button ToolTipService.ShowOnDisabled="True" Command="{Binding revert_cmd}" CommandParameter="{Binding content_source}" Width="100" Style="{StaticResource {x:Static c:DialogSkirt.DialogSkirtButtonStyleKey}}" ToolTip="{Binding revert_cmd_tooltip}">
<TextBlock Text="{Binding selected_definition.name, StringFormat='{}Revert {0}'}"/>
</Button>
</x:ArrayExtension>
</c:DialogSkirt.RightItems>
</c:DialogSkirt>
</Grid>
</ScrollViewer>
</Grid>
</AdornerDecorator>
</UserControl>
@@ -0,0 +1,112 @@
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;
namespace mbts.ui.spark {
partial class AlgoStudioView : UserControl {
public const string BadgesInTreeViewVisibilityKey = nameof(BadgesInTreeViewVisibilityKey);
public static readonly IValueConverter EditPaneVisualStateConverter =
ValueConverter.create(obj => obj == null ? VisualStates.Inactive : VisualStates.Active);
IAlgoStudioViewController _controller;
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<GroupBox>(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;
}
public void add_definition() => _controller.add_definition();
public void add_definition_clone(AlgoDefinitionVM src_definition) => _controller.add_definition_clone(src_definition);
public void add_template(AlgoDefinitionVM definition) => _controller.add_template(definition);
public void rename_definition(AlgoDefinitionVM definition) => _controller.rename_definition(definition);
public void rename_template(AlgoDefinitionTemplateVM template) => _controller.rename_template(template);
public void select_definition(AlgoDefinitionVM definition) => _controller.select_definition(definition);
public void select_template(AlgoDefinitionTemplateVM template) => _controller.select_template(template);
public IDisposable preserve_selected_definition() => _controller.preserve_selected_definition();
void _end_edit_executed(object s, ExecutedRoutedEventArgs e) =>
_controller.end_edit(e);
public static class VisualStateNames {
public static class EditPane {
public const string GroupName = nameof(EditPane);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
public static class Name {
public const string GroupName = nameof(Name);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}",
CannotRenameDefinition = nameof(CannotRenameDefinition),
CannotRenameDefinitionWhileTemplatesPresent = nameof(CannotRenameDefinitionWhileTemplatesPresent),
CannotRenameTemplate = nameof(CannotRenameTemplate);
}
public static class Abbreviation {
public const string GroupName = nameof(Abbreviation);
public static readonly string
Populated = $"{GroupName}{nameof(Populated)}",
Unpopulated = $"{GroupName}{nameof(Unpopulated)}",
NotSupportedForTemplates = $"{GroupName}{nameof(NotSupportedForTemplates)}";
}
public static class BadgeSelector {
public const string GroupName = nameof(BadgeSelector);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
public static class TreeViewBadge {
public const string GroupName = nameof(TreeViewBadge);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
public static class FavoriteToggleButton {
public const string GroupName = nameof(FavoriteToggleButton);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
}
}
}
@@ -0,0 +1,133 @@
using mbts.spark;
using mbts.ui.controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace mbts.ui.spark {
interface IAlgoStudioViewController : IDisposable {
void add_definition();
void add_definition_clone(AlgoDefinitionVM src_definition);
void add_template(AlgoDefinitionVM definition);
void rename_definition(AlgoDefinitionVM definition);
void rename_template(AlgoDefinitionTemplateVM template);
void end_edit(ExecutedRoutedEventArgs e);
void select_definition(AlgoDefinitionVM definition);
void select_template(AlgoDefinitionTemplateVM template);
IDisposable preserve_selected_definition();
}
class AlgoStudioViewControllerFactory {
static readonly IAlgoStudioViewController _empty = new EmptyController();
public static IAlgoStudioViewController create(AlgoStudioVM vm, TreeView tree_view, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) =>
vm == null || tree_view == null || name_text_box == null || color_picker_button == null || color_picker_popup == null ?
_empty : new Controller(vm, tree_view, name_text_box, color_picker_button, color_picker_popup);
/// <summary>
/// This wrapper class is returned by <see cref="create(AlgoStudioVM, TreeView)"/> when the vm or tree_view is null.
/// This further separates the view from the controller-logic; it doesn't even need to check for null when accessing <see cref="IAlgoStudioViewController"/> methods.
/// </summary>
class EmptyController : IAlgoStudioViewController {
public void add_definition() { }
public void add_definition_clone(AlgoDefinitionVM src_definition) { }
public void add_template(AlgoDefinitionVM definition) { }
public void rename_definition(AlgoDefinitionVM definition) { }
public void rename_template(AlgoDefinitionTemplateVM template) { }
public void end_edit(ExecutedRoutedEventArgs e) { }
public void select_definition(AlgoDefinitionVM definition) { }
public void select_template(AlgoDefinitionTemplateVM template) { }
public IDisposable preserve_selected_definition() => Disposable.empty;
public void Dispose() { }
}
class Controller : IAlgoStudioViewController {
readonly AlgoStudioVM _vm;
readonly TreeView _tree_view;
readonly TextBox _name_text_box;
IDisposable _dispose;
public Controller(AlgoStudioVM vm, TreeView tree_view, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) {
_vm = vm;
_tree_view = tree_view;
_name_text_box = name_text_box;
_dispose = PopupViewController.attach(color_picker_popup, color_picker_button);
}
public void add_definition() {
_vm.add_new_definition();
_begin_edit();
}
public void add_definition_clone(AlgoDefinitionVM src_definition) {
_vm.add_new_definition_clone(src_definition);
_begin_edit();
}
public void add_template(AlgoDefinitionVM def) {
var new_tmp = def.template_factory();
def.templates.Add(new_tmp);
_begin_edit();
}
public void end_edit(ExecutedRoutedEventArgs e) {
if (e.OriginalSource is EditableTextBlock etb) {
etb.end_edit();
_get_container(etb.DataContext)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true);
}
}
public void rename_definition(AlgoDefinitionVM definition) {
if (_tree_view.ItemContainerGenerator.ContainerFromItem(definition) is TreeViewItem tvi) {
var etb = tvi.descendants_of_type<EditableTextBlock>().FirstOrDefault();
etb.SetCurrentValue(EditableTextBlock.IsEditingProperty, true);
}
}
public void rename_template(AlgoDefinitionTemplateVM template) {
if (_tree_view.ItemContainerGenerator.ContainerFromItem(template.owner) is TreeViewItem tvi) {
if (tvi.ItemContainerGenerator.ContainerFromItem(template) is TreeViewItem ttvi) {
var etb = ttvi.descendants_of_type<EditableTextBlock>().FirstOrDefault();
etb.SetCurrentValue(EditableTextBlock.IsEditingProperty, true);
}
}
}
public void select_definition(AlgoDefinitionVM definition) =>
_tree_view.ItemContainerGenerator.ContainerFromItem(definition)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true);
public void select_template(AlgoDefinitionTemplateVM template) {
if (_tree_view.ItemContainerGenerator.ContainerFromItem(template.owner) is TreeViewItem def_view) {
def_view.SetCurrentValue(TreeViewItem.IsSelectedProperty, true);
def_view.ItemContainerGenerator.ContainerFromItem(template)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true);
}
}
public IDisposable preserve_selected_definition() =>
Disposable.Create(() => {
var name = _vm.selected_definition.name;
if (_vm.definitions.TryGetFirst(d => d.name == name, out AlgoDefinitionVM def))
_tree_view.ItemContainerGenerator.ContainerFromItem(def)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true);
});
public void Dispose() =>
Disposable.dispose(ref _dispose);
void _begin_edit() =>
WPFHelper.push_frame_until(() => Keyboard.Focus(_name_text_box) == _name_text_box);
TreeViewItem _get_container(object obj) =>
obj is AlgoDefinitionTemplateVM t ? _get_container(t) :
obj is AlgoDefinitionVM d ? _get_container(d) : null;
TreeViewItem _get_container(AlgoDefinitionVM d) =>
_tree_view.ItemContainerGenerator.ContainerFromItem(d) as TreeViewItem;
TreeViewItem _get_container(AlgoDefinitionTemplateVM t) =>
_get_container(t.owner) is TreeViewItem dview ? dview.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem : null;
}
}
}
@@ -0,0 +1,176 @@
using bts.api;
using bts.shell;
using bts.spark;
using mbts.ui;
using mbts.ui.spark;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows;
using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData;
namespace mbts.spark {
internal class AlgoStudioWindow : SparkWindow<StartupData>, IShellWindow {
public const string
NAME = "Algo Studio",
TemplatesEnabledKey = nameof(TemplatesEnabledKey),
ShowAlgoToolBarSaveDefinitionKey = nameof(ShowAlgoToolBarSaveDefinitionKey),
ShowAlgoToolBarRenameDefinitionKey = nameof(ShowAlgoToolBarRenameDefinitionKey),
ShowAlgoToolBarRevertDefinitionKey = nameof(ShowAlgoToolBarRevertDefinitionKey),
ShowAlgoToolBarUndoRedoDefinitionKey = nameof(ShowAlgoToolBarUndoRedoDefinitionKey);
const double
DEFAULT_CONTENT_WIDTH = 550.2,
DEFAULT_CONTENT_HEIGHT = 513.8;
readonly OrdersModel _model;
readonly List<SparkCommand> _commands = new List<SparkCommand>();
AlgoStudioVM _vm;
AlgoStudioView _view;
StartupData _state;
CompositeDisposable _resources;
public AlgoStudioWindow(OrdersModel model, AlgoStudioWindowFactory factory, IBus bus, StartupData state, ErrorReporter error_reporter)
: base(NAME, bus, factory, SparkCommands.ShowAlgoStudio.icon) {
_model = model;
_state = state;
thread_init();
}
public override StartupData SaveState => _state = _vm.create();
public override string window_type => NAME;
public override UIElement Content => _view;
public override IEnumerable<SparkCommand> 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;
bts.config.AlgoStudioOptions _ui_configuration => _model.algo_model.ui_configuration;
public override void Dispose() =>
_dispose_core();
public void thread_init() {
_dispose_core();
_vm = new AlgoStudioVM(_model);
_vm.load_from(_state);
_view = new AlgoStudioView { DataContext = _vm };
_view.Resources[AlgoStudioView.BadgesInTreeViewVisibilityKey] = _ui_configuration.show_badges_in_tree_view ? Visibility.Visible : Visibility.Collapsed;
_resources = new CompositeDisposable();
// observable sources
var content_src = _vm.observe_selected().Select(_ => _vm.content_source);
// add definition
_commands.Add(new SparkCommandCommand("Add Algo", Icons.AddBoxes, new DelegateCommand(_view.add_definition)));
// add definition clone
var add_definition_clone_spark_cmd = new ObservantSparkCommandCommand<AlgoDefinitionVM>(Icons.DocumentCopy, d => $"Clone '{d?.name}'", d => d != null, _view.add_definition_clone);
_commands.Add(add_definition_clone_spark_cmd);
// add template
var add_template_spark_cmd = new ObservantSparkCommandCommand<AlgoDefinitionVM>(Icons.AddFile, d => $"Add '{d?.name}' Template", d => d != null, _view.add_template) {
show_in_toolbar = (_ui_configuration.add_template_button & bts.config.AlgoStudioOptions.AddTemplateButton.MainToolBar) == bts.config.AlgoStudioOptions.AddTemplateButton.MainToolBar,
show_in_context_menu = (_ui_configuration.add_template_button & bts.config.AlgoStudioOptions.AddTemplateButton.DefinitionContextMenu) == bts.config.AlgoStudioOptions.AddTemplateButton.DefinitionContextMenu
};
_commands.Add(add_template_spark_cmd);
_resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(add_definition_clone_spark_cmd, add_template_spark_cmd));
// save
if (_ui_configuration.can_save_specific) {
var content_is_dirty_src = _vm.observe_selected().SelectManyInSeries(t => {
if (t.template != null) {
return t.template.observe_is_dirty();
} else if (t.definition != null) {
return t.definition.subscribe_is_definition_dirty();
} else return Observable.Return(false);
}).RefCount();
_commands.Add(new ReactiveSparkCommand(content_src.OnDispatcher().Select(c => $"Save '{c?.name}'"), Icons.DiskFile, () => {
if (_vm.selected_template is AlgoDefinitionTemplateVM t)
_vm.save_template(t).ignore();
else if (_vm.selected_definition is AlgoDefinitionVM d)
_vm.save_definition(d).ignore();
}, content_is_dirty_src));
}
// save all
var save_all_cmd = new ObservantAsyncCommand(_vm.save_all);
_commands.Add(new SparkCommandCommand("Save All", Icons.Disk, save_all_cmd));
_resources.Add(_vm.subscribe_dirty().OnDispatcher().Subscribe(save_all_cmd));
// undo/redo
if (_ui_configuration.can_undo_redo) {
// undo
var undo_cmd = new ObservantCommand(() => _vm.content_source?.try_undo());
var undo_spark_cmd = new SparkCommandCommand("Undo", Icons.UndoCircular, undo_cmd);
var can_undo_source = _vm.observe_selected().SelectManyInSeries(tup => {
IAlgoStudioContentVM content = (IAlgoStudioContentVM)tup.template ?? tup.definition;
return content != null ?
Observable.Create<bool>(o => {
content.can_undo_changed += notify;
notify();
return Disposable.Create(() => content.can_undo_changed -= notify);
void notify() => o.OnNext(content.can_undo);
}) :
Observable.Return(false);
});
_commands.Add(undo_spark_cmd);
_resources.Add(can_undo_source.Subscribe(undo_cmd));
_resources.Add(can_undo_source.Connect());
// redo
var redo_cmd = new ObservantCommand(() => _vm.content_source?.try_redo());
var redo_spark_cmd = new SparkCommandCommand("Redo", Icons.RedoCircular, redo_cmd);
var can_redo_source = _vm.observe_selected().SelectManyInSeries(tup => {
IAlgoStudioContentVM content = (IAlgoStudioContentVM)tup.template ?? tup.definition;
return content != null ?
Observable.Create<bool>(o => {
content.can_redo_changed += notify;
notify();
return Disposable.Create(() => content.can_redo_changed -= notify);
void notify() => o.OnNext(content.can_redo);
}) :
Observable.Return(false);
});
_commands.Add(redo_spark_cmd);
_resources.Add(can_redo_source.Subscribe(redo_cmd));
_resources.Add(can_redo_source.Connect());
}
// remove
var remove_spark_cmd = new ObservantSparkCommandCommand<IAlgoStudioContentVM>(Icons.Trash, v => $"Remove '{v?.name}'", v => v != null, value => {
if (value is AlgoDefinitionTemplateVM t) {
_vm.remove_template(t).ignore();
} else if (value is AlgoDefinitionVM d) {
string prompt; MessageBoxImage icon;
if (_model.algo_model.templates_enabled() && d.templates.Count > 0) {
prompt = $"Deleting this definition ({d.name}) will also delete its templates ({d.templates.Count}).\n\nDo you wan to Continue?";
icon = MessageBoxImage.Warning;
} else if (d.key.mode == AlgoKey.Mode.Persisted) {
prompt = $"Are you sure you want to delete '{d.name}?'";
icon = MessageBoxImage.Question;
} else {
// algo hasn't even been created yet (just an unsaved placeholder item), no need to get user confirmation in this case.
prompt = null;
icon = default;
}
if (prompt != null) {
var resp = BTSMessageBox.Show(prompt, "Algo Studio", BTSMessageBoxButtons.Yes | BTSMessageBoxButtons.No, icon);
switch (resp) {
case BTSMessageBoxButtons.Yes: break;
case BTSMessageBoxButtons.No:
default: return;
}
}
_vm.remove_definition(d).ignore();
}
});
_commands.Add(remove_spark_cmd);
_resources.Add(content_src.OnDispatcher().Subscribe(remove_spark_cmd));
}
void _dispose_core() {
Disposable.dispose(ref _resources);
if (_commands != null) _commands.OfType<IDisposable>().DisposeAll();
Disposable.dispose(ref _vm);
}
}
}
@@ -0,0 +1,33 @@
using bts.api;
using bts.spark;
using mbts.spark;
using mbts.ui;
using ProtoBuf;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace bts.shell {
class AlgoStudioWindowFactory : ShellWindowFactory<AlgoStudioWindowFactory.StartupData> {
readonly IBus _bus;
readonly OrdersModel _model;
readonly ErrorReporter _error_reporter;
public AlgoStudioWindowFactory(IShellModule owner, IBus bus, OrdersModel model, ErrorReporter error_reporter)
: base(owner, AlgoStudioWindow.NAME) {
_bus = bus;
_model = model;
_error_reporter = error_reporter;
_dispose = bus.subscribe(SparkTags.ShowAlgoStudioTag).OnDispatcher().Subscribe(_show);
}
public override Task<IShellWindow> load(StartupData state) =>
Task.FromResult<IShellWindow>(new AlgoStudioWindow(_model, this, _bus, state, _error_reporter));
async void _show(StartupData startup_data) =>
_bus.post(SparkTags.ShowWindow, await load(startup_data));
[ProtoContract]
public class StartupData { }
}
}
@@ -0,0 +1,39 @@
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
using System;
namespace mbts.spark {
struct AlgoData : IEquatable<AlgoData> {
public readonly CustomOrderDefinitionImmutable value;
public readonly string name;
public readonly AlgoKey key;
public AlgoData(CustomOrderDefinitionImmutable value)
: this(value, value.CustomCase.display_name(), new AlgoKey(value.CustomCase)) { }
public AlgoData(CustomOrderDefinitionImmutable value, string name, AlgoKey key) {
this.value = value;
this.name = name;
this.key = key;
}
public AlgoData with(CustomOrderDefinitionImmutable? value = null, string name = null) =>
new AlgoData(value ?? this.value, name ?? this.name, key);
public bool Equals(AlgoData other) =>
key == other.key &&
name == other.name &&
OrderDataHelper.EqualsHelpers.custom_order_def_compareri.Equals(value, other.value);
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
key.GetHashCode(),
EqualityComparer.safe_get_hash_code(name),
value.GetHashCode());
public static bool operator ==(AlgoData a, AlgoData b) => a.Equals(b);
public static bool operator !=(AlgoData a, AlgoData b) => !a.Equals(b);
}
}
@@ -0,0 +1,86 @@
using bts.api.orderman;
using bts.persist.algo;
using bts.utils;
using System;
namespace mbts.spark {
struct AlgoKey : IEquatable<AlgoKey> {
readonly AlgoPersistedKey? _persisted_key;
readonly AlgoNameStructureKey? _factory_key;
readonly Guid? _unpersisted;
public AlgoKey(Guid id_guid) {
_persisted_key = null;
_factory_key = null;
_unpersisted = id_guid;
}
public AlgoKey(CustomOrderDefinition.CustomOneofCase factory_root_algo_type)
: this(new AlgoNameStructureKey(factory_root_algo_type)) { }
public AlgoKey(AlgoNameStructureKey factory_key) {
_persisted_key = null;
_factory_key = factory_key;
_unpersisted = null;
}
public AlgoKey(AlgoPersistedKey persisted_key) {
_persisted_key = persisted_key;
_factory_key = null;
_unpersisted = null;
}
public enum Mode {
None,
Persisted,
Unpersisted,
Factory
}
public bool is_persisted => mode == Mode.Persisted;
public AlgoPersistedKey persisted => _persisted_key.Value;
public AlgoNameStructureKey factory => _factory_key ?? new AlgoNameStructureKey(CustomOrderDefinition.CustomOneofCase.None);
public Guid unpersisted => _unpersisted.Value;
public Mode mode {
get {
if (_persisted_key.HasValue) return Mode.Persisted;
if (_unpersisted.HasValue) return Mode.Unpersisted;
if (_factory_key.HasValue) return Mode.Factory;
return Mode.None;
}
}
public bool Equals(AlgoKey other) {
Mode m = mode;
if (m == other.mode) {
switch (m) {
case Mode.Persisted: return persisted == other.persisted;
case Mode.Unpersisted: return unpersisted == other.unpersisted;
case Mode.Factory: return factory == other.factory;
case Mode.None: return true;
}
}
return false;
}
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() {
int hash, phase_mult;
switch (mode) {
case Mode.None: hash = -1; phase_mult = 1; break;
case Mode.Persisted: hash = persisted.GetHashCode(); phase_mult = 2; break;
case Mode.Unpersisted: hash = unpersisted.GetHashCode(); phase_mult = 4; break;
case Mode.Factory: hash = factory.GetHashCode(); phase_mult = 3; break;
default: return 0;
}
return EqualityComparer.phase_hash(hash, phase_mult);
}
public static bool operator ==(AlgoKey a, AlgoKey b) => a.Equals(b);
public static bool operator !=(AlgoKey a, AlgoKey b) => !a.Equals(b);
InvalidOperationException _unexpected_mode_ex() => new InvalidOperationException($"Unexpected Mode '{mode}.'");
}
}
@@ -0,0 +1,74 @@
using bts.utils;
using ProtoBuf;
using System;
namespace bts.persist.algo {
[ProtoContract]
struct AlgoPersistedKey : IEquatable<AlgoPersistedKey> {
[ProtoMember(1)]
readonly string _id_string;
[ProtoMember(2)]
readonly uint? _id_uint;
public AlgoPersistedKey(string id_string) {
_id_string = id_string;
_id_uint = null;
}
public AlgoPersistedKey(uint id_uint) {
_id_uint = id_uint;
_id_string = null;
}
public enum Mode {
None,
String,
UInt
}
public string id_string => _id_string ?? string.Empty;
public uint id_uint => _id_uint ?? 0;
public Mode mode {
get {
if (_id_string != null) return Mode.String;
if (_id_uint.HasValue) return Mode.UInt;
return Mode.None;
}
}
public bool is_persisted => mode != Mode.None;
public mbts.spark.AlgoKey to_algo_key() =>
new mbts.spark.AlgoKey(this);
public bool Equals(AlgoPersistedKey other) {
Mode m = mode;
if (m == other.mode) {
switch (m) {
case Mode.String: return id_string == other.id_string;
case Mode.UInt: return id_uint == other.id_uint;
case Mode.None: return true;
}
}
return false;
}
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() {
int hash, phase_mult;
switch (mode) {
case Mode.None: hash = -1; phase_mult = 1; break;
case Mode.String: hash = id_string.GetHashCode(); phase_mult = 2; break;
case Mode.UInt: hash = id_uint.GetHashCode(); phase_mult = 3; break;
default: return 0;
}
return EqualityComparer.phase_hash(hash, phase_mult);
}
public static bool operator ==(AlgoPersistedKey a, AlgoPersistedKey b) => a.Equals(b);
public static bool operator !=(AlgoPersistedKey a, AlgoPersistedKey b) => !a.Equals(b);
InvalidOperationException _unexpected_mode_ex() => new InvalidOperationException($"Unexpected Mode '{mode}.'");
}
}
@@ -0,0 +1,104 @@
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
using ProtoBuf;
using System;
using System.Linq;
namespace mbts.spark {
struct AlgoNameStructureKey : IEquatable<AlgoNameStructureKey> {
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)) { }
public AlgoNameStructureKey(string name, AlgoStructureKey structure) {
this.name = name;
this.structure = structure;
}
public bool Equals(AlgoNameStructureKey other) => name == other.name && structure == other.structure;
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() => EqualityComparer.aggregate_hash(EqualityComparer.safe_get_hash_code(name), structure.GetHashCode());
public static bool operator ==(AlgoNameStructureKey a, AlgoNameStructureKey b) => a.Equals(b);
public static bool operator !=(AlgoNameStructureKey a, AlgoNameStructureKey b) => !a.Equals(b);
}
[ProtoContract]
struct AlgoStructureKey : IEquatable<AlgoStructureKey> {
[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(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 bool Equals(AlgoStructureKey other) =>
_structure.Length == other._structure.Length &&
_structure.SequenceEqual(other._structure);
public override bool Equals(object obj) =>
obj is AlgoStructureKey other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(_structure);
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 void _build_structure(CustomOrderDefinition algo, ref int[] structure, int pos) {
var cad = OrderDataHelper.get_child_algo_data(algo.CustomCase);
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);
}
static void _build_def(int[] structure, ref int pos, ref CustomOrderDefinition algo) {
for (int i = pos; i < structure.Length; i++) {
var cad = OrderDataHelper.get_child_algo_data(algo.CustomCase);
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].set_child(algo, child_algo);
}
}
}
}
}
}
@@ -0,0 +1,345 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.persist.algo;
using bts.spark;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace mbts.spark {
class AlgoStudioDefinitionTemplateModel : IAlgoStudioModel, IDisposable {
readonly AlgoService _service;
readonly AdminModel _admin_model;
readonly ErrorReporter _error_reporter;
readonly ObservableDemuxer<AlgoKey, AlgoDefinitionMetadata> _metadata_demuxer = new ObservableDemuxer<AlgoKey, AlgoDefinitionMetadata>();
readonly TableUpdateDemuxer<AlgoTemplateData, AlgoKey, AlgoKey> _definition_templates_demuxer;
IReadOnlyDictionary<AlgoKey, AlgoData> _algos = DictionaryHelper.empty<AlgoKey, AlgoData>();
IReadOnlyDictionary<AlgoKey, AlgoTemplateData> _algo_templates = DictionaryHelper.empty<AlgoKey, AlgoTemplateData>();
IDisposable _dispose;
public AlgoStudioDefinitionTemplateModel(AlgoService service, IAlgoDefinitionMetadataService meta, AdminModel admin_model, ErrorReporter error_reporter, bts.config.AlgoStudioOptions ui_configuration) {
_service = service;
metadata_service = meta;
_admin_model = admin_model;
_error_reporter = error_reporter;
this.ui_configuration = ui_configuration;
_definition_templates_demuxer = new TableUpdateDemuxer<AlgoTemplateData, AlgoKey, AlgoKey>(t => t.key, t => t.definition_key);
definitions = _service.subscribei_algos()
.Select(u => new Update<AlgoData, AlgoKey>(
u.all.Select(_Utils.definition_data).ToList(),
u.added.Select(_Utils.definition_data).ToList(),
u.changes.Select(ch => new Change<AlgoData>(_Utils.definition_data(ch.Old), _Utils.definition_data(ch.New))).ToList(),
u.removed.Select(d => _Utils.definition_data(d)).ToList(),
def => def.key))
.Table()
.Cache();
templates = _service.subscribei_algo_templates()
.Select(u => new Update<AlgoTemplateData, AlgoKey>(
u.all.Select(_Utils.template_data).ToList(),
u.added.Select(_Utils.template_data).ToList(),
u.changes.Select(ch => new Change<AlgoTemplateData>(_Utils.template_data(ch.Old), _Utils.template_data(ch.New))).ToList(),
u.removed.Select(_Utils.template_data).ToList(),
def => def.key))
.Table()
.Cache();
_dispose = new CompositeDisposable(
definitions.OnDispatcher().Subscribe(t => _algos = t.state),
templates.OnDispatcher().Subscribe(t => _algo_templates = t.state),
templates.Subscribe(_definition_templates_demuxer),
metadata_service.subscribe_metadata().Subscribe(_metadata_demuxer));
}
public IObservable<TableUpdate<AlgoData, AlgoKey>> definitions { get; }
public IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> templates { get; }
public IAlgoDefinitionMetadataService metadata_service { get; }
public bts.config.AlgoStudioOptions ui_configuration { get; }
public IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> subscribe_definition_templates(AlgoKey definition) =>
_definition_templates_demuxer.subscribe(definition);
public async Task<AlgoData?> save_definition(AlgoData definition_data) {
if (definition_data.key.is_persisted) {
// TODO: implement update op when backend ready
} else {
// create op
return await _create_definition(new CompositeAlgoDefinitionImmutable(_Utils.to_definition(definition_data)));
}
return null;
}
public async Task<AlgoTemplateData?> save_template(AlgoTemplateData template_data) {
if (template_data.key.is_persisted) {
// update op
return await _update_template(_Utils.to_recordi(template_data));
} else {
// create op
return await _create_template(_Utils.to_templatei(template_data));
}
}
/// <summary>
/// The api is not used here (there are some unresolved dependency issues with definitions on the backend).
/// The definition is marked as hidden in the AlgoMetadata stored on the server.
/// <para/>
/// For implementation details, see: <see cref="IAlgoDefinitionMetadataService"/>, <see cref="AlgoTemplateMetadataService"/>
/// </summary>
public async Task<bool> remove_definition(AlgoKey key) {
if (_algos.TryGetValue(key, out AlgoData curr)) {
if (_definition_templates_demuxer.try_get_values(key, out IReadOnlyDictionary<AlgoKey, AlgoTemplateData> tmps)) {
foreach (var t in tmps.Values)
await remove_template(t.key);
}
await metadata_service.hide_definition(key);
return true;
}
return false;
}
public async Task<bool> remove_template(AlgoKey template_key) {
var req = new AlgoServiceRemoveRequest();
_Utils.set_key(ref req, template_key);
var reply = await _safe_execute(() => _service.remove_template_async(req), ActionMetadata.remove_template);
return reply.success && reply.value.Success;
}
public void Dispose() =>
Disposable.dispose(ref _dispose);
async Task<AlgoData?> _create_definition(CompositeAlgoDefinitionImmutable definition) {
if (_try_get_user(out uint user_id)) {
return await _create_definition(definition, user_id);
} else {
_report_no_user_id(ActionMetadata.CreateDefinition);
}
return null;
}
async Task<AlgoTemplateData?> _create_template(AlgoTemplateImmutable template) {
if (_try_get_user(out uint user_id)) {
var (value, success) = await _error_reporter.safe_execute(() => _service.create_template_async(
new TemplateCreateRequest { UserId = user_id, NewTemplate = template.CloneToMutable() }),
r => r.Success, r => r.ErrMsg, ActionMetadata.CreateTemplate);
if (success)
return _Utils.template_data(value.Record);
} else {
_report_no_user_id(ActionMetadata.CreateTemplate);
}
return null;
}
async Task<AlgoTemplateData?> _update_template(AlgoTemplateRecordImmutable template) {
if (_try_get_user(out uint user_id)) {
var (value, success) = await _error_reporter.safe_execute(() => _service.update_template_async(
new TemplateUpdateRequest { Key = template.Key, UpdatedTemplate = template.AlgoTemplate.CloneToMutable() }),
r => r.Success, r => r.ErrMsg.ToString(), ActionMetadata.UpdateTemplate);
if (success)
return _Utils.template_data(template);
} else {
_report_no_user_id(ActionMetadata.UpdateTemplate);
}
return null;
}
async Task<AlgoData?> _create_definition(CompositeAlgoDefinitionImmutable definition, uint user_id) {
(var result, var success) = await _error_reporter.safe_execute(() => _service.create_composite_algo_async(
new CompositeAlgoCreateRequest {
NewAlgo = definition.CloneToMutable(),
UserId = user_id
}), r => r.Success, r => r.ErrMsg, "create definition");
return success ? _Utils.definition_data(new CompositeAlgoRecordImmutable(result.Record)) : (AlgoData?)null;
}
async Task<Result<T>> _safe_execute<T>(Func<Task<Result<T>>> execute, IActionMetadata<T> am) {
try {
var result = await execute();
if (!result.success) {
_report_error(am.present_progressive_desc, result.error_message);
} else if (!am.get_success(result.value)) {
_report_error(am.present_progressive_desc, am.get_error_msg(result.value));
}
return result;
} catch (Exception ex) {
_report_error(am.present_progressive_desc, ex.ToString());
}
return new Result<T>(bts.api.ApiError.UnexpectedResponse);
}
void _report_error(string present_progressive_desc, string msg) =>
_error_reporter.report_error($"Error {present_progressive_desc}: {msg}", AlgoStudioWindow.NAME, System.Windows.MessageBoxImage.Warning);
void _report_no_user_id(string desc) =>
_error_reporter.report_error($"{desc} failed: did not find current user id");
bool _try_get_user(out uint id) {
var user = _admin_model.get_current_user();
if (user.HasValue) {
id = user.Value.id;
return true;
} else {
id = 0;
return false;
}
}
// used for error handling/reporting
interface IActionMetadata {
string desc { get; }
string present_progressive_desc { get; }
}
interface IActionMetadata<TReply> : IActionMetadata {
bool get_success(TReply reply);
string get_error_msg(TReply reply);
}
static class ActionMetadata {
public const string
CreateDefinition = "create definition",
UpdateDefinition = "update definition",
CreateTemplate = "create template",
UpdateTemplate = "update template";
public static readonly IActionMetadata<AlgoServiceReply> update_template = new Impl<AlgoServiceReply>(_update, _template, r => r.Success, r => r.ErrMsg.ToString());
public static readonly IActionMetadata<AlgoServiceReply> remove_template = new Impl<AlgoServiceReply>(_delete, _template, r => r.Success, r => r.ErrMsg.ToString());
public static readonly IActionMetadata<TemplateCreateResult> create_template = new Impl<TemplateCreateResult>(_create, _template, r => r.Success, r => r.ErrMsg);
public static readonly IActionMetadata<CompositeAlgoCreateResult> create_definition = new Impl<CompositeAlgoCreateResult>(_create, _definition, r => r.Success, r => r.ErrMsg);
static readonly DescTuple _create = new DescTuple("create", "creating"), _update = new DescTuple("update", "updating"), _delete = new DescTuple("delete", "deleting");
static readonly string _definition = "definition", _template = "template";
class Impl<T> : IActionMetadata<T> {
readonly DescTuple _desc;
readonly string _subject;
readonly Func<T, bool> _get_success;
readonly Func<T, string> _get_error_msg;
public Impl(DescTuple desc, string subject, Func<T, bool> get_success, Func<T, string> get_error_msg) {
_desc = desc;
_subject = subject;
_get_success = get_success;
_get_error_msg = get_error_msg;
}
public string desc => _desc.desc;
public string present_progressive_desc => _desc.present_progressive_desc;
public bool get_success(T reply) => _get_success(reply);
public string get_error_msg(T reply) => _get_error_msg(reply);
}
struct DescTuple {
public readonly string desc, present_progressive_desc;
public DescTuple(string desc, string present_progressive_desc) {
this.desc = desc;
this.present_progressive_desc = present_progressive_desc;
}
}
}
/// <summary>
/// The AlgoService protobuf types have been extracted out of the viewmodels (<see cref="AlgoStudioVM"/>, <see cref="OrderPropertiesEditorVM"/>, <see cref="AlgoDefinitionVM"/>, <see cref="AlgoDefinitionTemplateVM"/>).
/// The viewmodels instead use these types to represent the data: <see cref="AlgoData"/> is used in place of <see cref="CompositeAlgoRecordImmutable"/>, and <see cref="AlgoTemplateData"/> is used in place of <see cref="AlgoTemplateRecordImmutable"/>.
/// This thin abstraction isolates the server-side from the client-side, so if one day the server side types change, we won't need to change any client-side code except the methods below which handle the conversion from server type to corresponding client type.
/// There are a couple other methods in here as well (this is an extensions class afterall), but [John]I am going out of town soon (1/6/18) and did not get a chance to organize these methods beyond containing them in <see cref="Utils"/>.
/// </summary>
static class _Utils {
// AlgoTemplateImmutable custom_order_definition(i)
public static CustomOrderDefinitionImmutable custom_order_definitioni(AlgoTemplateImmutable templatei) {
switch (templatei.AlgoParamsCase) {
case AlgoTemplate.AlgoParamsOneofCase.CompositeAlgoParams: return templatei.CompositeAlgoParams.Algo;
case AlgoTemplate.AlgoParamsOneofCase.SystemAlgoParams: return templatei.SystemAlgoParams;
default: throw ExceptionBuilder.Argument.unexpected_case(templatei.AlgoParamsCase, nameof(templatei));
}
}
public static AlgoData definition_data(AlgoTemplateImmutable templatei) {
switch (templatei.AlgoParamsCase) {
case AlgoTemplate.AlgoParamsOneofCase.CompositeAlgoParams: return definition_data(templatei.CompositeAlgoParams);
case AlgoTemplate.AlgoParamsOneofCase.SystemAlgoParams:
return new AlgoData(
templatei.SystemAlgoParams,
templatei.SystemAlgoParams.CustomCase.display_name(),
get_key(templatei.SystemAlgoParams));
default: throw ExceptionBuilder.Argument.unexpected_case(templatei.AlgoParamsCase, nameof(templatei));
}
}
public static AlgoData definition_data(CompositeAlgoRecordImmutable recordi) => new AlgoData(recordi.AlgoDefinition.Algo, recordi.AlgoDefinition.Name, get_key(recordi));
public static AlgoData definition_data(CompositeAlgoDefinitionImmutable definitioni) =>
new AlgoData(definitioni.Algo, definitioni.Name, get_key(definitioni));
public static AlgoData? definition_data(Result<CompositeAlgoCreateResult> result) {
if (result.success && result.value.Success) {
var r = result.value.Record;
return new AlgoData(new CustomOrderDefinitionImmutable(r.AlgoDefinition.Algo), r.AlgoDefinition.Name, new AlgoKey(new AlgoPersistedKey(r.Key)));
} else return null;
}
// AlgoTemplateRecord(Immutable) template data
public static AlgoTemplateData template_data(AlgoTemplateRecord record) => template_data(new AlgoTemplateRecordImmutable(record));
public static AlgoTemplateData template_data(AlgoTemplateRecordImmutable recordi) => new AlgoTemplateData(custom_order_definitioni(recordi.AlgoTemplate), recordi.AlgoTemplate.Name, get_key(recordi), definition_data(recordi.AlgoTemplate));
public static CompositeAlgoDefinition to_definition(AlgoData definition_data) =>
new CompositeAlgoDefinition {
Name = definition_data.name,
Algo = definition_data.value.CloneToMutable()
};
// AlgoTemplateData to_record(i)
public static AlgoTemplateRecord to_record(AlgoTemplateData template) {
var record = new AlgoTemplateRecord {
AlgoTemplate = new AlgoTemplate {
Name = template.name,
CompositeAlgoParams = new CompositeAlgoDefinition {
Name = template.definition.name,
Algo = template.value.CloneToMutable()
}
}
};
set_key(ref record, template.key);
return record;
}
public static AlgoTemplateRecordImmutable to_recordi(AlgoTemplateData template) => new AlgoTemplateRecordImmutable(to_record(template));
// AlgoTemplateData to_template(i)
public static AlgoTemplate to_template(AlgoTemplateData template) =>
new AlgoTemplate {
Name = template.name,
CompositeAlgoParams = new CompositeAlgoDefinition {
Name = template.definition.name,
Algo = template.value.CloneToMutable()
}
};
public static AlgoTemplateImmutable to_templatei(AlgoTemplateData template) => new AlgoTemplateImmutable(to_template(template));
public static AlgoKey get_key(CompositeAlgoRecordImmutable recordi) => new AlgoKey(new AlgoPersistedKey(recordi.Key));
public static AlgoKey get_key(AlgoTemplateRecordImmutable recordi) => new AlgoKey(new AlgoPersistedKey(recordi.Key));
public static AlgoKey get_key(CompositeAlgoDefinitionImmutable definitioni) => new AlgoKey(new AlgoPersistedKey(definitioni.Name));
public static AlgoKey get_key(CustomOrderDefinitionImmutable custom_order_definitioni) => new AlgoKey(custom_order_definitioni.CustomCase);
public static void set_key(ref AlgoTemplateRecord record, AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Persisted:
switch (key.persisted.mode) {
case AlgoPersistedKey.Mode.String:
record.Key = key.persisted.id_string; break;
}
break;
}
}
public static void set_key(ref AlgoServiceRemoveRequest request, AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Persisted:
switch (key.persisted.mode) {
case AlgoPersistedKey.Mode.String:
request.Key = key.persisted.id_string; break;
}
break;
}
}
}
}
}
@@ -0,0 +1,120 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman.algo;
using bts.persist.algo;
using bts.spark;
using mbts.spark.utilities;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace mbts.spark {
class AlgoStudioFlatDefinitionModel : IAlgoStudioModel, IDisposable {
readonly AlgoDefinitionService _service;
readonly AdminModel _admin_model;
readonly ErrorReporter _error_reporter;
IReadOnlyDictionary<AlgoKey, AlgoData> _algos = DictionaryHelper.empty<AlgoKey, AlgoData>();
IReadOnlyDictionary<AlgoKey, AlgoTemplateData> _algo_templates = DictionaryHelper.empty<AlgoKey, AlgoTemplateData>();
IDisposable _dispose;
public AlgoStudioFlatDefinitionModel(AlgoDefinitionService service, IAlgoDefinitionMetadataService metadata_service, AdminModel admin_model, ErrorReporter error_reporter, bts.config.AlgoStudioOptions ui_configuration) {
_service = service;
this.metadata_service = metadata_service;
_admin_model = admin_model;
_error_reporter = error_reporter;
this.ui_configuration = ui_configuration;
definitions = service.subscribei_algo_definitions().Filter(r => r.Metadata.IsActive).SelectKeyValue(_definition_data, d => d.key).Table().Cache();
}
public IObservable<TableUpdate<AlgoData, AlgoKey>> definitions { get; }
public IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> templates => Observable.Empty<TableUpdate<AlgoTemplateData, AlgoKey>>();
public IAlgoDefinitionMetadataService metadata_service { get; }
public bts.config.AlgoStudioOptions ui_configuration { get; }
public IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> subscribe_definition_templates(AlgoKey definition_key) =>
Observable.Return(TableUpdate<AlgoTemplateData, AlgoKey>.mk_empty(t => t.key));
public async Task<AlgoData?> save_definition(AlgoData definition_data) {
if (_try_get_user(out uint user_id)) {
var (value, success) = await _error_reporter.safe_execute(() => _service.save_algo_definition_async(
_with_key(new AlgoDefinitionUpdateRequest { UserId = user_id, Algo = _template(definition_data) }, definition_data.key)),
r => r.Success, r => r.ErrorMessage, "saving template");
if (success)
return _definition_data(new AlgoDefinitionRecordImmutable(value.Record));
} else {
_report_no_user_id("save template");
}
return null;
}
public async Task<bool> remove_definition(AlgoKey definition_key) {
var req = new AlgoDefinitionRemoveRequest();
_set_key(ref req, definition_key);
(AlgoDefinitionRemoveResponse resp, bool success) = await _error_reporter.safe_execute(() => _service.remove_algo_definition_async(req), r => r.Success, r => r.ErrorMessage, "remove template");
return success;
}
public Task<AlgoTemplateData?> save_template(AlgoTemplateData template_data) => Task.FromResult((AlgoTemplateData?)null);
public Task<bool> remove_template(AlgoKey key) =>
Task.FromResult(false);
public void Dispose() =>
Disposable.dispose(ref _dispose);
static AlgoDefinition _template(AlgoData definition_data) =>
new AlgoDefinition { Name = definition_data.name, Definition = definition_data.value.CloneToMutable() };
static AlgoDefinitionImmutable _templatei(AlgoData definition_data) =>
new AlgoDefinitionImmutable(_template(definition_data));
static AlgoData _definition_data(AlgoDefinitionRecordImmutable recordi) =>
new AlgoData(recordi.Algo.Definition, recordi.Algo.Name, _key(recordi));
static AlgoKey _key(AlgoDefinitionRecordImmutable recordi) =>
new AlgoKey(new AlgoPersistedKey(recordi.Key));
static AlgoDefinitionUpdateRequest _with_key(AlgoDefinitionUpdateRequest request, AlgoKey key) {
_set_key(ref request, key);
return request;
}
static void _set_key(ref AlgoDefinitionUpdateRequest request, AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Persisted: request.Key = key.persisted.id_uint; break;
case AlgoKey.Mode.Unpersisted:
case AlgoKey.Mode.Factory:
case AlgoKey.Mode.None: request.Key = 0; break;
default: throw ExceptionBuilder.Argument.unexpected_case(key.mode, nameof(key));
}
}
static void _set_key(ref AlgoDefinitionRemoveRequest request, AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Persisted: request.Key = key.persisted.id_uint; break;
default: throw ExceptionBuilder.Argument.unexpected_case(key.mode, nameof(key));
}
}
void _report_error(string present_progressive_desc, string msg) =>
_error_reporter.report_error($"Error {present_progressive_desc}: {msg}", AlgoStudioWindow.NAME, System.Windows.MessageBoxImage.Warning);
void _report_no_user_id(string desc) =>
_error_reporter.report_error($"{desc} failed: did not find current user id");
bool _try_get_user(out uint id) {
var user = _admin_model.get_current_user();
if (user.HasValue) {
id = user.Value.id;
return true;
} else {
id = 0;
return false;
}
}
}
}
@@ -0,0 +1,20 @@
using bts.api.orderman;
namespace mbts.spark {
struct AlgoTemplateData {
public readonly CustomOrderDefinitionImmutable value;
public readonly string name;
public readonly AlgoKey key;
public readonly AlgoData definition;
public AlgoTemplateData(CustomOrderDefinitionImmutable value, string name, AlgoKey key, AlgoData definition) {
this.value = value;
this.name = name;
this.key = key;
this.definition = definition;
}
public AlgoKey definition_key => definition.key;
public string definition_name => definition.name;
}
}
@@ -0,0 +1,53 @@
using bts;
using bts.api;
using bts.api.core;
using bts.spark;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
namespace mbts.spark {
interface IAlgoStudioModel {
IObservable<TableUpdate<AlgoData, AlgoKey>> definitions { get; }
IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> templates { get; }
IObservable<TableUpdate<AlgoTemplateData, AlgoKey>> subscribe_definition_templates(AlgoKey definition_key);
IAlgoDefinitionMetadataService metadata_service { get; }
Task<AlgoData?> save_definition(AlgoData definition_data);
Task<AlgoTemplateData?> save_template(AlgoTemplateData template_data);
Task<bool> remove_definition(AlgoKey definition_key);
Task<bool> remove_template(AlgoKey template_key);
bts.config.AlgoStudioOptions ui_configuration { get; }
}
class AlgoStudioModelExporter {
[ImportingConstructor]
AlgoStudioModelExporter(Spark.AlgoServiceWrapper service_wrapper, IAlgoDefinitionMetadataService meta, AdminModel admin_model, ErrorReporter error_reporter) {
var ui_configuration = config.Configuration.get<bts.config.AlgoStudioOptions>();
switch (service_wrapper.mode) {
case Spark.AlgoServiceWrapper.Mode.Flat: model = new AlgoStudioFlatDefinitionModel(service_wrapper.flat, meta, admin_model, error_reporter, ui_configuration); break;
case Spark.AlgoServiceWrapper.Mode.Hierarchical: model = new AlgoStudioDefinitionTemplateModel(service_wrapper.hierarhical, meta, admin_model, error_reporter, ui_configuration); break;
}
}
[Export]
public IAlgoStudioModel model { get; }
}
static class AlgoStudioModelUtils {
public static bool templates_enabled(this IAlgoStudioModel model) =>
get_templates_enabled(model.ui_configuration);
public static bool get_templates_enabled(bts.config.AlgoStudioOptions ui_configuration) =>
ui_configuration.add_template_button != bts.config.AlgoStudioOptions.AddTemplateButton.None;
public static IReadOnlyDictionary<object, object> get_dynamic_resources(bts.config.AlgoStudioOptions ui_configuration) =>
new Dictionary<object, object> {
{ AlgoStudioWindow.ShowAlgoToolBarRenameDefinitionKey, ui_configuration.can_modify_definition_name && ui_configuration.show_algo_toolbar_rename },
{ AlgoStudioWindow.ShowAlgoToolBarSaveDefinitionKey, ui_configuration.can_modify_definition_values && ui_configuration.show_algo_toolbar_save },
{ AlgoStudioWindow.ShowAlgoToolBarRevertDefinitionKey, ui_configuration.show_algo_toolbar_revert },
{ AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey, ui_configuration.show_algo_toolbar_undo_redo },
{ AlgoStudioWindow.TemplatesEnabledKey, get_templates_enabled(ui_configuration) }
};
}
}
@@ -0,0 +1,78 @@
using bts.persist.algo;
using bts.proto;
using bts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.spark {
/// <summary>
/// This class may be identitical to <see cref="AlgoDefinitionPersistedMetadata"/> in every way but name; the reason both exist is to
/// decouple the client-side key type from the server-side one, so both key types may evolve independently moving forward.
/// </summary>
struct AlgoDefinitionMetadata : IEquatable<AlgoDefinitionMetadata> {
public readonly AlgoKey id, default_template;
readonly AlgoKey[] _favorite_templates;
public readonly bool is_favorite, is_hidden;
public readonly string abbreviation;
public readonly System.Windows.Media.Color? badge_color;
public AlgoDefinitionMetadata(AlgoKey id)
: this(id, default, default, default, default, default, default) { }
public AlgoDefinitionMetadata(AlgoKey id, AlgoKey default_template, AlgoKey[] favorite_templates, bool is_favorite, bool is_hidden, string abbreviation, System.Windows.Media.Color? badge_color) {
this.id = id;
this.default_template = default_template;
_favorite_templates = favorite_templates;
this.is_favorite = is_favorite;
this.is_hidden = is_hidden;
this.abbreviation = abbreviation;
this.badge_color = badge_color;
}
public IReadOnlyList<AlgoKey> favorite_templates => _favorite_templates ?? Array.Empty<AlgoKey>();
internal AlgoDefinitionPersistedMetadata to_persisted() =>
id.mode != AlgoKey.Mode.Persisted ?
throw new InvalidOperationException("Metadata does not have a persisted key.") :
new AlgoDefinitionPersistedMetadata(id.persisted,
default_template.mode == AlgoKey.Mode.Persisted ? default_template.persisted : default,
favorite_templates.Where(t => t.mode == AlgoKey.Mode.Persisted).Select(t => t.persisted).ToArray(),
is_favorite, is_hidden, abbreviation, new NullableColorProto(badge_color));
public AlgoDefinitionMetadata with(AlgoKey? id = null, AlgoKey? default_template = null, IEnumerable<AlgoKey> favorite_templates = null, bool? is_favorite = null, bool? is_hidden = null, string abbreviation = null, NullableColorProto? badge_color = null) =>
new AlgoDefinitionMetadata(
id ?? this.id,
default_template ?? this.default_template,
favorite_templates == null ? _favorite_templates : favorite_templates.ToArray(),
is_favorite ?? this.is_favorite,
is_hidden ?? this.is_hidden,
abbreviation ?? this.abbreviation,
badge_color.HasValue ? badge_color.Value.value : this.badge_color);
public bool Equals(AlgoDefinitionMetadata other) =>
id == other.id &&
default_template == other.default_template &&
is_favorite == other.is_favorite &&
is_hidden == other.is_hidden &&
abbreviation == other.abbreviation &&
badge_color == other.badge_color &&
favorite_templates.SequenceEqual(other.favorite_templates);
public override bool Equals(object obj) =>
EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
id.GetHashCode(),
default_template.GetHashCode(),
is_favorite.GetHashCode(),
is_hidden.GetHashCode(),
abbreviation == null ? 0 : abbreviation.GetHashCode(),
badge_color?.GetHashCode() ?? 0,
EqualityComparer.aggregate_hash_limited(_favorite_templates));
public static bool operator ==(AlgoDefinitionMetadata a, AlgoDefinitionMetadata b) => a.Equals(b);
public static bool operator !=(AlgoDefinitionMetadata a, AlgoDefinitionMetadata b) => !a.Equals(b);
}
}
@@ -0,0 +1,82 @@
using bts.proto;
using bts.utils;
using mbts.spark;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.persist.algo {
/// <summary>
/// This class may be identitical to <see cref="AlgoDefinitionMetadata"/> in every way but name; the reason both exist is to
/// decouple the client-side key type from the server-side one, so both key types may evolve independently moving forward.
/// </summary>
[ProtoContract]
struct AlgoDefinitionPersistedMetadata : IEquatable<AlgoDefinitionPersistedMetadata> {
[ProtoMember(1)]
public readonly AlgoPersistedKey id;
[ProtoMember(2)]
public readonly AlgoPersistedKey default_template;
[ProtoMember(3)]
readonly AlgoPersistedKey[] _favorite_templates;
[ProtoMember(4)]
public readonly bool is_favorite;
[ProtoMember(5)]
public readonly bool is_hidden;
[ProtoMember(6)]
public readonly string abbreviation;
[ProtoMember(7)]
public readonly NullableColorProto badge_color;
public AlgoDefinitionPersistedMetadata(AlgoPersistedKey id)
: this(id, default, default, default, default, default, default) { }
public AlgoDefinitionPersistedMetadata(AlgoPersistedKey id, AlgoPersistedKey default_template, AlgoPersistedKey[] favorite_templates, bool is_favorite, bool is_hidden, string abbreviation, NullableColorProto badge_color) {
this.id = id;
this.default_template = default_template;
_favorite_templates = favorite_templates;
this.is_favorite = is_favorite;
this.is_hidden = is_hidden;
this.abbreviation = abbreviation;
this.badge_color = badge_color;
}
public IReadOnlyList<AlgoPersistedKey> favorite_templates => _favorite_templates ?? Array.Empty<AlgoPersistedKey>();
public AlgoDefinitionMetadata to_definition_data() =>
new AlgoDefinitionMetadata(id.to_algo_key(), default_template.to_algo_key(), ArrayHelper.safe_convert(_favorite_templates, k => k.to_algo_key()), is_favorite, is_hidden, abbreviation, badge_color.value);
public AlgoDefinitionPersistedMetadata with(AlgoPersistedKey? default_template = null, IEnumerable<AlgoPersistedKey> favorite_templates = null, bool? is_favorite = null, bool? is_hidden = null, string abbreviation = null, NullableColorProto? badge_color = null) =>
new AlgoDefinitionPersistedMetadata(id,
default_template ?? this.default_template,
favorite_templates == null ? _favorite_templates : favorite_templates.ToArray(),
is_favorite ?? this.is_favorite,
is_hidden ?? this.is_hidden,
abbreviation ?? this.abbreviation,
badge_color ?? this.badge_color);
public bool Equals(AlgoDefinitionPersistedMetadata other) =>
id == other.id &&
default_template == other.default_template &&
is_favorite == other.is_favorite &&
is_hidden == other.is_hidden &&
abbreviation == other.abbreviation &&
badge_color == other.badge_color &&
favorite_templates.SequenceEqual(other.favorite_templates);
public override bool Equals(object obj) =>
EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
id.GetHashCode(),
default_template.GetHashCode(),
is_favorite.GetHashCode(),
is_hidden.GetHashCode(),
abbreviation == null ? 0 : abbreviation.GetHashCode(),
EqualityComparer.aggregate_hash_limited(_favorite_templates));
public static bool operator ==(AlgoDefinitionPersistedMetadata a, AlgoDefinitionPersistedMetadata b) => a.Equals(b);
public static bool operator !=(AlgoDefinitionPersistedMetadata a, AlgoDefinitionPersistedMetadata b) => !a.Equals(b);
}
}
@@ -0,0 +1,106 @@
using bts.persist.algo;
using bts.proto;
using bts.utils;
using mbts;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Reactive.Subjects;
using System.Threading.Tasks;
namespace bts {
interface IAlgoDefinitionMetadataService {
IObservable<IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata>> subscribe_metadata();
IObservable<AlgoDefinitionMetadata> subscribe_metadata(AlgoKey definition_key);
Task update_metadata(AlgoKey definition, Func<AlgoDefinitionMetadata, AlgoDefinitionMetadata> update);
}
static class AlgoDefinitionMetadataServiceExtensions {
public static Task add_to_favorites(this IAlgoDefinitionMetadataService service, AlgoKey definition) =>
service.update_metadata(definition, d => d.with(is_favorite: true));
public static Task add_to_favorites(this IAlgoDefinitionMetadataService service, AlgoKey definition, AlgoKey template) =>
service.update_metadata(definition, m => m.with(favorite_templates: ListUtils.add_distinct(m.favorite_templates, template)));
public static Task remove_from_favorites(this IAlgoDefinitionMetadataService service, AlgoKey definition) =>
service.update_metadata(definition, d => d.with(is_favorite: false));
public static Task remove_from_favorites(this IAlgoDefinitionMetadataService service, AlgoKey definition, AlgoKey template) =>
service.update_metadata(definition, m => m.with(favorite_templates: ListUtils.remove(m.favorite_templates, template)));
public static Task set_as_default(this IAlgoDefinitionMetadataService service, AlgoKey definition, AlgoKey template) =>
service.update_metadata(definition, m => m.with(default_template: template));
public static Task hide_definition(this IAlgoDefinitionMetadataService service, AlgoKey definition) =>
service.update_metadata(definition, m => m.with(is_hidden: true));
public static Task show_definition(this IAlgoDefinitionMetadataService service, AlgoKey definition) =>
service.update_metadata(definition, m => m.with(is_hidden: false));
public static Task set_badge_color(this IAlgoDefinitionMetadataService service, AlgoKey definition, NullableColorProto badge_color) =>
service.update_metadata(definition, m => m.with(badge_color: badge_color));
}
/// <summary>
/// An <see cref="IUserPersist"/> based implementation of <see cref="IAlgoDefinitionMetadataService"/>.
/// </summary>
[Export(typeof(IInitializable))]
[Export(typeof(IAlgoDefinitionMetadataService))]
class AlgoTemplateMetadataService : IAlgoDefinitionMetadataService, IInitializable {
const string _namespace = "algo_templates", _name = "metadata";
readonly IUserPersist _persist;
readonly Dictionary<AlgoKey, AlgoDefinitionMetadata> _data = new Dictionary<AlgoKey, AlgoDefinitionMetadata>();
readonly BehaviorSubject<IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata>> _subject = new BehaviorSubject<IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata>>(new Dictionary<AlgoKey, AlgoDefinitionMetadata>());
readonly ObservableDemuxer<AlgoKey, AlgoDefinitionMetadata> _metadata_demuxer = new ObservableDemuxer<AlgoKey, AlgoDefinitionMetadata>();
[ImportingConstructor]
AlgoTemplateMetadataService(IUserPersist persist) {
_persist = persist;
_subject.Subscribe(_metadata_demuxer);
}
int IInitializable.priority => int.MaxValue;
public IObservable<IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata>> subscribe_metadata() => _subject;
public IObservable<AlgoDefinitionMetadata> subscribe_metadata(AlgoKey definition) =>
_metadata_demuxer.subscribe(definition);
public async Task update_metadata(AlgoKey definition, Func<AlgoDefinitionMetadata, AlgoDefinitionMetadata> update_meta_factory) =>
await Task.Run(() => _update_metadata(definition, update_meta_factory));
void _broadcast() =>
_subject.OnNext(new Dictionary<AlgoKey, AlgoDefinitionMetadata>(_data));
void _update_metadata(AlgoKey definition, Func<AlgoDefinitionMetadata, AlgoDefinitionMetadata> update_meta_factory) {
lock (_data) {
if (!_data.TryGetValue(definition, out AlgoDefinitionMetadata orig_meta))
orig_meta = new AlgoDefinitionMetadata(definition);
AlgoDefinitionMetadata new_meta = update_meta_factory(orig_meta);
if (new_meta != orig_meta) {
_data[definition] = new_meta;
_broadcast();
_persist.try_set(_namespace, _name,
ArrayHelper.convert(_data.Values, d => d.to_persisted()))
.ignore();
}
}
}
async void IInitializable.initialize() {
(var success, var meta_array, var error) = await _persist.try_get<AlgoDefinitionPersistedMetadata[]>(_namespace, _name);
if (success && meta_array != null) {
lock (_data) {
_data.Clear();
foreach (var m in meta_array)
_data[m.id.to_algo_key()] = m.to_definition_data();
_broadcast();
}
}
}
}
}
@@ -0,0 +1,62 @@
using bts.api.core;
using bts.utils;
using mbts.collections;
using mbts.ui.utilities;
using mbts.utils;
using System;
using System.Collections.Generic;
namespace mbts.spark {
static class AlgoCollectionHelper {
public static readonly IComparer<AlgoDefinitionVM> algo_definition_vm_comparer =
new ComparerBuilder<AlgoDefinitionVM>(
new [] {
Comparer<AlgoDefinitionVM>.Create(_CompareUtils.compare_modes),
Comparer<AlgoDefinitionVM>.Create(_CompareUtils.compare_names)
}).to_comparer().to_safe();
public static readonly IComparer<IAlgoVM> algo_vm_comparer =
new ComparerBuilder<IAlgoVM>(
new [] {
Comparer<IAlgoVM>.Create(_CompareUtils.compare_modes),
Comparer<IAlgoVM>.Create(_CompareUtils.compare_names)
}).to_comparer().to_safe();
public static void update_persisted_definitions(ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey> target, TableUpdate<AlgoData, AlgoKey> update, Func<AlgoData, AlgoDefinitionVM> factory) {
foreach (var d in update.removed)
target.Remove(d.key);
foreach (var d in update.changed)
target[d.key].load(d);
foreach (var d in update.added) {
if (target.TryGetValue(d.key, out AlgoDefinitionVM def)) {
def.load(d);
} else target.Add(factory(d));
}
}
static class _CompareUtils {
public static int compare_modes(AlgoDefinitionVM a, AlgoDefinitionVM b) =>
_compare_modes(a.key.mode, b.key.mode);
public static int compare_modes(IAlgoVM a, IAlgoVM b) =>
_compare_modes(a.id.mode, b.id.mode);
public static int compare_names(AlgoDefinitionVM a, AlgoDefinitionVM b) =>
DisplayNameHelper.compare_alpha_numeric(a.name, b.name);
public static int compare_names(IAlgoVM a, IAlgoVM b) =>
DisplayNameHelper.compare_alpha_numeric(a.display_name, b.display_name);
static int _compare_modes(AlgoKey.Mode a, AlgoKey.Mode b) {
// Factory mode is 'lowest', consider all other modes equivalent.
if (a == AlgoKey.Mode.Factory) {
if (b != AlgoKey.Mode.Factory)
return -1;
} else if (b == AlgoKey.Mode.Factory) {
return 1;
}
return 0;
}
}
}
}
@@ -0,0 +1,243 @@
using bts;
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using System.Windows.Input;
using VisualStateNames = mbts.ui.spark.AlgoStudioView.VisualStateNames;
namespace mbts.spark {
class AlgoDefinitionTemplateVM : DisposableViewModelBase, IAlgoStudioContentVM, IEquatable<AlgoDefinitionTemplateVM> {
/// <see cref="CustomType"/> is referenced by an x:Static extension in OrderDetailsPopupControl.xaml <see cref="mbts.ui.spark.algo.OrderDetailsPopupControl"/>.
/// In most cases, <see cref="mbts.ui.NestedExtension"/> works just like <see cref="System.Windows.Markup.TypeExtension"/>, but for nested types, such as <see cref="CustomTemplatePlaceholderVM"/>.
/// However, when the former is used to denote the DataType of a DataTemplate, a strange XamlReader exception is thrown at runtime.
/// After spending ~15 minutes investigating what was happening, [John]I decided it was more trouble than it was worth and opted for this workaround.
public static readonly Type CustomType = typeof(CustomTemplatePlaceholderVM);
readonly OrdersModel _model;
readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel();
/// Note: the difference between <see cref="EditStack{T}"/> and <see cref="VersionContainer{T}"/> is that the former implements push/pop functionality so the user may undo/redo (like ctrl+z/ctrl+y in text editors),
/// while the latter is a lazy delegate-based container for the most recent value (<see cref="VersionContainer{T}.increment_version"/>).
readonly EditStack<Snapshot> _edit_stack = new EditStack<Snapshot>();
readonly VersionContainer<Snapshot> _version;
readonly DeferrableActionWrapper _refresh_on_local_change;
readonly Property<IAlgoVM> _algo_root;
readonly DelegateProperty<bool> _can_undo, _can_redo, _is_dirty;
readonly Property<bool> _is_default, _is_favorite, _is_selected;
readonly Property<string> _name, _abbreviation;
// maintains the state of each algo-root, so the user may change the definition root back and forth without any loss of state amongst the templates
Snapshot _committed;
public AlgoDefinitionTemplateVM(AlgoDefinitionVM owner, OrdersModel model, AlgoData data, AlgoEditingPermissions editing_permissions = AlgoEditingPermissions.AllowEditValues) {
// init core data
this.owner = owner;
_model = model;
key = data.key;
_version = new VersionContainer<Snapshot>(_snapshot);
// maintain states for different algo roots, so they aren't lost when the user changes the root algo type
var algo_map = new Dictionary<AlgoKey, IAlgoVM> {
{ data.key, algo_vm_factory(data.value) }
};
// init backing props
_name = backing(nameof(this.name), name);
_abbreviation = backing(nameof(abbreviation), string.Empty);
_is_default = backing(nameof(is_default), false);
_is_favorite = backing(nameof(is_favorite), false);
_is_selected = backing(nameof(is_selected), false);
_algo_root = backing(nameof(algo_root), get_algo_root(owner.algo_root));
_committed = _version.value;
_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));
_is_dirty = backing(nameof(is_dirty), () => !_committed.Equals(_version.value));
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
set_as_default_cmd = new DelegateCommand(() => {
if (!is_default && key.mode == AlgoKey.Mode.Persisted)
_model.algo_model.metadata_service.set_as_default(owner.key, key).ignore();
});
// init visual states
// TODO: implement these features in IAlgoMetadataService; until then, set the appropriate visual states.
_edit_pane_vs_model.set_state(VisualStateNames.Abbreviation.GroupName, VisualStateNames.Abbreviation.NotSupportedForTemplates);
_tree_view_vs_model.set_state(VisualStateNames.FavoriteToggleButton.GroupName, VisualStateNames.FavoriteToggleButton.Inactive);
switch (key.mode) {
case AlgoKey.Mode.Persisted:
_edit_stack.push(_committed);
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active);
break;
case AlgoKey.Mode.Unpersisted: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active); break;
case AlgoKey.Mode.Factory: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive); break;
}
// set hooks/subscriptions
_refresh_on_local_change = new DeferrableActionWrapper(on_local_changed);
_dispose = new System.Reactive.Disposables.CompositeDisposable(
as_demuxer().subscribe_many(_refresh_on_local_change.execute, nameof(name), nameof(abbreviation), nameof(is_default), nameof(is_favorite)),
owner.observe_algo_root().Subscribe(r => _algo_root.set(get_algo_root(r))),
_algo_root.observe_current(true).SelectManyInSeries(r => r?.subscribe_definition()).RefCount().Subscribe(_ => _refresh_on_local_change.execute()),
Disposable.wrap_collection(algo_map.Values)) {
() => {
_can_redo.Changed -= on_can_redo_changed;
_can_undo.Changed -= on_can_undo_changed;
}
};
// local methods
IAlgoVM algo_vm_factory(CustomOrderDefinitionImmutable def) => OrderTypeVMFactory.create(new AlgoData(def, def.CustomCase.display_name(), OrderDataHelper.get_shallow_factory_key(def)), editing_permissions);
IAlgoVM get_algo_root(IAlgoVM owner_root) {
var key = new AlgoKey(owner_root.order_type);
if (algo_map.TryGetValue(key, out IAlgoVM vm)) {
vm.load_structure(owner_root.definition);
} else {
vm = algo_map.GetOrAdd(key, ot => algo_vm_factory(owner_root.definition));
}
return vm;
}
void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke();
void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke();
void on_local_changed() {
_version.increment_version();
_edit_stack.push_distinct(_version.value);
_is_dirty.refresh();
_refresh_undo_redo();
}
}
public event Action can_redo_changed, can_undo_changed;
public event PropertyChange<IAlgoVM> algo_root_changed { add => _algo_root.Changed += value; remove => _algo_root.Changed -= value; }
public AlgoDefinitionVM owner { get; }
public AlgoKey owner_key => owner.key;
public AlgoKey key { get; }
public string name { get => _name.Value; set => _name.set(value); }
public string abbreviation { get => _abbreviation.Value; set => _abbreviation.set(value); }
public bool is_dirty => _is_dirty.Value;
public bool can_redo => _can_redo.Value;
public bool can_undo => _can_undo.Value;
public bool is_default => _is_default.Value;
public bool is_favorite { get => _is_favorite.Value; set => _is_favorite.set(value); }
public IAlgoVM algo_root => _algo_root.Value;
public virtual bool is_custom_placeholder => false;
public bool is_selected { get => _is_selected.Value; set => _is_selected.set(value); }
public bool is_expanded => false;
public bool is_persisted => key.mode == AlgoKey.Mode.Persisted;
public ObservableCollection<string> edit_pane_visual_states => _edit_pane_vs_model.states;
public ObservableCollection<string> tree_view_visual_states => _tree_view_vs_model.states;
public ICommand set_as_default_cmd { get; }
public IObservable<bool> observe_is_dirty() => _is_dirty.observe_current(true);
public void undo() => _restore(_edit_stack.try_undo);
public void redo() => _restore(_edit_stack.try_redo);
public void on_meta(bool is_default, bool is_favorite) {
_is_default.set(is_default);
_is_favorite.set(is_favorite);
}
public AlgoData create_def_data() =>
new AlgoData(algo_root.definition, name, key);
public AlgoTemplateData create() =>
create(owner.create_algo_def());
public AlgoTemplateData create(AlgoData record) {
if (!OrderDataHelper.EqualsHelpers.structure_equals(algo_root.definition, record.value))
throw new InvalidOperationException("AlgoTemplate's algo structure does not match that of its parent.");
return new AlgoTemplateData(algo_root.definition, name, key, record);
}
public AlgoDefinitionTemplateVM to_persisted(AlgoDefinitionVM persisted_owner, AlgoData template) =>
new AlgoDefinitionTemplateVM(persisted_owner, _model, template);
public void load_committed() => _load_from(_committed.name, _committed.definition, true);
public void load_from(AlgoTemplateData value) {
if (key.mode != AlgoKey.Mode.Persisted)
throw new InvalidOperationException("AlgoStructure has not been saved yet.");
else if (value.key != key)
throw new InvalidOperationException("Value id does not match this id.");
_load_from(value.name, value.value, true);
}
public bool Equals(AlgoDefinitionTemplateVM other) => other != null && key == other.key;
public override bool Equals(object obj) => Equals(obj as AlgoDefinitionTemplateVM);
public override int GetHashCode() => key.GetHashCode();
void _load_from(string new_name, CustomOrderDefinitionImmutable new_def, bool update_committed) {
using (_refresh_on_local_change.defer_execution()) {
name = new_name;
algo_root.load_from(new_def);
}
if (update_committed) {
_committed = _version.value;
_is_dirty.refresh();
}
}
void _refresh_undo_redo() {
_can_redo.refresh();
_can_undo.refresh();
}
void _restore(TryGetValue<Snapshot> try_get_snapshot) {
while (try_get_snapshot(out Snapshot next_state)) {
if (!_version.value.Equals(next_state)) {
_load_from(next_state.name, next_state.definition, false);
break;
}
}
}
Snapshot _snapshot() =>
new Snapshot(name, abbreviation, algo_root?.definition ?? new CustomOrderDefinitionImmutable(new CustomOrderDefinition()), is_default, is_favorite);
struct Snapshot : IEquatable<Snapshot> {
public readonly string name, abbreviation;
public readonly CustomOrderDefinitionImmutable definition;
public readonly bool is_default, is_favorite;
public Snapshot(string name, string abbreviation, CustomOrderDefinitionImmutable definition, bool is_default, bool is_favorite) {
this.name = name;
this.abbreviation = abbreviation;
this.definition = definition;
this.is_default = is_default;
this.is_favorite = is_favorite;
}
public bool Equals(Snapshot other) =>
name == other.name &&
abbreviation == other.abbreviation &&
is_default == other.is_default &&
is_favorite == other.is_favorite &&
OrderDataHelper.EqualsHelpers.equals(definition, other.definition);
public override bool Equals(object obj) =>
EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
EqualityComparer.safe_aggregate_hash(name),
EqualityComparer.safe_aggregate_hash(abbreviation),
is_default.GetHashCode(),
is_favorite.GetHashCode(),
OrderDataHelper.EqualsHelpers.custom_order_def_compareri.GetHashCode(definition));
public static bool operator ==(Snapshot a, Snapshot b) => a.Equals(b);
public static bool operator !=(Snapshot a, Snapshot b) => !a.Equals(b);
}
public class CustomTemplatePlaceholderVM : AlgoDefinitionTemplateVM {
const string _custom_name = "(Custom)";
public CustomTemplatePlaceholderVM(AlgoDefinitionVM owner, OrdersModel model, CustomOrderDefinitionImmutable definition)
: base(owner, model, new AlgoData(definition, _custom_name, new AlgoKey(Guid.NewGuid())), AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowEditValues) {
_edit_stack.reset(_snapshot());
}
public override bool is_custom_placeholder => true;
}
}
}
@@ -0,0 +1,467 @@
using bts.api.core;
using bts.api.orderman;
using bts.proto;
using bts.utils;
using mbts.collections;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.controls.color_picker;
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.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Data;
using System.Windows.Media;
using VisualStateNames = mbts.ui.spark.AlgoStudioView.VisualStateNames;
namespace mbts.spark {
public enum AlgoFormats {
None = 0,
Exchange = 1,
Spreader = 1 << 1,
DefaultPlaceholder = 1 << 2
}
class AlgoDefinitionVM : DisposableViewModelBase, IAlgoStudioContentVM, IAlgoSelector, IEquatable<AlgoDefinitionVM> {
public const string new_algo_name = "New Algo", new_template_name = "New Template";
public static readonly CustomOrderDefinitionImmutable new_algo_def = OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase.Iceberg);
readonly OrdersModel _model;
readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel();
readonly ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoKey> _templates = new ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoKey>(t => t.key);
readonly EditStack<Snapshot> _edit_stack = new EditStack<Snapshot>();
readonly VersionContainer<Snapshot> _version;
readonly Property<bool> _is_expanded, _is_selected;
readonly Property<IAlgoVM> _algo_root, _visible_algo_root;
readonly Property<AlgoDefinitionTemplateVM> _selected_template;
readonly DelegateProperty<bool> _is_favorite, _is_dirty, _can_undo, _can_redo;
readonly Property<string> _name, _abbreviation;
readonly ObservableKeyedCollection<IAlgoVM, AlgoKey> _algo_roots = new ObservableKeyedCollection<IAlgoVM, AlgoKey>(vm => vm.id);
readonly ObservableAppendCollection<AlgoDefinitionTemplateVM> _templates_with_custom;
readonly DeferrableActionWrapper _refresh_on_local_changes;
readonly ReactiveThresholdMonitor<AlgoDefinitionTemplateVM> _any_templates_dirty_monitor = new ReactiveThresholdMonitor<AlgoDefinitionTemplateVM>(t => t.observe_is_dirty());
readonly Property<AlgoFormats> _selected_format;
AlgoEditingPermissions _editing_permissions;
int? _favorite_index;
Brush _badge_fill;
Snapshot? _committed;
AlgoDefinitionMetadata _metadata;
TableUpdateBuffer<AlgoTemplateData, AlgoKey> _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);
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);
AlgoDefinitionVM(OrdersModel model, AlgoData def_data, AlgoFormats init_format = AlgoFormats.Exchange) {
// init core data
_model = model;
key = def_data.key;
algos_view = ObservableAutoWrapper.create_sorted_wrapper(_algo_roots, AlgoCollectionHelper.algo_vm_comparer);
_template_update_buffer = new TableUpdateBuffer<AlgoTemplateData, AlgoKey>(t => t.key);
_templates_with_custom = new ObservableAppendCollection<AlgoDefinitionTemplateVM>(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>(_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);
_selected_format = backing(nameof(selected_format), init_format);
_selected_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_template));
_is_favorite = backing(nameof(is_favorite), () => _favorite_index.HasValue);
_is_expanded = backing(nameof(is_expanded), true);
_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)));
_visible_algo_root = backing<IAlgoVM>(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));
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
_refresh_on_local_changes = new DeferrableActionWrapper(on_local_changed);
// load initial state
init_async();
async void init_async() {
// visible_algo_root is selected_template.algo_root if user can add templates, otherwise algo_root
// - this behavior is configurable in 'AlgoStudioOptions' in UI.proto (01/28/2018)
if (_model.algo_model.templates_enabled()) {
resources.Add(_selected_template.observe_current(true).Subscribe(t => _visible_algo_root.set(t?.algo_root)));
} else {
resources.Add(_algo_root.observe_current(true).Subscribe(_visible_algo_root.set));
}
// init tree view item visual state
_tree_view_vs_model.set_state(VisualStateNames.TreeViewBadge.GroupName, conf.show_badges_in_tree_view ? VisualStateNames.TreeViewBadge.Active : VisualStateNames.TreeViewBadge.Inactive);
// set hooks/subscriptions
using (_refresh_on_local_changes.supress_execution()) {
resources.AddRange(
custom_badge_color.observe_nullable(true).Subscribe(v => Set(ref _badge_fill, (v ?? algo_root.safe_get_badge_color()).to_brush(), nameof(badge_fill))),
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;
if (vm is ILazyAlgo la) {
bool synced_with_loaded = false;
return vm.subscribe_definition().Subscribe(_ => {
if (la.is_loaded) {
if (!synced_with_loaded) {
synced_with_loaded = true;
_version.increment_version();
_on_committed_changed();
} else {
_refresh_on_local_changes.execute();
}
} else {
synced_with_loaded = false;
}
});
}
return vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.execute());
}),
ObservableAutoWrapper.connect_item_hooks(algo_roots, a => a as IDisposable ?? Disposable.empty, true),
ObservableAutoWrapper.connect_item_hooks(templates, t => new CompositeDisposable(_any_templates_dirty_monitor.join(t), t), true),
Disposable.Create(() => {
_can_redo.Changed -= on_can_redo_changed;
_can_undo.Changed -= on_can_undo_changed;
}));
switch (key.mode) {
case AlgoKey.Mode.Persisted:
_metadata = new AlgoDefinitionMetadata(key);
resources.Add(_template_update_buffer.OnDispatcher().Subscribe(_on_templates));
resources.Add(model.algo_model.metadata_service.subscribe_metadata(key).OnDispatcher().Subscribe(_on_metadata));
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, conf.can_modify_definition_name ? VisualStateNames.Name.Active : VisualStateNames.Name.CannotRenameDefinition);
break;
case AlgoKey.Mode.Factory:
_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);
}
}));
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);
_on_committed_changed();
}
}
// 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() {
_version.increment_version();
if (algo_root != null)
_edit_stack.push_distinct(_version.value);
_is_dirty.refresh();
_refresh_undo_redo();
}
}
// events
public event Action can_redo_changed, can_undo_changed;
public event PropertyChange<IAlgoVM> algo_root_changed { add => _algo_root.Changed += value; remove => _algo_root.Changed -= value; }
// properties
public AlgoKey key { get; }
public string name { get => _name.Value; set => _name.set(value); }
public string abbreviation { get => _abbreviation.Value; set => _abbreviation.set(value); }
public ObservableCollection<IAlgoVM> algo_roots => _algo_roots;
public IReadOnlyObservableCollection<IAlgoVM> algos_view { get; }
public IAlgoVM algo_root { get => _algo_root.Value; set => _algo_root.set(value); }
public IAlgoVM visible_algo_root => _visible_algo_root.Value;
public AlgoDefinitionTemplateVM selected_template { get => _selected_template.Value; set => _selected_template.set(value); }
public int? favorite_index {
get => _favorite_index;
set {
if (Set(ref _favorite_index, value))
_is_favorite.refresh();
}
}
public bool is_favorite => _is_favorite.Value;
public bool is_expanded { get => _is_expanded.Value; set => _is_expanded.set(value); }
public bool is_selected { get => _is_selected.Value; set => _is_selected.set(value); }
public bool is_dirty => _is_dirty.Value;
public bool is_factory_definition => key.mode == AlgoKey.Mode.Factory;
public bool can_redo => _can_redo.Value;
public bool can_undo => _can_undo.Value;
public EnabledValueVM<Color> custom_badge_color { get; } = new EnabledValueVM<Color>();
public ObservableCollection<ColorPaletteVM> custom_badge_color_palettes { get; } = new ObservableCollection<ColorPaletteVM>();
public Brush badge_fill => _badge_fill;
public ObservableCollection<AlgoDefinitionTemplateVM> templates => _templates;
/// <see cref="templates_with_custom"/> has the same elements as <see cref="templates"/>, plus the custom-placeholder-item, which is always at index 0.
/// The custom-placeholder supports legacy behavior in the ladder/ticket algo popup by allowing the user to manipulate the algo-structure (e.g. change an iceberg-limit order to iceberg-lean-cover-offset etc.).
/// However, the custom-placeholder item cannot be used to create/save algo-templates.
/// Algo-templates are just a set of values used to populate a concrete algo-structure; the 'structures' can be created in the AlgoStudio (<see cref="AlgoStudioWindow"/>).
/// If we were to strictly follow this paradigm, the user would no longer be able to freely change the algo-structure in the ladder/ticket popup (they would be forced to open up a new <see cref="AlgoStudioWindow"/>, and we know how much they hate more clicks!).
/// Some users might consider this a regression. The custom-placeholder-item addresses that concern.
public ObservableAppendCollection<AlgoDefinitionTemplateVM> templates_with_custom => _templates_with_custom;
public ListCollectionView templates_view { get; }
// format
public AlgoFormats selected_format { get => _selected_format.Value; set => _selected_format.set(value); }
public ObservableCollection<AlgoFormats> formats { get; } = new ObservableCollection<AlgoFormats> { AlgoFormats.Exchange, AlgoFormats.Spreader, AlgoFormats.Exchange | AlgoFormats.Spreader };
// visual states
public ObservableCollection<string> edit_pane_visual_states => _edit_pane_vs_model.states;
public ObservableCollection<string> tree_view_visual_states => _tree_view_vs_model.states;
#region IAlgoSelector
event PropertyChange<IAlgoVM> IAlgoSelector.selected_algo_changed { add => algo_root_changed += value; remove => algo_root_changed -= value; }
ObservableKeyedCollection<IAlgoVM, AlgoKey> IAlgoSelector.algos => _algo_roots;
IAlgoVM IAlgoSelector.selected_algo { get => algo_root; set => algo_root = value; }
void IAlgoSelector.load_algo_data(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) =>
_load_algo_data(algo_data, default_algo);
#endregion
#region IObserver (algo data...)
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnNext((IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) value) =>
_load_algo_data(value.algo_data, value.default_algo);
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnCompleted() { }
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnError(Exception error) { }
#endregion
void _load_algo_data(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) {
var orig_algo = algo_root?.id;
_algo_roots.SyncWithDictionary(algo_data, d => OrderTypeVMFactory.create(d, _editing_permissions, true));
if (!try_select(orig_algo) && !try_select(default_algo))
algo_root = algo_roots.FirstOrDefault();
//
bool try_select(AlgoKey? algo_key) {
if (algo_key.HasValue && _algo_roots.TryGetValue(algo_key.Value, out IAlgoVM match)) {
algo_root = match;
return true;
} else return false;
}
}
// idempotent
public void prepend_custom_template() {
if (_templates_with_custom.appended_front.Count == 0)
_templates_with_custom.insert_front(new AlgoDefinitionTemplateVM.CustomTemplatePlaceholderVM(this, _model, algo_root.definition));
}
public AlgoDefinitionTemplateVM template_factory() =>
new AlgoDefinitionTemplateVM(this, _model, algo_root.create_def_data().with(name: new_template_name)) {
is_selected = true
};
public IObservable<bool> subscribe_is_definition_dirty() => _is_dirty.observe_current(true);
public IObservable<bool> subscribe_any_templates_dirty() => _any_templates_dirty_monitor;
public IObservable<bool> subscribe_is_definition_or_any_templates_dirty() =>
Observable.Merge(
subscribe_is_definition_dirty().Select(v => v || _any_templates_dirty_monitor.is_above_threshold),
subscribe_any_templates_dirty().Select(v => v || is_dirty))
.DistinctUntilChanged();
public void undo() => _restore(_edit_stack.try_undo);
public void redo() => _restore(_edit_stack.try_redo);
public void load_committed() {
using (_refresh_on_local_changes.defer_execution())
_assign_from_data(_committed.Value);
_on_committed_changed();
}
/// <summary>
/// Subscribes to the templates source for this definition if it has been persisted (subscription requires a persistant id); does nothing if this definition has not been persisted, or if it is already subscribed (idempotent).
/// </summary>
public void connect() {
if (!_connected) {
_connected = true;
concat_disposable(_model.algo_model.subscribe_definition_templates(key).OnDispatcher().Subscribe(_template_update_buffer.OnNext));
}
}
public IDisposable buffer_updates() => _template_update_buffer.buffer_updates();
public void load(AlgoData data) {
_assert_can_load(data.key);
if (algo_root != null)
_edit_stack.push_distinct(_version.value);
using (_refresh_on_local_changes.defer_execution())
_assign_from_data(data);
_on_committed_changed();
}
// 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);
public AlgoData create_algo_def() =>
new AlgoData(algo_root.definition, name, key);
public AlgoDefinitionMetadata create_metadata() =>
_metadata.with(abbreviation: abbreviation, badge_color: new NullableColorProto(custom_badge_color.get_nullable()));
public bool Equals(AlgoDefinitionVM other) => other != null && key == other.key;
public override bool Equals(object obj) => Equals(obj as AlgoDefinitionVM);
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.");
if (key != data_key)
throw new InvalidOperationException($"{typeof(AlgoDefinitionVM)} '{nameof(key)}' not equal to the key generated from the specified data.");
}
void _assign_from_data(Snapshot state) {
_assign_from_data(state.data);
_selected_format.set(state.format);
_abbreviation.set(state.abbreviation);
custom_badge_color.set_nullable(state.custom_badge_color);
}
void _assign_from_data(AlgoData data) =>
_assign_from_data(data.name, data.value);
void _assign_from_data(string name, CustomOrderDefinitionImmutable definition) {
this.name = name;
algo_root = _algo_roots.GetOrAdd(OrderDataHelper.get_shallow_factory_key(definition), _ => _mk_algo_root(definition));
algo_root.load_from(definition);
}
void _on_committed_changed() {
_committed = _version.value;
_is_dirty.refresh();
_refresh_undo_redo();
}
IAlgoVM _mk_algo_root(CustomOrderDefinitionImmutable definition) =>
OrderTypeVMFactory.create(new AlgoData(definition), editing_permissions: _editing_permissions, true);
void _on_metadata(AlgoDefinitionMetadata metadata) {
using (_refresh_on_local_changes.supress_execution()) {
_abbreviation.set(metadata.abbreviation);
custom_badge_color.set_nullable(metadata.badge_color);
foreach (var t in templates) {
if (t.key.mode == AlgoKey.Mode.Persisted)
t.on_meta(t.key == metadata.default_template, metadata.favorite_templates.Contains(t.key));
else
t.on_meta(false, false);
}
_version.increment_version();
if (_edit_stack.size == 1 && _edit_stack.pos == 1) {
// this is a hack to account for the metadata being part of the committed state,
// despite arriving separately from the main data, which is passed into the constructor.
// the edit_stack is reset when this happens, so the origin-committed-state has the persisted metadata.
// TODO: unhack it.
_edit_stack.reset(_version.value);
} else _edit_stack.push_distinct(_version.value);
_on_committed_changed();
}
}
void _on_templates(TableUpdate<AlgoTemplateData, AlgoKey> table) {
foreach (var rec in table.removed)
_templates.Remove(rec.key);
foreach (var rec in table.changed)
_templates[rec.key].load_from(rec);
foreach (var rec in table.added) {
if (_templates.TryGetValue(rec.key, out AlgoDefinitionTemplateVM tmp)) {
tmp.load_from(rec);
} else {
tmp = new AlgoDefinitionTemplateVM(this, _model, new AlgoData(rec.value, rec.name, rec.key));
tmp.on_meta(tmp.key == _metadata.default_template, _metadata.favorite_templates.Contains(tmp.key));
_templates.Add(tmp);
}
}
}
void _refresh_undo_redo() {
_can_undo.refresh();
_can_redo.refresh();
}
void _restore(TryGetValue<Snapshot> try_get_snapshot) {
while (try_get_snapshot(out Snapshot next_state)) {
if (!_version.value.Equals(next_state)) {
using (_refresh_on_local_changes.defer_execution()) {
_assign_from_data(next_state);
return;
}
}
}
_refresh_undo_redo();
}
Snapshot _snapshot() =>
new Snapshot(create_algo_def(), abbreviation, custom_badge_color.get_nullable(), selected_format);
public struct Snapshot : IEquatable<Snapshot> {
public readonly AlgoData data;
public readonly string abbreviation;
public readonly Color? custom_badge_color;
public readonly AlgoFormats format;
public Snapshot(AlgoData data, string abbreviation, Color? custom_badge_color, AlgoFormats format) {
this.data = data;
this.abbreviation = abbreviation;
this.custom_badge_color = custom_badge_color;
this.format = format;
}
public bool Equals(Snapshot other) =>
data == other.data &&
abbreviation == other.abbreviation &&
custom_badge_color == other.custom_badge_color &&
format == other.format;
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
data.GetHashCode(),
abbreviation?.GetHashCode() ?? 0,
custom_badge_color?.GetHashCode() ?? 0,
(int)format);
#if DEBUG
public override string ToString() {
var sb = new System.Text.StringBuilder();
sb.Append($"name: {data.name}; ");
sb.Append($"abbrev.: {abbreviation}; ");
sb.Append($"badge: {custom_badge_color} ");
sb.Append($"fmt: {format} ");
sb.Append($"def: {data.value}");
return sb.ToString();
}
#endif
public static bool operator ==(Snapshot a, Snapshot b) => a.Equals(b);
public static bool operator !=(Snapshot a, Snapshot b) => !a.Equals(b);
}
}
}
@@ -0,0 +1,249 @@
using bts;
using bts.api.orderman;
using bts.collections;
using bts.utils;
using mbts.collections;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData;
namespace mbts.spark {
interface IAlgoStudioContentVM : IUndoRedo {
event Action can_redo_changed;
event Action can_undo_changed;
event PropertyChange<IAlgoVM> algo_root_changed;
string name { get; set; }
IAlgoVM algo_root { get; }
void load_committed();
}
static class AlgoStudioContentVMExtensions {
public static IObservable<IAlgoVM> observe_algo_root(this IAlgoStudioContentVM vm) =>
Observable.Create<IAlgoVM>(o => {
o.OnNext(vm.algo_root);
vm.algo_root_changed += on_algo_root_changed;
return Disposable.Create(() => vm.algo_root_changed -= on_algo_root_changed);
void on_algo_root_changed(IAlgoVM oldval, IAlgoVM newval) => o.OnNext(newval);
});
}
class AlgoStudioVM : DisposableViewModelBase, IHandleSelectedItemChanged {
static readonly AlgoFormats _studio_formats = AlgoFormats.Exchange;
readonly OrdersModel _model;
readonly Property<AlgoDefinitionVM> _selected_definition;
readonly Property<AlgoDefinitionTemplateVM> _selected_template;
readonly Property<IAlgoVM> _editable_content;
readonly DelegateProperty<string> _save_cmd_tooltip, _revert_cmd_tooltip;
readonly ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey> _definitions = new ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey>(d => d.key);
readonly ListCollectionView<AlgoDefinitionVM> _definitions_view;
readonly TableUpdateBuffer<AlgoData, AlgoKey> _definitions_update_buffer;
readonly ReactiveThresholdMonitor<AlgoDefinitionVM> _any_dirty_monitor = new ReactiveThresholdMonitor<AlgoDefinitionVM>(d => d.subscribe_is_definition_or_any_templates_dirty());
IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata> _persisted_meta = new Dictionary<AlgoKey, AlgoDefinitionMetadata>();
public AlgoStudioVM(OrdersModel model) {
_model = model;
_selected_definition = backing<AlgoDefinitionVM>(nameof(selected_definition));
_selected_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_template));
_editable_content = backing(nameof(editable_content), observe_selected().SelectManyInSeries(tup => tup.template?.observe_algo_root() ?? tup.definition?.observe_algo_root()).RefCount().OnDispatcher());
_definitions_update_buffer = new TableUpdateBuffer<AlgoData, AlgoKey>(def => def.key);
_definitions_view = new ListCollectionView<AlgoDefinitionVM>(definitions) {
CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic()
};
definitions_view.Filter = d => !(d.key.mode == AlgoKey.Mode.Persisted && _persisted_meta.TryGetValue(d.key, out AlgoDefinitionMetadata meta) && meta.is_hidden);
// save
var save_cmd = new ObservantAsyncCommand<IAlgoStudioContentVM>(save_async);
this.save_cmd = save_cmd;
_save_cmd_tooltip = backing(nameof(save_cmd_tooltip), get_save_tooltip);
// revert
var revert_cmd = new ObservantCommand<IAlgoStudioContentVM>(c => c.load_committed());
this.revert_cmd = revert_cmd;
_revert_cmd_tooltip = backing(nameof(revert_cmd_tooltip), get_revert_tooltip);
//
_dispose = new CompositeDisposable(
_model.algo_model.definitions.Subscribe(_definitions_update_buffer),
_definitions_update_buffer.OnDispatcher().Subscribe(u => AlgoCollectionHelper.update_persisted_definitions(_definitions, u, d => AlgoDefinitionVM.create(model, d, true, _studio_formats))),
_model.algo_model.metadata_service.subscribe_metadata().OnDispatcher().Subscribe(meta => {
_persisted_meta = meta;
definitions_view.Refresh();
}),
ObservableAutoWrapper.connect(observe_selected().Select(t => t.template?.edit_pane_visual_states ?? t.definition?.edit_pane_visual_states ?? new ObservableCollection<string>()), content_visual_states),
observe_selected().SelectManyInSeries(t => t.template?.observe_is_dirty() ?? t.definition?.subscribe_is_definition_or_any_templates_dirty() ?? Observable.Return(false)).RefCount().OnDispatcher()
.Subscribe(new CompositeObserver<bool>(save_cmd, revert_cmd) { val => {
_save_cmd_tooltip.refresh();
_revert_cmd_tooltip.refresh();
} }),
ObservableAutoWrapper.connect_item_hooks(definitions, d => new CompositeDisposable(_any_dirty_monitor.join(d), d), true));
// local methods
string get_revert_tooltip() {
if (content_source is AlgoDefinitionTemplateVM tmp) {
switch (tmp.key.mode) {
case AlgoKey.Mode.Persisted: return tmp.is_dirty ? $"Revert changes to '{tmp.name}'" : "No changes to revert";
}
} else if (content_source is AlgoDefinitionVM def) {
switch (def.key.mode) {
case AlgoKey.Mode.Persisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Revert changes to '{def.name}' templates" : "No changes to revert";
}
}
return null;
}
async Task save_async(IAlgoStudioContentVM content) {
if (content is AlgoDefinitionTemplateVM tmp) {
await save_template(tmp);
} else if (content is AlgoDefinitionVM def) {
await save_definition(def);
}
}
string get_save_tooltip() {
if (content_source is AlgoDefinitionTemplateVM tmp) {
switch (tmp.key.mode) {
case AlgoKey.Mode.Unpersisted: return tmp.is_dirty ? $"Save '{tmp.name}'" : $"Cannot Save '{tmp.name}'";
case AlgoKey.Mode.Persisted: return tmp.is_dirty ? $"Save changes to '{tmp.name}'" : "No changes to save";
}
} else if (content_source is AlgoDefinitionVM def) {
switch (def.key.mode) {
case AlgoKey.Mode.Unpersisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Save '{def.name}'" : $"Cannot Save '{def.name}'";
case AlgoKey.Mode.Persisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Save changes to '{def.name}' templates" : "No changes to save";
}
}
return null;
}
}
event Action<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)> _selected_changed;
public ObservableCollection<AlgoDefinitionVM> definitions => _definitions;
public ObservableCollection<string> content_visual_states { get; } = new ObservableCollection<string>();
public AlgoDefinitionVM selected_definition { get => _selected_definition.Value; set => _selected_definition.set(value); }
public AlgoDefinitionTemplateVM selected_template { get => _selected_template.Value; set => _selected_template.set(value); }
public IAlgoStudioContentVM content_source => (IAlgoStudioContentVM)selected_template ?? selected_definition;
public IAlgoVM editable_content => _editable_content.Value;
public ICollectionView<AlgoDefinitionVM> definitions_view => _definitions_view;
public ICommand save_cmd { get; }
public ICommand revert_cmd { get; }
public string save_cmd_tooltip => _save_cmd_tooltip.Value;
public string revert_cmd_tooltip => _revert_cmd_tooltip.Value;
public void add_new_definition() =>
_add_new_definition(AlgoDefinitionVM.new_algo_def, AlgoDefinitionVM.new_algo_name);
public void add_new_definition_clone(AlgoDefinitionVM src_definition) {
if (src_definition == null || src_definition.algo_root == null) {
add_new_definition();
} else {
_add_new_definition(src_definition.algo_root.definition, string.IsNullOrEmpty(src_definition.name) ? AlgoDefinitionVM.new_algo_name : $"{src_definition.name} - Copy");
}
}
void _add_new_definition(CustomOrderDefinitionImmutable def, string name) =>
_definitions.Add(AlgoDefinitionVM.create_placeholder(_model, def, name, _studio_formats));
public StartupData create() => new StartupData();
public void load_from(StartupData state) { }
public IObservable<AlgoDefinitionVM> subscribe_definition() => _selected_definition.observe_current(true);
public IObservable<AlgoDefinitionTemplateVM> subscribe_template() => _selected_template.observe_current(true);
public IObservable<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)> observe_selected() =>
Observable.Create<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)>(o => {
_selected_changed += o.OnNext;
return Disposable.Create(() => _selected_changed -= o.OnNext);
});
public IObservable<bool> subscribe_dirty() => _any_dirty_monitor;
public async Task remove_definition(AlgoDefinitionVM definition) {
if (definition.key.mode == AlgoKey.Mode.Persisted) {
await _model.algo_model.remove_definition(definition.key);
} else {
// This is a new definition, which hasn't been saved/persisted yet. No need to call the server.
definition.templates.Clear();
definitions.Remove(definition);
}
}
public async Task remove_template(AlgoDefinitionTemplateVM template) {
if (template.key.mode == AlgoKey.Mode.Persisted) {
await _model.algo_model.remove_template(template.key);
} else {
// This is a new template, which hasn't been saved/persisted yet. No need to call the server.
template.owner.templates.Remove(template);
}
}
public async Task save_definition(AlgoDefinitionVM definition) {
using (_save_op()) {
var newly_persisted_keys = await AlgoPersistenceHelper.persist_definition(_model, _definitions, definition);
AlgoKey pkey;
switch (definition.key.mode) {
case AlgoKey.Mode.Unpersisted:
if (!newly_persisted_keys.TryGetValue(definition.key, out pkey))
return;
break;
case AlgoKey.Mode.Persisted:
pkey = definition.key;
break;
default: return;
}
await _model.algo_model.metadata_service.update_metadata(pkey, _ => definition.create_metadata().with(id: pkey));
}
}
public async Task save_template(AlgoDefinitionTemplateVM template) {
using (_save_op())
await AlgoPersistenceHelper.persist_template(_model, _definitions, template);
}
public async Task save_all() =>
await _save(definitions.WrapSelector(def => (def, def.templates.AsList()), t => t.def));
async Task _save(IList<(AlgoDefinitionVM definition, IList<AlgoDefinitionTemplateVM> templates)> definition_templates) {
using (_save_op())
await AlgoPersistenceHelper.persist(_model, definition_templates);
}
IDisposable _save_op() {
int? def_index = selected_definition == null ? (int?)null : _definitions.IndexOf(selected_definition);
int? tmp_index = selected_template == null ? (int?)null : selected_definition.templates.IndexOf(selected_template);
return new CompositeDisposable(_definitions_update_buffer.buffer_updates()) {
() => {
if (def_index.HasValue) {
var def = _definitions[def_index.Value];
if (tmp_index.HasValue) {
var tmp = def.templates[tmp_index.Value];
tmp.is_selected = true;
} else def.is_selected = true;
}
}
};
}
/// Despite the existence of these properties: <see cref="AlgoDefinitionVM.is_selected"/>, and <see cref="AlgoDefinitionTemplateVM.is_selected"/>,
/// <see cref="AlgoStudioVM"/> still implements <see cref="IHandleSelectedItemChanged"/> to update the properties that depend on the <see cref="System.Windows.Controls.TreeView.SelectedItem"/>.
/// [John]I am going to Uganda in 3 days (today is 1/3/2019), and decided against removing this legacy-dependency at the last minute.
/// Fwiw, <see cref="AlgoDefinitionVM.is_selected"/> and <see cref="AlgoDefinitionTemplateVM.is_selected"/> are bound to <see cref="System.Windows.Controls.TreeViewItem.IsSelected"/>.
/// They serve to prevent a quirky default behavior in TreeView: double clicking any TreeViewItem collapses the entire TreeView.
/// This behavior wasn't just quirky either, it actually conflicted with the double-click-to-set-template-as-default behavior.
/// (for details, <see cref="mbts.ui.spark.AlgoStudioView.EnableToggleDefaultOnDoubleClickProperty"/>)
void IHandleSelectedItemChanged.on_selected_item_changed(object old_value, object new_value) {
if (new_value is AlgoDefinitionVM def) {
selected_definition = def;
selected_template = null;
} else if (new_value is AlgoDefinitionTemplateVM templ) {
selected_definition = templ.owner;
selected_template = templ;
} else {
selected_definition = null;
selected_template = null;
}
_selected_changed?.Invoke((selected_definition, selected_template));
RaisePropertyChanged(nameof(content_source));
}
}
}
+150 -119
View File
@@ -1,21 +1,27 @@
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.spark;
using bts.utils;
using mbts.collections;
using mbts.persist;
using mbts.spark.filters;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Windows.Data;
using System.Windows.Media;
using static bts.api.orderman.Fill.Types;
using static bts.shell.FillsWindowFactory;
using static mbts.ui.controls.DIYGrid;
@@ -23,106 +29,117 @@ using static mbts.ui.spark.FillsView;
using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
namespace mbts.spark {
class FillsVM : SecurityGrid<FillsVM.Row, FillTuple> {
class FillsVM : DisposableViewModelBase, IHandleGridSorting {
readonly OrdersModel _model;
readonly RXOperableCollection<Row, FillTuple, string> _rows;
readonly DIYGridSortManager<Columns> _sort_manager;
readonly IDIYGridFiltersManager<FillTuple, Columns, FilterStates> _filters_manager;
readonly ObservableKeyedCollection<ColumnBase, Columns> _columns = new ObservableKeyedCollection<ColumnBase, Columns>(_col_key);
List<(ColumnBase col, Columns key, ListSortDirection direction)> _active_comparers = new List<(ColumnBase col, Columns key, ListSortDirection direction)>();
IWindowSettingsManager<GridSettings> _settings_manager;
int _total_row_count;
public FillsVM(IBus bus, OrdersModel model, IObservable<StartupData> state_obs, IWindowSettingsManager<GridSettings> settings_manager)
: this(bus, model, state_obs, _get_observable(bus, model, state_obs), settings_manager) { }
FillsVM(IBus bus, OrdersModel model, IObservable<StartupData> state_obs, IConnectableObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> fills_source, IWindowSettingsManager<GridSettings> settings_manager)
: base(RXCollection.CreateIncrementalUpdate(fills_source), null) {
FillsVM(IBus bus, OrdersModel model, IObservable<StartupData> state_obs, IConnectableObservable<TableUpdate<FillTuple, string>> fills_source, IWindowSettingsManager<GridSettings> settings_manager) {
_model = model;
_settings_manager = settings_manager;
account_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_accounts().Select(d => d.Values), r => r.account, nameof(Row.account));
user_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_users().Select(d => d.Values), r => r.user, nameof(Row.user));
security_filter = DiscreteValuesFilterVM.Create<Row, SecurityImmutable, SecurityCriteria>(
fills_source.with_respect_to(
/// Columns
var col_tups = new ObservableKeyedCollection<DIYGridColumnData<FillTuple, Columns, FilterStates>, Columns>(c => c.key);
// security
add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security.ToString(),
DiscreteValuesFilterVM.Create<FillTuple, SecurityImmutable, SecurityCriteria>(
fills_source.distinct_on(
ft => ft.fill.FillKey,
ft => ft.security ?? SecurityDataHelper.Defaults.SecurityImmutable,
s => s.Id, ft => ft.key
).Select(t => (t.added.Values, t.removed.Values)),
r => r.security,
s => s.Id
).Select(t => (t.added.Concat(t.changed), t.removed.Concat(t.changes.Select(ch => ch.Old)))),
r => r.security ?? SecurityDataHelper.Defaults.SecurityImmutable,
SecurityCriteria.from_securities,
SecurityCriteria.get_to_securities(bus),
nameof(Row.security),
SecurityDataHelper.EqualityComparer.IDComparer,
Comparer<SecurityImmutable>.Default
);
// columns
add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security.ToString(), nameof(Row.security), security_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Security);
add_col(Columns.FillTime, DefaultColumnHeaders.FillTime, r => r.fill_time.ToString("M/d h:mm:ss tt"), nameof(Row.fill_time), fill_time_filter, DataGridFilterKnownTemplates.TimeFilter, DefaultColumnWidths.Time);
add_col(Columns.User, DefaultColumnHeaders.User, r => r.user, nameof(Row.user), user_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.User);
add_col(Columns.Account, DefaultColumnHeaders.Account, r => r.account, nameof(Row.account), account_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Account);
add_col(Columns.Exchange, DefaultColumnHeaders.Exchange, r => r.exchange.ToString(), nameof(Row.exchange), exchange_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Exchange);
add_col(Columns.TimeInForce, DefaultColumnHeaders.TimeInForce, r => r.time_in_force.ToString(), nameof(Row.time_in_force), time_in_force_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.TimeInForce);
columns.Add(new OrderTypeColumn<Columns>(Columns.OrderType, new Binding(nameof(Row.order_type)), new Binding(nameof(Row.order_metadata)), new Binding(nameof(Row.dynamic_order_type_display_name)), order_type_filter) { id = col_id(Columns.OrderType), sort_member_path = nameof(Row.order_type) });
columns.Add(new SideColumn<Row, Columns>(Columns.Side, r => r.side, side_filter) { id = col_id(Columns.Side), sort_member_path = nameof(Row.side) });
add_col(Columns.Size, DefaultColumnHeaders.Size, r => r.size.ToString(), nameof(Row.size), size_filter, DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.Size);
add_col(Columns.Price, DefaultColumnHeaders.Price, r => r.format_price(r.price), nameof(Row.price), price_filter, DataGridFilterKnownTemplates.DoubleMinMax, DefaultColumnWidths.Price);
add_col(Columns.FillKind, DefaultColumnHeaders.FillKind, r => r.fill_kind.ToString(), nameof(Row.fill_kind), fill_kind_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.FillKind);
add_col(Columns.FillKey, DefaultColumnHeaders.FillKey, r => r.fill_key.ToString(), nameof(Row.fill_key), fill_key_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.FillKey);
add_col(Columns.OrderKey, DefaultColumnHeaders.OrderKey, r => r.order_key.ToString(), nameof(Row.order_key), order_key_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.OrderKey);
add_col(Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, r => r.security_key.ToString(), nameof(Row.security_key), security_key_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.SecurityKey);
//
void add_col(Columns col_key, string header, Func<Row, string> get_text, string prop, IDataGridColumnFilter filter, string filter_template, double width) =>
columns.Add(new RenderTextColumn<Row, Columns>(col_key, get_text, filter, filter_template) {
id = col_id(col_key),
Header = header,
sort_member_path = prop,
Width = width
});
grid_settings_manager = new SimpleGridSettingsManager<Row>(columns, new Dictionary<string, GridColumnSettingsFeatureFlags> { }, row_vms);
equality_comparer: SecurityDataHelper.EqualityComparer.IDComparer,
comparer: Comparer<SecurityImmutable>.Default
), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Security);
// order type
var order_type_filter = dv_filter(OrderDataHelper.all_order_types, r => r.order?.order_type() ?? OrderType.None);
add_col_expl(Columns.OrderType,
new OrderTypeColumn<Columns>(Columns.OrderType, new Binding(nameof(Row.badge_fill)), new Binding(nameof(Row.display_name)), order_type_filter) {
id = col_id(Columns.OrderType),
sort_member_path = nameof(Row.order_type)
}, order_type_filter);
// side
var side_filter = dv_filter(new[] { Side.Buy, Side.Sell }, r => r.fill.Side);
add_col_expl(Columns.Side, new SideColumn<Row, Columns>(Columns.Side, r => r.side, side_filter) { id = col_id(Columns.Side) }, side_filter);
// all others (easily identified by the enum 'Columns.Foo')
add_col(Columns.FillTime, DefaultColumnHeaders.FillTime, r => r.fill_time.ToString("M/d h:mm:ss tt"), new TimeFilterVM<FillTuple>(r => r.fill.Timestamp.ToDateTimeOffset().LocalDateTime), DataGridFilterKnownTemplates.TimeFilter, DefaultColumnWidths.Time);
add_col(Columns.User, DefaultColumnHeaders.User, r => r.user, dv_filter_rx(_model.factory.subscribe_users().Select(d => d.Values), r => r.order?.user() ?? string.Empty), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.User);
add_col(Columns.Account, DefaultColumnHeaders.Account, r => r.account, dv_filter_rx(_model.factory.subscribe_accounts().Select(d => d.Values), r => r.account), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Account);
add_col(Columns.Exchange, DefaultColumnHeaders.Exchange, r => r.exchange.ToString(), dv_filter(EnumHelper.get_values<Venue>().ToArray(), r => r.security.exchange_or_default()), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Exchange);
add_col(Columns.TimeInForce, DefaultColumnHeaders.TimeInForce, r => r.time_in_force.ToString(), dv_filter(EnumHelper.get_values<TimeInForce>().ToArray(), r => r.order?.time_in_force() ?? TimeInForce.Undefined), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.TimeInForce);
add_col(Columns.Size, DefaultColumnHeaders.Size, r => r.size.ToString(), new DoubleMinMax<FillTuple>(r => r.fill.LastShares), DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.Size);
add_col(Columns.Price, DefaultColumnHeaders.Price, r => r.format_price(r.price), new DoubleMinMax<FillTuple>(r => r.fill.LastPrice), DataGridFilterKnownTemplates.DoubleMinMax, DefaultColumnWidths.Price);
add_col(Columns.FillKind, DefaultColumnHeaders.FillKind, r => r.fill_kind.ToString(), dv_filter(EnumHelper.get_values<FillKind>().ToArray(), r => r.fill.FillKind), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.FillKind);
add_col(Columns.FillKey, DefaultColumnHeaders.FillKey, r => r.fill_key.ToString(), new RegexFilterVM<FillTuple>(r => r.fill.FillKey), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.FillKey);
add_col(Columns.OrderKey, DefaultColumnHeaders.OrderKey, r => r.order_key.ToString(), new RegexFilterVM<FillTuple>(r => r.fill.OrderKey.ToString()), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.OrderKey);
add_col(Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, r => r.security_key.ToString(), new RegexFilterVM<FillTuple>(r => r.fill.SecurityKey.ToString()), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.SecurityKey);
/// Rows
_rows = new RXOperableCollection<Row, FillTuple, string>(
(ft, fk) => new Row(ft, model),
ft => ft.fill.FillKey,
new ComparerBuilder<FillTuple>(new[] {
_get_column_comparer(Columns.FillTime),
_get_column_comparer(Columns.FillKey)
}).to_comparer());
// row sort/filter managers
_sort_manager = new DIYGridSortManager<Columns>(col_tups.WrapSelector(t => (t.col, t.key)), Columns.FillKey);
_filters_manager = DIYGridFiltersManager.create(col_tups);
var rows_manager = new DIYGridRowsManager<FillTuple, Columns, FilterStates>(_filters_manager, _sort_manager, _get_column_comparer, f => _rows.filter = f, c => _rows.comparer = c, _rows.reset, FillsWindow.window_type_name);
// grid settings
grid_settings_manager = new SimpleGridSettingsManager<Row>(columns, new Dictionary<string, GridColumnSettingsFeatureFlags> { }, 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());
//
_resources.AddRange(
state_obs.OnDispatcher().Subscribe(s =>
{
using (rows_view.DeferRefresh()) {
if (s.grid != 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;
}
if (s.filters is FilterStates filters) {
fill_time_filter.load_state(filters.fill_time);
time_in_force_filter.load_state(filters.time_in_force);
order_type_filter.load_state(filters.order_type);
account_filter.load_state(filters.account);
user_filter.load_state(filters.user);
exchange_filter.load_state(filters.exchange);
security_filter.load_state(filters.security);
side_filter.load_state(filters.side);
price_filter.load_state(filters.price);
size_filter.load_state(filters.size);
fill_kind_filter.load_state(filters.fill_kind);
fill_key_filter.load_state(filters.fill_key);
order_key_filter.load_state(filters.order_key);
security_key_filter.load_state(filters.security_key);
} else {
fill_time_filter.load_state(
new TimeFilterTuple(ui.controls.TimeFilterMode.CMEOpen,
TimeTextTuple.FromDateTime(DateTime.Today),
TimeTextTuple.FromDateTime(DateTime.Today.AddDays(1))
)
);
fill_kind_filter.load_state(EnumHelper.get_values_except(FillKind.Sod).ToArray());
}
rows_view.set_sort_descriptions(s.sorting_criterion, columns);
_dispose = Disposable.Create(
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) {
// 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;
}
var fs = s.filters ?? new FilterStates {
fill_time = new TimeFilterTuple(
TimeFilterMode.CMEOpen,
TimeTextTuple.FromDateTime(DateTime.Today),
TimeTextTuple.FromDateTime(DateTime.Today.AddDays(1)))
};
rows_manager.on_settings(fs, s.sorting_criterion);
}),
DataGridFilterHelper.hook_filters(rows_view,
fill_time_filter, time_in_force_filter, order_type_filter, account_filter, user_filter, exchange_filter,
security_filter, side_filter, price_filter, size_filter, fill_kind_filter, fill_key_filter, order_key_filter, security_key_filter
),
settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager),
fills_source.Connect()
);
// local methods
void add_col<TFilter>(Columns col_key, string header, Func<Row, string> get_text, IDataGridColumnPersistentFilter<FillTuple, TFilter> filter, string filter_template, double width) =>
add_col_expl<TFilter>(col_key, new RenderTextColumn<Row, Columns>(col_key, get_text, filter, filter_template) {
id = col_id(col_key),
Header = header,
Width = width
}, filter);
void add_col_expl<TFilter>(Columns col_key, ColumnBase col, IDataGridColumnPersistentFilter<FillTuple, TFilter> filter) =>
col_tups.Add(col_key, DIYGridColumnData.create<FillTuple, Columns, FilterStates, TFilter>(col, filter, _get_column_comparer(col_key)));
// discrete-values-filter factories
IDataGridColumnPersistentFilter<FillTuple, T[]> dv_filter<T>(IReadOnlyCollection<T> items, Func<FillTuple, T> get_row_val) => DiscreteValuesFilterVM.Create<FillTuple, T>(items, get_row_val);
IDataGridColumnPersistentFilter<FillTuple, T[]> dv_filter_rx<T>(IObservable<IEnumerable<T>> items, Func<FillTuple, T> get_row_val) => DiscreteValuesFilterVM.Create<FillTuple, T>(items, get_row_val);
}
public ObservableCollection<ColumnBase> columns { get; } = new ObservableCollection<ColumnBase>();
public ObservableCollection<Row> rows => _rows;
public int total_row_count => _total_row_count;
public SimpleGridSettingsManager<Row> grid_settings_manager { get; }
@@ -133,72 +150,86 @@ namespace mbts.spark {
return grid_settings_manager.create();
}
#region Filters
public IDataGridColumnPersistentFilter<Row, TimeFilterTuple> fill_time_filter { get; } = new TimeFilterVM<Row>(r => r.fill_time, nameof(Row.fill_time));
public IDataGridColumnPersistentFilter<Row, TimeInForce[]> time_in_force_filter { get; } = DiscreteValuesFilterVM.Create<Row, TimeInForce>(EnumHelper.get_values<TimeInForce>().ToLArray(), r => r.time_in_force, nameof(Row.time_in_force));
public IDataGridColumnPersistentFilter<Row, OrderType[]> order_type_filter { get; } = DiscreteValuesFilterVM.Create<Row, OrderType>(OrderFactory.all_order_types, r => r.order_type, nameof(Row.order_type));
public IDataGridColumnPersistentFilter<Row, string[]> account_filter { get; }
public IDataGridColumnPersistentFilter<Row, string[]> user_filter { get; }
public IDataGridColumnPersistentFilter<Row, Venue[]> exchange_filter { get; } = DiscreteValuesFilterVM.Create<Row, Venue>(EnumHelper.get_values<Venue>().ToLArray(), r => r.exchange, nameof(Row.exchange));
public IDataGridColumnPersistentFilter<Row, SecurityCriteria> security_filter { get; }
public IDataGridColumnPersistentFilter<Row, Side[]> side_filter { get; } = DiscreteValuesFilterVM.Create<Row, Side>(new[] { Side.Buy, Side.Sell }, r => r.side, nameof(Row.side));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> price_filter { get; } = new DoubleMinMax<Row>(r => r.price, nameof(Row.price));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> size_filter { get; } = new DoubleMinMax<Row>(r => r.size, nameof(Row.size));
public IDataGridColumnPersistentFilter<Row, FillKind[]> fill_kind_filter { get; } = DiscreteValuesFilterVM.Create<Row, FillKind>(EnumHelper.get_values<FillKind>().ToArray(), r => r.fill_kind, nameof(Row.fill_kind));
public IDataGridColumnPersistentFilter<Row, string> fill_key_filter { get; } = new RegexFilterVM<Row>(r => r.fill_key, nameof(Row.fill_key));
public IDataGridColumnPersistentFilter<Row, string> order_key_filter { get; } = new RegexFilterVM<Row>(r => r.order_key.ToString(), nameof(Row.order_key));
public IDataGridColumnPersistentFilter<Row, string> security_key_filter { get; } = new RegexFilterVM<Row>(r => r.security_key.ToString(), nameof(Row.security_key));
public IEnumerable<SortingCriteria> get_sorting_criterion() =>
_sort_manager.create();
static Columns _col_key(ColumnBase column) =>
((IKeyedColumn<Columns>)column).key;
void IHandleGridSorting.on_sorting(object sender, DIYGridSortingEventArgs e) =>
_sort_manager.on_sorting(e);
public FilterStates get_filters() =>
new FilterStates {
fill_time = fill_time_filter.get_state(),
time_in_force = time_in_force_filter.get_state(),
order_type = order_type_filter.get_state(),
account = account_filter.get_state(),
user = user_filter.get_state(),
exchange = exchange_filter.get_state(),
security = security_filter.get_state(),
side = side_filter.get_state(),
price = price_filter.get_state(),
size = size_filter.get_state(),
fill_kind = fill_kind_filter.get_state(),
fill_key = fill_key_filter.get_state(),
order_key = order_key_filter.get_state(),
security_key = security_key_filter.get_state()
};
#endregion
_filters_manager.create();
protected override Row row_factory(FillTuple row_model) => new Row(row_model, _model);
protected override IEnumerable<SortingCriteria> get_default_sorting() { yield return new SortingCriteria(nameof(Row.fill_time), false); }
static IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> _get_observable(IBus bus, OrdersModel model, StartupData state) {
static IObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, StartupData state) {
if (!state.orders.is_null_or_empty()) {
var orders_hash = new HashSet<uint>(state.orders);
return model.on_fill_tuples.filter(f => orders_hash.Contains(f.fill.OrderKey));
return model.on_fill_tuples.Filter(f => orders_hash.Contains(f.fill.OrderKey));
} else return model.on_fill_tuples;
}
static IConnectableObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> _get_observable(IBus bus, OrdersModel model, IObservable<StartupData> state) =>
static IConnectableObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, IObservable<StartupData> state) =>
state.SelectManyInSeries(s => _get_observable(bus, model, s));
static IComparer<FillTuple> _get_column_comparer(Columns col) {
switch (col) {
case Columns.Account: return wrap(ft => ft.account ?? string.Empty);
case Columns.Exchange: return wrap_default(ft => ft.security.exchange_or_default());
case Columns.FillKey: return wrap(ft => ft.fill.FillKey);
case Columns.FillKind: return wrap_default(ft => ft.fill.FillKind);
case Columns.FillTime: return wrap(ft => ft.fill.Timestamp.to_local_time());
case Columns.OrderKey: return wrap(ft => ft.fill.OrderKey);
case Columns.OrderType: return wrap_default(ft => ft.order?.order_type() ?? OrderType.None);
case Columns.Price: return wrap(ft => ft.fill.LastPrice);
case Columns.Security: return wrap(ft => ft.security ?? SecurityDataHelper.Defaults.SecurityImmutable);
case Columns.SecurityKey: return wrap(ft => ft.fill.SecurityKey);
case Columns.Side: return wrap_default(ft => ft.fill.Side);
case Columns.Size: return wrap(ft => ft.fill.LastShares);
case Columns.TimeInForce: return wrap_default(ft => ft.order?.time_in_force() ?? TimeInForce.Undefined);
case Columns.User: return wrap(ft => ft.order?.user() ?? string.Empty);
default: goto case Columns.FillTime;
}
// local methods
IComparer<FillTuple> wrap<T>(Func<FillTuple, T> selector) where T : IComparable<T> =>
Comparer<T>.Default.wrap(selector);
IComparer<FillTuple> wrap_default<T>(Func<FillTuple, T> selector) =>
Comparer<T>.Default.wrap(selector);
}
void _on_fills(TableUpdate<FillTuple, string> u) {
foreach (var ft in u.removed.Concat(u.changes.Select(ch => ch.Old))) {
var k = ft.fill.FillKey;
rows.removeFirst(r => r.fill_key == k);
}
foreach (var ft in u.added.Concat(u.changed))
rows.Add(new Row(ft, _model));
}
public class Row : SecurityRow, IEquatable<Row>, IRowVM {
readonly OrdersModel _model;
readonly FillTuple _fill_tuple;
readonly FillImmutable _fill;
readonly OrderRecordImmutable _order;
Brush _badge_fill;
OrderMetadata _order_metadata;
public Row(FillTuple fill_tuple, OrdersModel model) :
base(fill_tuple.security ?? SecurityDataHelper.Defaults.SecurityImmutable) {
_fill_tuple = fill_tuple;
_fill = fill_tuple.fill;
_order = fill_tuple.order ?? OrderDataHelper.Defaults.OrderRecordImmutable;
_model = model;
account = fill_tuple.account;
}
public DateTime fill_time => _fill.Timestamp.ToDateTimeOffset().LocalDateTime;
public DateTime fill_time => _fill.Timestamp.to_local_time();
public TimeInForce time_in_force => _order.time_in_force();
public OrderType order_type => _order.order_type();
public string dynamic_order_type_display_name => _order.dynamic_order_type_display_name();
public OrderMetadata order_metadata => _model.factory.get_metadata(_order.Def.CustomDef.CustomCase);
public string display_name => OrderUtils.display_name(_order, _fill_tuple.algo);
public OrderMetadata order_metadata => _order_metadata ?? (_order_metadata = _model.factory.get_metadata(_order.Def.CustomDef.CustomCase));
public Brush badge_fill => _badge_fill ?? (_badge_fill = OrderUtils.badge_fill(_order, _fill_tuple.algo_meta, order_metadata));
public string account { get; private set; }
public string user => _order.user();
public Venue exchange => security.Exchange;
@@ -28,7 +28,7 @@
Grid.Row="0"
Columns="{Binding columns}"
CurrentRow="{Binding current_row}"
Rows="{Binding rows_view}"
Rows="{Binding rows}"
>
<c:DIYGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
@@ -51,9 +51,9 @@
<StatusBarItem HorizontalAlignment="Right">
<TextBlock>
<Run Text="Fills:"/>
<Run Text="{Binding ElementName=_grid, Path=Rows.Count, Mode=OneWay}" />
<Run Text="{Binding rows.Count, Mode=OneWay}" />
<Run Text="of"/>
<Run Text="{Binding rows_view.SourceCollection.Count, Mode=OneWay}" />
<Run Text="{Binding total_row_count, Mode=OneWay}" />
</TextBlock>
</StatusBarItem>
</StatusBar>
@@ -7,7 +7,7 @@ namespace mbts.ui.spark {
/// Interaction logic for FillsView.xaml
/// </summary>
partial class FillsView : UserControl {
public enum Columns { FillTime, User, Account, Exchange, Security, TimeInForce, OrderType, Side, Price, Size, FillKind, FillKey, OrderKey, SecurityKey, ExchangeOrderID }
public enum Columns { FillTime, User, Account, Exchange, Security, TimeInForce, OrderType, Side, Price, Size, FillKind, FillKey, OrderKey, SecurityKey }
public FillsView() =>
InitializeComponent();
@@ -17,7 +17,8 @@ using StartupData = bts.shell.FillsWindowFactory.StartupData;
namespace mbts.spark {
class FillsWindow : SparkWindow<StartupData>, ISharedWindow {
const string _window_type = "Fills", _thread_id = "Fills";
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<GridSettings> _settings_manager;
@@ -36,11 +37,11 @@ namespace mbts.spark {
event Action<FillsWindowFactory.StartupData> _state_changed;
public override string window_type => _window_type;
public override string window_type => window_type_name;
public override UIElement Content => _view;
public override IEnumerable<SparkCommand> Commands => _commands;
public override StartupData SaveState => _state = new StartupData(_state.orders, _vm.rows_view.get_sorting_criteria(_vm.columns), _vm.get_filters(), _vm.get_grid_save_state());
public override StartupData SaveState => _state = new StartupData(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.get_grid_save_state());
public override double MinWidth =>
StartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width)
+ SPARK_MENU_COLLAPSED_WIDTH
@@ -71,7 +72,7 @@ namespace mbts.spark {
)
);
// TODO: bind to main window's Title
var dialog = new SimpleGridSettingsDialog { Title = $"{_window_type} Grid Settings", DataContext = vm };
var dialog = new SimpleGridSettingsDialog { Title = $"{window_type_name} Grid Settings", DataContext = vm };
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
return dialog;
}))
@@ -79,7 +80,7 @@ namespace mbts.spark {
_subscriptions = Disposable.Create(() =>
_state_changed?.Invoke(
_state = new StartupData(_state.orders,
_vm.rows_view.get_sorting_criteria(_vm.columns),
_vm.get_sorting_criterion().ToList(),
_vm.get_filters(),
_vm.grid_settings_manager.create()
)
@@ -4,6 +4,7 @@ using mbts.persist;
using mbts.spark;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using ProtoBuf;
using System;
@@ -118,33 +119,60 @@ namespace bts.shell {
[ProtoContract]
public class FilterStates {
[ProtoMember(1)]
public TimeFilterTuple fill_time;
[DIYGridColumnID(nameof(Columns.FillTime))]
public TimeFilterTuple fill_time { get; set; }
[ProtoMember(2)]
public TimeInForce[] time_in_force;
[DIYGridColumnID(nameof(Columns.TimeInForce))]
public TimeInForce[] time_in_force { get; set; }
[ProtoMember(3)]
public CustomOrderDefinition.CustomOneofCase[] order_type;
[DIYGridColumnID(nameof(Columns.OrderType))]
public CustomOrderDefinition.CustomOneofCase[] order_type { get; set; }
[ProtoMember(4)]
public string[] account;
[DIYGridColumnID(nameof(Columns.Account))]
public string[] account { get; set; }
[ProtoMember(5)]
public string[] user;
[DIYGridColumnID(nameof(Columns.User))]
public string[] user { get; set; }
[ProtoMember(6)]
public Venue[] exchange;
[DIYGridColumnID(nameof(Columns.Exchange))]
public Venue[] exchange { get; set; }
[ProtoMember(7)]
public SecurityCriteria security;
[DIYGridColumnID(nameof(Columns.Security))]
public SecurityCriteria security { get; set; }
[ProtoMember(8)]
public Side[] side;
[DIYGridColumnID(nameof(Columns.Side))]
public Side[] side { get; set; }
[ProtoMember(9)]
public DoubleMinMaxState price;
[DIYGridColumnID(nameof(Columns.Price))]
public DoubleMinMaxState price { get; set; }
[ProtoMember(10)]
public DoubleMinMaxState size;
[DIYGridColumnID(nameof(Columns.Size))]
public DoubleMinMaxState size { get; set; }
[ProtoMember(11)]
public string fill_key;
[DIYGridColumnID(nameof(Columns.FillKey))]
public string fill_key { get; set; }
[ProtoMember(12)]
public string order_key;
[DIYGridColumnID(nameof(Columns.OrderKey))]
public string order_key { get; set; }
[ProtoMember(13)]
public string security_key;
[DIYGridColumnID(nameof(Columns.SecurityKey))]
public string security_key { get; set; }
[ProtoMember(14)]
public Fill.Types.FillKind[] fill_kind;
[DIYGridColumnID(nameof(Columns.FillKind))]
public Fill.Types.FillKind[] fill_kind { get; set; }
}
}
}
@@ -18,13 +18,12 @@ using LadderSettings = mbts.spark.LadderSettings;
namespace bts.shell {
class LadderWindowFactory : ShellWindowFactory<LadderSaveState> {
const string _window_type = "ladder";
readonly TimeSpan _security_timeout;
readonly LadderConfig _ladder_conf;
readonly IBus _bus;
readonly IWindowManager _wm;
readonly UserSettingsHub _settings_hub;
readonly OrdersModel _orders_model;
readonly MarketDataAuxiliaryModel _md_auxiliary_model;
readonly int _max_ladders_open;
IReadOnlyDictionary<uint, SecurityMD> _securities = new Dictionary<uint, SecurityMD>();
public LadderWindowFactory(IShellModule owner, IBus bus, IWindowManager wm, UserSettingsHub settings_hub, OrdersModel orders_model, MarketDataAuxiliaryModel md_auxiliary_model)
@@ -34,9 +33,7 @@ namespace bts.shell {
_settings_hub = settings_hub;
_orders_model = orders_model;
_md_auxiliary_model = md_auxiliary_model;
var knobs = Configuration.get<bts.config.LadderKnobs>();
_max_ladders_open = (int)(knobs.max_open_ladders);
_security_timeout = TimeSpan.FromSeconds(Math.Max(15, knobs.security_timeout_secs));
_ladder_conf = new LadderConfig(Configuration.get<bts.config.LadderKnobs>(), Configuration.get<bts.config.toggles.LaddersOnThreads>().enabled);
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s),
bus.subscribe(SparkTags.ShowLadderTag).OnDispatcher().Subscribe(s => show_windows(new[] { s })),
@@ -45,7 +42,7 @@ namespace bts.shell {
}
public async override Task<IShellWindow> load(LadderSaveState state) {
await Wait.until_true(() => _securities.ContainsKey(state.security_key), _security_timeout);
await Wait.until_true(() => _securities.ContainsKey(state.security_key), _ladder_conf.security_timeout);
if (_securities.TryGetValue(state.security_key, out SecurityMD security)) {
return create_ladder_window(security, state.settings);
}
@@ -67,9 +64,13 @@ namespace bts.shell {
var init = state_settings ?? settings_manager.default_settings;
init.use_defaults |= state_settings == null;
var vm = new LadderVM(_bus, model, settings_manager, init);
return new LadderView(vm);
vm.order_properties_vm.open_algo_popup_on_select = _ladder_conf.open_algo_popup_on_select;
var lv = new LadderView(vm);
foreach (var kv in AlgoStudioModelUtils.get_dynamic_resources(vm.model.order_gateway.algo_model.ui_configuration))
lv.Resources[kv.Key] = kv.Value;
return lv;
});
string thread = Configuration.get<bts.config.toggles.LaddersOnThreads>().enabled ? $"Ladder{id:00}" : "";
string thread = _ladder_conf.ladders_on_threads ? $"Ladder{id:00}" : "";
return ShellWindow.create(
module, md.security.ToString(), _window_type, view,
(v,s) => save(_get_state(((LadderView)v).vm), s),
@@ -102,11 +103,11 @@ namespace bts.shell {
}
void show_windows(IReadOnlyCollection<SecurityMD> securities) {
int n_allowed = _max_ladders_open - _wm.list_windows().Where(w => w.window_type == _window_type).Count();
int n_allowed = (int)_ladder_conf.max_open_ladders - _wm.list_windows().Where(w => w.window_type == _window_type).Count();
int n_opened = 0;
foreach (var s in securities) {
if (++n_opened > n_allowed) {
BTSMessageBox.Show($"The maximum number of ladders are already opened ({_max_ladders_open}).", "Ladders",
BTSMessageBox.Show($"The maximum number of ladders are already opened ({_ladder_conf.max_open_ladders}).", "Ladders",
BTSMessageBoxButtons.OK, MessageBoxImage.Exclamation, true, false, true);
break;
} else {
@@ -135,6 +136,19 @@ namespace bts.shell {
// ).Aggregate((old, vm) => { old.Dispose(); return vm; })
// .Subscribe(vm => { view.DataContext = vm; window.Title = vm.security.ToString(); });
//}
readonly struct LadderConfig {
public readonly uint max_open_ladders;
public readonly bool ladders_on_threads, open_algo_popup_on_select;
public readonly TimeSpan security_timeout;
public LadderConfig(bts.config.LadderKnobs knobs, bool ladders_on_threads) {
max_open_ladders = knobs.max_open_ladders;
open_algo_popup_on_select = knobs.open_algo_popup_on_select;
security_timeout = TimeSpan.FromSeconds(Math.Max(15, knobs.security_timeout_secs));
this.ladders_on_threads = ladders_on_threads;
}
}
}
[ProtoContract]
@@ -30,7 +30,7 @@ namespace mbts.spark {
interface ICVOrderBookColumn : IKeyedColumn<Columns>, IGridColumn {
string sort_member_path { get; }
ListSortDirection? SortDirection { get; set; }
IDataGridColumnFilter<OrderSecurity> filter { get; }
IDataGridColumnFilter<OrderSecurityAlgoMeta> filter { get; }
IComparer<OrderBookRowVM> comparer { get; }
}
@@ -65,7 +65,7 @@ namespace mbts.spark {
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
// security
Add(security_column = new SecurityColumn(
DiscreteValuesFilterVM.Create<OrderSecurity, SecurityImmutable, SecurityCriteria>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, SecurityImmutable, SecurityCriteria>(
order_securities,
ort => ort.security ?? SecurityDataHelper.Defaults.SecurityImmutable,
SecurityCriteria.from_securities,
@@ -81,7 +81,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.symbol),
r => r.symbol,
DefaultColumnWidths.Symbol,
DiscreteValuesFilterVM.Create<OrderSecurity, string>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, string>(
mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(),
ort => ort.security?.Symbol ?? string.Empty,
nameof(OrderBookRowVM.symbol)
@@ -95,7 +95,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.time_created),
r => r.time_created_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderSecurity>(
new TimeFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.created(),
nameof(OrderBookRowVM.time_created)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -107,7 +107,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.last_change),
r => r.last_change_text,
DefaultColumnWidths.Time,
new TimeFilterVM<OrderSecurity>(
new TimeFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.last_change(),
nameof(OrderBookRowVM.last_change)),
DataGridFilterKnownTemplates.TimeFilter,
@@ -119,7 +119,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.user),
r => r.user,
DefaultColumnWidths.User,
DiscreteValuesFilterVM.Create<OrderSecurity, string>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, string>(
model.factory.subscribe_users().Select(d => d.Values),
ort => ort.order.user(),
nameof(OrderBookRowVM.user)),
@@ -132,7 +132,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.account),
r => r.account,
DefaultColumnWidths.Account,
DiscreteValuesFilterVM.Create<OrderSecurity, string, string[]>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, string, string[]>(
model.factory.subscribe_accounts().Select(d => d.Values),
ort => ort.order.account(),
vals => vals.ToArray(),
@@ -147,7 +147,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.exchange),
r => r.exchange.ToString(),
DefaultColumnWidths.Exchange,
DiscreteValuesFilterVM.Create<OrderSecurity, Venue>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, Venue>(
EnumHelper.get_values_except(Venue.Unset).ToList(),
ort => ort.security.exchange_or_default(),
nameof(OrderBookRowVM.exchange)),
@@ -160,7 +160,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.time_in_force),
r => r.time_in_force.ToString(),
DefaultColumnWidths.TimeInForce,
DiscreteValuesFilterVM.Create<OrderSecurity, TimeInForce>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, TimeInForce>(
EnumHelper.get_values<TimeInForce>().ToList(),
ort => ort.order.time_in_force(),
nameof(OrderBookRowVM.time_in_force)),
@@ -168,8 +168,8 @@ namespace mbts.spark {
_wrap_comparer(r => r.time_in_force)));
// order type
Add(order_type_column = new OrderBookOrderTypeColumn(
DiscreteValuesFilterVM.Create<OrderSecurity, OrderType>(
utilities.OrderFactory.all_order_types,
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, OrderType>(
utilities.OrderDataHelper.all_order_types,
ort => ort.order.order_type(),
nameof(OrderBookRowVM.order_type))));
// order sub type
@@ -179,7 +179,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.order_sub_type),
r => r.order_sub_type_text,
80,
DiscreteValuesFilterVM.Create<OrderSecurity, OrderSubType>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, OrderSubType>(
EnumHelper.get_values<OrderSubType>().ToList(),
ort => ort.order.sub_type(),
nameof(OrderBookRowVM.order_sub_type)),
@@ -187,20 +187,20 @@ namespace mbts.spark {
_wrap_comparer(r => r.order_sub_type)));
// side
Add(side_column = new SideColumn(
DiscreteValuesFilterVM.Create<OrderSecurity, Side>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, Side>(
new[] { Side.Buy, Side.Sell },
ort=> ort.order.side(),
nameof(OrderBookRowVM.side))));
// quantity
Add(qty_column = new SizeColumn(
new UIntMinMax<OrderSecurity>(ort => ort.order.quantity(), nameof(OrderBookRowVM.quantity))));
new UIntMinMax<OrderSecurityAlgoMeta>(ort => ort.order.quantity(), nameof(OrderBookRowVM.quantity))));
// edit quantity column
// not usually part of the main order book, but it's useful to add it
// rather than debugging the popup window
//Add(edit_qty_column = new EditableQtyColumn());
// filled quantity
Add(filled_qty_column = new FilledColumn(
new UIntMinMax<OrderSecurity>(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
new UIntMinMax<OrderSecurityAlgoMeta>(ort => ort.order.filled(), nameof(OrderBookRowVM.filled_quantity))));
// price
Add(price_column = new SimpleTextColumn<DoubleMinMaxState>(
Columns.Price,
@@ -208,7 +208,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.price),
r => r.price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderSecurity>(
new DoubleMinMax<OrderSecurityAlgoMeta>(
ort => ort.order.price(),
nameof(OrderBookRowVM.price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -224,7 +224,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.avg_price),
r => r.avg_price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderSecurity>(
new DoubleMinMax<OrderSecurityAlgoMeta>(
ort => ort.order.avg_price(),
nameof(OrderBookRowVM.avg_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -236,7 +236,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.last_price),
r => r.last_price_text,
DefaultColumnWidths.Price,
new DoubleMinMax<OrderSecurity>(
new DoubleMinMax<OrderSecurityAlgoMeta>(
ort => ort.order.last_price(),
nameof(OrderBookRowVM.last_price)),
DataGridFilterKnownTemplates.DoubleMinMax,
@@ -248,7 +248,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.status),
r => r.status.ToString(),
80,
DiscreteValuesFilterVM.Create<OrderSecurity, OrderStatus>(
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, OrderStatus>(
EnumHelper.get_values<OrderStatus>().ToList(),
ort => ort.order.status(),
nameof(OrderBookRowVM.status)),
@@ -256,7 +256,7 @@ namespace mbts.spark {
_wrap_comparer(r => r.status)));
// last message
Add(last_message_column = new OrderBookLastMessageColumn(
new RegexFilterVM<OrderSecurity>(
new RegexFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.last_msg(),
nameof(OrderBookRowVM.last_msg))));
// security key
@@ -266,7 +266,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.security_key),
r => r.security_key.ToString(),
DefaultColumnWidths.SecurityKey,
new RegexFilterVM<OrderSecurity>(
new RegexFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.security_key().ToString(),
nameof(OrderBookRowVM.security_key)),
DataGridFilterKnownTemplates.Regex,
@@ -278,7 +278,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.order_key),
r => r.order_key.ToString(),
DefaultColumnWidths.OrderKey,
new RegexFilterVM<OrderSecurity>(
new RegexFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.Key.ToString(),
nameof(OrderBookRowVM.order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -290,7 +290,7 @@ namespace mbts.spark {
nameof(OrderBookRowVM.parent_order_key),
r => r.parent_order_key.ToString(),
DefaultColumnWidths.ParentKey,
new RegexFilterVM<OrderSecurity>(
new RegexFilterVM<OrderSecurityAlgoMeta>(
ort => ort.order.ParentKey.ToString(),
nameof(OrderBookRowVM.parent_order_key)),
DataGridFilterKnownTemplates.Regex,
@@ -389,9 +389,9 @@ namespace mbts.spark {
}
}
public Func<OrderSecurity, bool> get_filter() {
public Func<OrderSecurityAlgoMeta, bool> get_filter() {
var active_filters = this.OfType<ICVOrderBookColumn>().Where(c => c.filter.active.GetValueOrDefault()).Select(c => c.filter).ToArray();
return active_filters.Length == 0 ? null : new Func<OrderSecurity, bool>(r => active_filters.All(f => f.filter(r)));
return active_filters.Length == 0 ? null : new Func<OrderSecurityAlgoMeta, bool>(r => active_filters.All(f => f.filter(r)));
}
public OrderBookSortingData get_sorting_data() {
@@ -481,7 +481,7 @@ namespace mbts.spark {
GlyphContext _root_glyph_context, _child_glyph_context;
protected OrderbookColumnBase(Columns col_key, string header, Func<OrderBookRowVM, string> get_text, string sort_prop, double width,
IDataGridColumnPersistentFilter<OrderSecurity, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, T> filter, string filter_template, IComparer<OrderBookRowVM> comparer) : base(col_key) {
id = key.ToString();
Width = width;
Header = header;
@@ -499,10 +499,10 @@ namespace mbts.spark {
}
}
public IDataGridColumnPersistentFilter<OrderSecurity, T> filter { get; }
public IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, T> filter { get; }
public IComparer<OrderBookRowVM> comparer { get; }
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderSecurityAlgoMeta> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => _filter_template;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -516,7 +516,7 @@ namespace mbts.spark {
public class SimpleTextColumn<TFilterState> : OrderbookColumnBase<TFilterState>, IRenderColumn<OrderBookRowVM> {
public SimpleTextColumn(Columns key, string header, string sort_prop, Func<OrderBookRowVM, string> get_text, double width,
IDataGridColumnPersistentFilter<OrderSecurity, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, TFilterState> filter, string filter_template, IComparer<OrderBookRowVM> comparer)
: base(key, header, get_text, sort_prop, width, filter, filter_template, comparer) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -526,7 +526,7 @@ namespace mbts.spark {
#region Explicit Column Defs
public class SideColumn : OrderbookColumnBase<Side[]>, IRenderColumn<OrderBookRowVM> {
public SideColumn(IDataGridColumnPersistentFilter<OrderSecurity, Side[]> filter)
public SideColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, Side[]> filter)
: base(Columns.Side, "B/S", r => r.side.ToString(), nameof(OrderBookRowVM.side), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues, _wrap_comparer(r => r.side)) { }
public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
@@ -535,7 +535,7 @@ namespace mbts.spark {
}
public class SizeColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
public SizeColumn(IDataGridColumnPersistentFilter<OrderSecurity, UIntMinMaxState> filter)
public SizeColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, UIntMinMaxState> filter)
: base(Columns.Size, "Qty", r => r.quantity.ToString(), nameof(OrderBookRowVM.quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.quantity)) {
sort_member_path = nameof(OrderBookRowVM.quantity);
}
@@ -546,7 +546,7 @@ namespace mbts.spark {
}
public class FilledColumn : OrderbookColumnBase<UIntMinMaxState>, IRenderColumn<OrderBookRowVM> {
public FilledColumn(IDataGridColumnPersistentFilter<OrderSecurity, UIntMinMaxState> filter)
public FilledColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, UIntMinMaxState> filter)
: base(Columns.Filled, "Filled Qty", r => r.filled_quantity.ToString(), nameof(OrderBookRowVM.filled_quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.filled_quantity)) {
sort_member_path = nameof(OrderBookRowVM.filled_quantity);
}
@@ -558,8 +558,8 @@ namespace mbts.spark {
public class OrderBookOrderTypeColumn : OrderTypeColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter<OrderSecurity, OrderType[]> filter)
: base(Columns.OrderType, new Binding(nameof(OrderBookRowVM.order_type)), new Binding(nameof(OrderBookRowVM.order_metadata)), new Binding(nameof(OrderBookRowVM.dynamic_order_type_display_name)), filter) {
public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, OrderType[]> filter)
: base(Columns.OrderType, new Binding(nameof(OrderBookRowVM.badge_fill)), new Binding(nameof(OrderBookRowVM.display_name)), filter) {
id = key.ToString();
this.filter = filter;
sort_member_path = nameof(OrderBookRowVM.order_type);
@@ -567,10 +567,10 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
public new IDataGridColumnPersistentFilter<OrderSecurity, OrderType[]> filter { get; }
public new IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, OrderType[]> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.order_type);
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderSecurityAlgoMeta> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
@@ -582,7 +582,7 @@ namespace mbts.spark {
public class OrderBookLastMessageColumn : TextColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurity, string> filter)
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, string> filter)
: base(Columns.LastMessage, new Binding(nameof(OrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) {
id = key.ToString();
this.filter = filter;
@@ -592,10 +592,10 @@ namespace mbts.spark {
tooltip_binding = new Binding(nameof(OrderBookRowVM.last_msg));
}
public new IDataGridColumnPersistentFilter<OrderSecurity, string> filter { get; }
public new IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, string> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.last_msg);
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderSecurityAlgoMeta> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
protected override void OnSortDirectionChanged(ListSortDirection? new_value) {
@@ -611,7 +611,7 @@ namespace mbts.spark {
ListSortDirection? _cached_sort_direction;
public SecurityColumn(IDataGridColumnPersistentFilter<OrderSecurity, SecurityCriteria> filter) : base(Columns.Security) {
public SecurityColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, SecurityCriteria> filter) : base(Columns.Security) {
id = key.ToString();
this.filter = filter;
Header = DefaultColumnHeaders.Security;
@@ -620,10 +620,10 @@ namespace mbts.spark {
_cached_sort_direction = SortDirection;
}
public IDataGridColumnPersistentFilter<OrderSecurity, SecurityCriteria> filter { get; }
public IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, SecurityCriteria> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.security, SecurityHelper.Comparer.InstanceImmutable.to_nullable());
IDataGridColumnFilter<OrderSecurity> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter<OrderSecurityAlgoMeta> ICVOrderBookColumn.filter => filter;
IDataGridColumnFilter IFilterableColumn.filter => filter;
string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -15,12 +15,12 @@ using System.Reactive.Linq;
namespace mbts.spark {
class OrderBookRowCollection : ObservableCollection<OrderBookRowVM> {
static readonly IEqualityComparer<INode<OrderBookRowVM>> _node_equality_comparer = EqualityComparer.Create<INode<OrderBookRowVM>, uint>(n => n.value.order_key);
readonly Func<OrderSecurity, OrderBookRowVM> _row_factory;
readonly Func<OrderSecurityAlgoMeta, OrderBookRowVM> _row_factory;
/// Critical: Any and all row mutations <see cref="OrderBookRowVM"/> must be executed through <see cref="SortedTree{T, TKey}.TryReplace(TKey, Func{T, T})"/>.
/// Mutations can change the sort-position of a row, and <see cref="_tree"/> will be broken if its elements aren't properly sorted (it relies heavily on binary-search logic).
SortedTree<OrderBookRowVM, uint> _tree;
IComparer<OrderBookRowVM> _comparer;
Func<OrderSecurity, bool> _filter;
Func<OrderSecurityAlgoMeta, bool> _filter;
bool _is_refresh_pending;
int _deferment_count = 0;
/// When processing changed-items, the <see cref="SortedTree{T, TKey}.TryReplace(TKey, Func{T, T})"/> method is used to update the changed row. It is not expected to fail (return false),
@@ -29,12 +29,12 @@ namespace mbts.spark {
const int _max_replace_misses_logged = 10;
int _n_replace_misses_logged;
public OrderBookRowCollection(Func<OrderSecurity, OrderBookRowVM> row_factory, IComparer<OrderBookRowVM> comparer) {
public OrderBookRowCollection(Func<OrderSecurityAlgoMeta, OrderBookRowVM> row_factory, IComparer<OrderBookRowVM> comparer) {
_row_factory = row_factory;
_tree = _mk_tree(_comparer = comparer);
}
public Func<OrderSecurity, bool> filter {
public Func<OrderSecurityAlgoMeta, bool> filter {
get => _filter;
set {
_filter = value;
@@ -146,7 +146,7 @@ namespace mbts.spark {
});
}
public void update(TableUpdate<(SecurityImmutable? sec,OrderRecordImmutable order),uint> table) {
public void update(TableUpdate<OrderSecurityAlgoMeta, uint> table) {
IEnumerable<INode<OrderBookRowVM>> impacted_branch_roots;
int n_removed = table.removed.Count();
if (n_removed == total_row_count) {
@@ -154,7 +154,7 @@ namespace mbts.spark {
_tree = _mk_tree(_comparer, table.added.Select(x => _row_factory(x)));
impacted_branch_roots = _tree.RootNodes;
} else {
foreach (OrderSecurity ort in table.removed)
foreach (OrderSecurityAlgoMeta ort in table.removed)
_tree.Remove(ort.order.Key);
foreach (var change in table.changes) {
if (!_tree.TryReplace(change.New.order.Key, r => { r.update(change.New); return r; })) {
@@ -163,7 +163,7 @@ namespace mbts.spark {
Log.Ui.error($"{nameof(OrderBookRowCollection)} failed to process Changed {nameof(OrderSecurity)} in update (old:{change.Old.order.Key}, new:{change.New.order.Key}). This is the '{_n_replace_misses_logged}' time this has happened in this OrderBook.");
}
}
foreach (OrderSecurity ort in table.added)
foreach (OrderSecurityAlgoMeta ort in table.added)
_tree.Insert(_row_factory(ort));
impacted_branch_roots =
table.added.Concat(table.changed).Select(ort => ort.order.Key).Select(_tree.GetRootNode)
@@ -10,12 +10,14 @@ using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.spark {
partial class OrderBookRowVM : DisposableViewModelBase, IEquatable<OrderBookRowVM>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
const string _unknown_security_price_format_string = "0.#########";
const int _unknown_security_price_num_fractional_digits = 9;
readonly OrderBookVM _owner;
Brush _badge_fill;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _modify_order_quantity, _modify_order_price;
bool _is_parent, _is_expanded, _is_selected;
int _depth_level;
@@ -27,7 +29,7 @@ namespace mbts.spark {
double _prospective_price;
public OrderBookRowVM(OrderBookVM owner, OrderSecurity order_tuple, bool is_expanded) {
public OrderBookRowVM(OrderBookVM owner, OrderSecurityAlgoMeta order_tuple, bool is_expanded) {
_owner = owner;
this.order_tuple = order_tuple;
is_visible = !is_child;
@@ -50,9 +52,10 @@ namespace mbts.spark {
public event Action invalidated;
// Core
public OrderSecurity order_tuple { get; private set; }
public OrderSecurityAlgoMeta 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 = order_tuple.badge_fill(order_metadata));
public uint order_key => order.Key;
public uint parent_order_key => order.ParentKey;
public uint security_key => order.security_key();
@@ -63,7 +66,7 @@ namespace mbts.spark {
public string symbol => _security.symbol_or_default();
// Def
public CustomOrderDefinition.CustomOneofCase order_type => order.order_type();
public string dynamic_order_type_display_name => order.dynamic_order_type_display_name();
public string display_name => order_tuple.display_name();
public OrderSubType order_sub_type => order.sub_type();
public string order_sub_type_text => _fmt_order_sub_type(order_sub_type);
public Side side => order.side();
@@ -164,9 +167,10 @@ namespace mbts.spark {
internal void expand_internal() => Set(ref _is_expanded, true);
internal void collapse_internal() => Set(ref _is_expanded, false);
public void update(OrderSecurity order_tuple) {
public void update(OrderSecurityAlgoMeta order_tuple) {
Log.assert(order_tuple.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key.");
bool had_security = _security.HasValue;
var old_meta = this.order_tuple.meta;
// _show_order_modify_cmd is lazy (instantiated in the default_command getter); it might be null, don't not force instantiation
bool? could_modify_execute = _show_order_modify_cmd?.CanExecute(null);
OrderRecordImmutable old_order = order;
@@ -196,6 +200,10 @@ namespace mbts.spark {
// need to raise invalidated to refresh the price cells (the security.ContractSpec determines how they are formatted - Ticks!)
invalidate = true;
}
if (old_meta?.badge_color != order_tuple.meta?.badge_color) {
_badge_fill = null;
RaisePropertyChanged(nameof(badge_fill));
}
if (old_order.status() != order.status()) {
invalidate = true;
RaisePropertyChanged(nameof(status));
@@ -228,4 +236,4 @@ namespace mbts.spark {
security.Value.ContractSpec.format(v) :
Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string);
}
}
}
@@ -15,7 +15,6 @@ using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using static bts.shell.OrderBookWindowFactory;
@@ -56,7 +55,7 @@ namespace mbts.spark {
expand_all_rows_command = new DelegateCommand(_row_collection.expand_all);
grid_settings_manager = _create_grid_settings_manager(owner_title, bus, notification_service, model, rows, core_columns);
_resources = new List<IDisposable> {
model.on_orders.OnDispatcher().Subscribe(_row_collection.update),
model.on_order_tuples.OnDispatcher().Subscribe(_row_collection.update),
grid_settings_manager,
Disposable.Create(() => {
_columns.filter_changed -= on_filter_changed;
@@ -18,14 +18,16 @@ namespace bts.shell {
OrderBookWindowFactory _obwf;
FillsWindowFactory _fwf;
PAndLWindowFactory _plwf;
AlgoStudioWindowFactory _aswf;
[ImportingConstructor]
public TradingShellModule(IBus bus, IWindowManager wm, INotificationService notification_service, INotificationServiceDataCache notification_service_data_cache,
UserSettingsHub settings_hub, OrdersModel orders_model, PAndLModel pandl_model, MarketDataAuxiliaryModel md_auxiliary_model) {
UserSettingsHub settings_hub, OrdersModel orders_model, PAndLModel pandl_model, MarketDataAuxiliaryModel md_auxiliary_model, ErrorReporter error_reporter) {
_lwf = new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, md_auxiliary_model);
_obwf = new OrderBookWindowFactory(this, bus, notification_service, notification_service_data_cache, orders_model, settings_hub);
_fwf = new FillsWindowFactory(this, bus, settings_hub, orders_model);
_plwf = new PAndLWindowFactory(this, bus, settings_hub, pandl_model);
_aswf = new AlgoStudioWindowFactory(this, bus, orders_model, error_reporter);
}
public ImageSource icon => Icons.Trades;
@@ -39,7 +41,8 @@ namespace bts.shell {
SparkCommands.ShowFills.complete(() => new FillsWindowFactory.StartupData()),
SparkCommands.ShowPAndL.complete(() => new PAndLWindowFactory.PAndLStartupData()),
SparkCommands.PickLadder,
SparkCommands.PickOrderTicket
SparkCommands.PickOrderTicket,
SparkCommands.ShowAlgoStudio.complete(() => new AlgoStudioWindowFactory.StartupData())
};
IEnumerable<IShellWindowFactory> window_factories() {
@@ -47,6 +50,7 @@ namespace bts.shell {
yield return _obwf;
yield return _fwf;
yield return _plwf;
yield return _aswf;
}
public Task<IShellWindow> create(Stream load_stream) {
+14 -31
View File
@@ -1,7 +1,6 @@
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.utils;
using System;
using static bts.api.orderman.Fill.Types;
@@ -11,13 +10,17 @@ namespace mbts.spark {
public readonly FillImmutable fill;
public readonly OrderRecordImmutable? order;
public readonly SecurityImmutable? security;
public readonly FillTupleKey key;
public readonly AlgoData? algo;
public readonly AlgoDefinitionMetadata? algo_meta;
public FillTuple(FillImmutable fill, OrderRecordImmutable? order, SecurityImmutable? security) {
public FillTuple(FillImmutable fill, OrderSecurityAlgoMeta? order_tuple) {
this.fill = fill;
this.order = order;
this.security = security;
key = new FillTupleKey(fill.FillKey, order.HasValue ? order.Value.Key : 0u, security?.Id ?? 0);
if (order_tuple is OrderSecurityAlgoMeta osam) {
order = osam.order;
security = osam.security;
algo = osam.algo;
algo_meta = osam.meta;
}
}
public string account {
@@ -26,7 +29,7 @@ namespace mbts.spark {
if (fill.FillKind != FillKind.Sod && order.HasValue && order.Value.HasDef) account_string = order.Value.Def.Account;
else account_string = fill.Account;
return account_string == null ? string.Empty : account_string;
}
}
}
public bool Equals(FillTuple other) => other != null
@@ -35,31 +38,11 @@ namespace mbts.spark {
&& other.fill.Equals(fill);
public override bool Equals(object obj) => Equals(obj as FillTuple);
public override int GetHashCode() => key.GetHashCode();
}
struct FillTupleKey : IEquatable<FillTupleKey> {
public readonly string fill_key;
public readonly uint order_key, security_key;
public FillTupleKey(string fill_key, uint order_key, uint security_key) {
this.fill_key = fill_key;
this.order_key = order_key;
this.security_key = security_key;
}
public bool Equals(FillTupleKey other) =>
other.order_key == order_key &&
other.security_key == security_key &&
other.fill_key == fill_key;
public override bool Equals(object obj) =>
obj is FillTupleKey k && Equals(k);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
fill_key.GetHashCode(),
(int)order_key,
(int)security_key);
fill.FillKey.GetHashCode(),
order.HasValue ? order.Value.Key.GetHashCode() : 0,
security.HasValue ? security.Value.Id.GetHashCode() : 0);
}
}
}
-132
View File
@@ -1,132 +0,0 @@
using bts.api;
using bts.api.core;
using bts.api.orderman;
using mbts.collections;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
namespace mbts.spark {
class FillTupleSource : IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>>, IDisposable {
// returns a ref-count Observable.Create-wrapper that initializes/destroys the [hot-observable] FillTupleSource.
// (initializes when the first subscription is made, and destroys when the last subscription is disposed).
public static IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> create_observable(
IObservable<TableUpdate<(SecurityImmutable?,OrderRecordImmutable), uint>> orders,
IObservable<TableUpdate<(SecurityImmutable?,FillImmutable), string>> fills) {
FillTupleSource source = null;
int ref_count = 0;
return Observable.Create<IIncrementalUpdate<FillTuple, FillTupleKey>>(observer => {
if (Interlocked.Increment(ref ref_count) == 1) {
SparkUtils.lazy_assert(source == null, () => fmt_assert_msg("source should be null, there must be a leak."));
source = new FillTupleSource(orders, fills);
}
IDisposable sub = source.Subscribe(observer);
return Disposable.Create(() => {
Disposable.dispose_once(ref sub);
if (Interlocked.Decrement(ref ref_count) == 0)
Disposable.dispose_once(ref source);
});
});
string fmt_assert_msg(string msg) => $"{nameof(FillTupleSource)}.{nameof(create_observable)}: {msg}";
}
readonly Subject<IIncrementalUpdate<FillTuple, FillTupleKey>> _subject = new Subject<IIncrementalUpdate<FillTuple, FillTupleKey>>();
readonly Dictionary<FillTupleKey, FillTuple> _state = new Dictionary<FillTupleKey, FillTuple>();
readonly SetMap<uint, string> _order_fills = new SetMap<uint, string>();
readonly SetMap<uint, string> _security_fills = new SetMap<uint, string>();
IReadOnlyDictionary<string, (SecurityImmutable? sec, FillImmutable fill)> _fills_cache = new Dictionary<string, (SecurityImmutable?, FillImmutable)>();
IReadOnlyDictionary<uint, (SecurityImmutable?,OrderRecordImmutable)> _orders_cache = new Dictionary<uint, (SecurityImmutable?,OrderRecordImmutable)>();
IDisposable _dispose;
object _lock = new object();
FillTupleSource(
IObservable<TableUpdate<(SecurityImmutable?,OrderRecordImmutable), uint>> orders,
IObservable<TableUpdate<(SecurityImmutable?,FillImmutable), string>> fills) =>
//
_dispose = Disposable.Create(
orders.Subscribe(_update_orders),
fills.AddRemoveOnly().Subscribe(_update_fills));
public IDisposable Subscribe(IObserver<IIncrementalUpdate<FillTuple, FillTupleKey>> observer) {
lock (_lock) {
observer.OnNext(new IncrementalUpdate<FillTuple, FillTupleKey>(new Dictionary<FillTupleKey, FillTuple>(_state), new Dictionary<FillTupleKey, FillTuple>(0)));
return _subject.Subscribe(observer);
}
}
public void Dispose() => Disposable.dispose(ref _dispose);
void _update_fills(LegacyTableUpdate<(SecurityImmutable?,FillImmutable), string> fills) {
lock (_lock) {
var removed = new Dictionary<FillTupleKey, FillTuple>();
var added = new Dictionary<FillTupleKey, FillTuple>();
foreach (var (security,fill) in fills.removed) {
FillTuple old_ft = new FillTuple(fill, _get_order(fill.OrderKey), security);
removed.Add(old_ft.key, old_ft);
_security_fills.remove(fill.SecurityKey, fill.FillKey);
_order_fills.remove(fill.OrderKey, fill.FillKey);
}
foreach (var (security,fill) in fills.added) {
FillTuple new_ft = new FillTuple(fill, _get_order(fill.OrderKey), security);
added.Add(new_ft.key, new_ft);
_security_fills.add(fill.SecurityKey, fill.FillKey);
_order_fills.add(fill.OrderKey, fill.FillKey);
}
_fills_cache = fills.state;
_apply_changes(added, removed);
}
}
void _update_orders(TableUpdate<(SecurityImmutable?,OrderRecordImmutable order), uint> orders) {
lock (_lock) {
Dictionary<FillTupleKey, FillTuple> added = new Dictionary<FillTupleKey, FillTuple>(), removed = new Dictionary<FillTupleKey, FillTuple>();
HashSet<uint> changed_keys = new HashSet<uint>();
foreach (var (_,o) /*winking owl*/ in orders.removed) {
if (_order_fills.try_lookup(o.Key, out ISet<string> fill_keys)) {
OrderRecordImmutable? curr_order = null;
if (orders.try_get(o.Key, out var newval)) {
curr_order = newval.order;
changed_keys.Add(o.Key);
}
var fills = fill_keys.Select(fk => _fills_cache[fk]);
foreach (var (security, fill) in fills) {
FillTuple old_ft = new FillTuple(fill, o, security);
removed.Add(old_ft.key, old_ft);
FillTuple new_ft = new FillTuple(fill, curr_order, security);
added.Add(new_ft.key, new_ft);
}
}
}
foreach (var (_,o) in orders.added) {
if (!changed_keys.Contains(o.Key) && _order_fills.try_lookup(o.Key, out ISet<string> fill_keys)) {
var fills = fill_keys.Select(fk => _fills_cache[fk]);
foreach (var (security,fill) in fills) {
FillTuple old_ft = new FillTuple(fill, null, security);
removed.Add(old_ft.key, old_ft);
FillTuple new_ft = new FillTuple(fill, o, security);
added.Add(new_ft.key, new_ft);
}
}
}
_orders_cache = orders.state;
_apply_changes(added, removed);
}
}
OrderRecordImmutable? _get_order(uint key) =>
_orders_cache.TryGetValue(key, out var o) ? o.Item2 : new OrderRecordImmutable?();
void _apply_changes(Dictionary<FillTupleKey, FillTuple> added, Dictionary<FillTupleKey, FillTuple> removed) {
foreach (var kv in removed)
_state.Remove(kv.Key);
foreach (var kv in added)
_state.Add(kv.Key, kv.Value);
_subject.OnNext(new IncrementalUpdate<FillTuple, FillTupleKey>(added, removed));
}
}
}
@@ -0,0 +1,19 @@
using bts.api.orderman;
namespace mbts.spark {
struct NamedCustomOrderDefinition {
public readonly string id, display_name;
public readonly CustomOrderDefinitionImmutable definition;
public NamedCustomOrderDefinition(CustomOrderDefinitionImmutable definition)
: this(definition.CustomCase.type_id(), definition.CustomCase.display_name(), definition) { }
public NamedCustomOrderDefinition(CompositeAlgoRecordImmutable record)
: this(record.AlgoDefinition.Algo) { }
public NamedCustomOrderDefinition(string id, string display_name, CustomOrderDefinitionImmutable definition) {
this.id = id;
this.display_name = display_name;
this.definition = definition;
}
}
}
@@ -173,13 +173,15 @@
/>
<uag:OrderDetailsPopupControl
Grid.Row="2"
usp:OrderModificationControl.IsDirty="{Binding order_type_dirty, FallbackValue={u:False}}"
HasEditableProperties="{Binding properties_vm.selected_order_type.has_editable_properties, FallbackValue={u:False}}"
IsEnabled="{Binding can_change_order_type, FallbackValue={u:True}}"
IsOpen="{Binding properties_vm.selected_order_type.editable_properties_open, FallbackValue={u:False}}"
ItemsSource="{Binding properties_vm.order_types}"
Margin="0,2"
SelectedItem="{Binding properties_vm.selected_order_type}"
DataContext="{Binding properties_vm}"
usp:OrderModificationControl.IsDirty="{Binding DataContext.order_type_dirty, RelativeSource={RelativeSource AncestorType=usp:OrderModificationControl}, FallbackValue={u:False}}"
HasEditableProperties="{Binding can_expand, FallbackValue={u:False}}"
IsAlgoTemplateToolBarReadOnly="True"
IsEnabled="{Binding DataContext.can_change_order_type, RelativeSource={RelativeSource AncestorType=usp:OrderModificationControl}, FallbackValue={u:True}}"
IsOpen="{Binding is_expanded, FallbackValue={u:False}}"
ItemsSource="{Binding algo_definitions_view}"
SelectedItem="{Binding selected_algo_definition}"
>
<uag:OrderDetailsPopupControl.Style>
<Style TargetType="uag:OrderDetailsPopupControl" BasedOn="{StaticResource {x:Type uag:OrderDetailsPopupControl}}">
@@ -1,6 +1,4 @@
using bts.api.orderman;
using mbts.spark;
using System.Windows;
using System.Windows;
using System.Windows.Controls;
namespace mbts.ui.spark {
@@ -15,47 +13,4 @@ namespace mbts.ui.spark {
public OrderModificationControl() =>
InitializeComponent();
}
class OrderModificationTemplateSelector : DataTemplateSelector {
public DataTemplate StopLimitOrderTemplate { get; set; }
public DataTemplate StopMarketOrderTemplate { get; set; }
public DataTemplate TimeBoxOrderTemplate { get; set; }
public DataTemplate TickOrderTemplate { get; set; }
public DataTemplate LeanOrderTemplate { get; set; }
public DataTemplate JoinOrderTemplate { get; set; }
public DataTemplate TopOrderTemplate { get; set; }
public DataTemplate CoverOrderTemplate { get; set; }
public DataTemplate OCOOrderTemplate { get; set; }
public DataTemplate PricerOrderTemplate { get; set; }
public DataTemplate OffsetOrderTemplate { get; set; }
public DataTemplate TriggerOrderTemplate { get; set; }
public DataTemplate IcebergOrderTemplate { get; set; }
public DataTemplate SpreaderTemplate { get; set; }
public DataTemplate DynamicOrderTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
var vm = item as IOrderTypeVM;
if (vm != null) {
switch (vm.order_type) {
case CustomOrderDefinition.CustomOneofCase.Stop: return StopMarketOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.StopLimit: return StopLimitOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.TimeBox: return TimeBoxOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Tick: return TickOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Lean: return LeanOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Join: return JoinOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Top: return TopOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Cover: return CoverOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Oco : return OCOOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Pricer: return PricerOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Offset: return OffsetOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Trigger: return TriggerOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Iceberg: return IcebergOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Spreader: return SpreaderTemplate;
case CustomOrderDefinition.CustomOneofCase.Dynamic: return DynamicOrderTemplate;
}
}
return null;
}
}
}
}
+324 -125
View File
@@ -1,71 +1,30 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.collections;
using bts.spark;
using bts.utils;
using mbts.collections;
using mbts.spark.utilities;
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.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
namespace mbts.spark {
struct OrderTemplateKey : IEquatable<OrderTemplateKey> {
public readonly CustomOrderDefinition.CustomOneofCase type;
public readonly string name;
public OrderTemplateKey(CustomOrderDefinition.CustomOneofCase type)
: this(type, OrderUtils.order_type_display_name(type)) { }
public OrderTemplateKey(CustomOrderDefinition.CustomOneofCase type, string name) {
this.type = type;
this.name = name;
}
public bool Equals(OrderTemplateKey other) =>
type == other.type &&
name == other.name;
public override bool Equals(object obj) =>
obj is OrderTemplateKey other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
type.GetHashCode(),
name == null ? 0 : name.GetHashCode());
public override string ToString() => $"{name}:{type}";
public static bool operator ==(OrderTemplateKey a, OrderTemplateKey b) => a.Equals(b);
public static bool operator !=(OrderTemplateKey a, OrderTemplateKey b) => !a.Equals(b);
}
struct OrderTemplateHeader : IEquatable<OrderTemplateHeader> {
public readonly OrderTemplateKey key;
// Note: display_name is NOT part of EQUALITY
public readonly string display_name;
public OrderTemplateHeader(CustomOrderDefinition.CustomOneofCase type)
: this(new OrderTemplateKey(type), OrderUtils.order_type_display_name(type)) { }
public OrderTemplateHeader(OrderTemplateKey key, string display_name) {
this.key = key;
this.display_name = display_name;
}
public bool Equals(OrderTemplateHeader other) =>
key.Equals(other.key);
public override bool Equals(object obj) =>
obj is OrderTemplateHeader other && Equals(other);
public override int GetHashCode() => key.GetHashCode();
public override string ToString() => $"{display_name} ({key})";
}
class InlineOrderProperties {
public readonly InlineUserProperty<AccountTuple> account;
public readonly InlineUserProperty<TimeInForce> time_in_force;
@@ -90,100 +49,295 @@ namespace mbts.spark {
this.order_type_def = order_type_def ?? new InlineUserProperty<CustomOrderDefinition>();
}
}
class OrderPropertiesEditorVM : DisposableViewModelBase {
readonly OrdersModel _model;
readonly Property<SecurityImmutable> _security;
readonly Property<AlgoDefinitionTemplateVM> _selected_algo_template, _selected_favorite_algo_template;
readonly SelectorProperty<AccountTuple, AccountTuple?> _accounts;
readonly SelectorProperty<TimeInForce> _time_in_force;
readonly SelectorProperty<IOrderTypeVM> _order_type;
IDisposable _order_type_param_errors_sub;
readonly SelectionModel<AlgoDefinitionVM> _selected_algo_definition;
readonly ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey> _algo_definitions = new ObservableKeyedCollection<AlgoDefinitionVM, AlgoKey>(d => d.key);
readonly ListCollectionView<AlgoDefinitionVM> _algo_definitions_view, _favorite_algo_definitions_view;
readonly TableUpdateBuffer<AlgoData, AlgoKey> _definitions_buffer = new TableUpdateBuffer<AlgoData, AlgoKey>(d => d.key);
readonly EditableCollectionModel<AlgoDefinitionTemplateVM, AlgoDefinitionVM> _algo_template_collection_model;
readonly ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoKey> _favorite_templates = new ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoKey>(tvm => tvm.key);
IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata> _algo_metadata = DictionaryHelper.empty<AlgoKey, AlgoDefinitionMetadata>();
IReadOnlyDictionary<AlgoKey, int> _favorite_algos_index = DictionaryHelper.empty<AlgoKey, int>();
int _favorite_algos_column_count;
bool _open_algo_popup_on_select;
public OrderPropertiesEditorVM(OrdersModel model, IObservable<SecurityMD> security_md_source, IObservable<InlineOrderProperties> order_properties) {
_model = model;
var security_source = security_md_source.Select(smd => smd.security);
_security = backing(nameof(security), security_source.OnDispatcher(), SecurityDataHelper.Defaults.SecurityImmutable);
// guarentee that "this.security" will always be set before observers are notified
// this is important bc some observers will reference "this.security" in their callbacks
// - namely the [SelectorProperty]order_type's "get_default" function,
// which may be called in response to its items changing, which are driven by the observable security
// (see 'get_default_order_type_vm')
security_source = _security.observe_current(true).Replay(1).RefCount();
_security = backing(nameof(security), security_source, SecurityDataHelper.Defaults.SecurityImmutable);
security_source = _security.observe_current(true);
_selected_algo_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_algo_template));
_selected_algo_definition = new SelectionModel<AlgoDefinitionVM>(algo_definitions,
() => {
var t = _model.factory.default_order_type(security);
return algo_definitions.FirstOrDefault(d => d.algo_root?.order_type == t, d => true);
});
_algo_definitions_view = new ListCollectionView<AlgoDefinitionVM>(_algo_definitions) {
CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic(),
IsLiveSorting = true
};
algo_definitions_view.Filter = d => {
if (d.key.mode == AlgoKey.Mode.Persisted && _algo_metadata.TryGetValue(d.key, out AlgoDefinitionMetadata meta) && meta.is_hidden)
return false;
var sec_fmt = OrderDataHelper.get_algo_format(security.ContractCase);
return (d.selected_format & sec_fmt) == sec_fmt;
};
_algo_definitions_view.LiveFilteringProperties.Add(nameof(AlgoDefinitionVM.selected_format));
_algo_definitions_view.LiveSortingProperties.Add(nameof(AlgoDefinitionVM.name));
algo_definitions_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AlgoDefinitionVM.is_factory_definition)));
_favorite_algo_definitions_view = new ListCollectionView<AlgoDefinitionVM>(_algo_definitions);
_favorite_algo_definitions_view.SortDescriptions.Add(new SortDescription(nameof(AlgoDefinitionVM.favorite_index), ListSortDirection.Ascending));
_favorite_algo_definitions_view.LiveSortingProperties.Add(nameof(AlgoDefinitionVM.favorite_index));
_favorite_algo_definitions_view.IsLiveSorting = true;
_favorite_algo_definitions_view.LiveFilteringProperties.Add(nameof(AlgoDefinitionVM.is_favorite));
_favorite_algo_definitions_view.IsLiveFiltering = true;
favorite_algo_definitions_view.Filter = d => d.is_favorite;
_accounts = backing(
nameof(selected_account),
model.factory.subscribe_account_tuples(),
order_properties.Select(ops => ops.account),
a => new AccountTuple?(a),
() => {
foreach (var a in accounts) {
return a;
}
return new AccountTuple?();
},
() => accounts.Cast<AccountTuple?>().FirstOrDefault(),
EqualityComparer<AccountTuple?>.Default,
new[] { new PropertyValidation<AccountTuple?>(a => (a.HasValue && !string.IsNullOrWhiteSpace(a.Value.name) && accounts.Contains(a.Value), "Please select an account")) }.ToReadOnlyList());
_order_type = backing(
nameof(selected_order_type),
security_source.Select(s => model.factory.default_order_type_templates(s).Select(kv => create_order_type_vm(kv.Value, kv.Key.key.name, kv.Key.display_name))),
order_properties.Select(get_order_type_vm_prop),
get_default_order_type_vm,
EqualityComparer.null_check_wrapper(OrderTypeVMExtensions.key_comparer));
_order_type.Changed += on_selected_order_type_changed;
_time_in_force = backing(
nameof(selected_time_in_force),
// remember, both observables must fire once to start the CombineLatest sequence
security_source.CombineLatest(_order_type.observe_current(true)).Select(
t => model.factory.default_time_in_forces(t.Item1, t.Item2?.order_type ?? CustomOrderDefinition.CustomOneofCase.None)),
security_source.CombineLatest(_selected_algo_definition.observe_selected_item(true)).Select(
t => model.factory.default_time_in_forces(t.Item1, t.Item2?.algo_root?.order_type ?? CustomOrderDefinition.CustomOneofCase.None)),
order_properties.Select(ops => ops.time_in_force),
() => model.factory.default_time_in_force(security),
tif => time_in_forces.Contains(tif));
_dispose = Disposable.Create(() => _order_type.Changed -= on_selected_order_type_changed);
// local methods
IOrderTypeVM create_order_type_vm(CustomOrderDefinitionImmutable? cd, string id, string display_name) {
IOrderTypeVM vm = null;
if(cd?.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic)
vm = OrderTypeVMFactory.create(cd.Value.CustomCase, id, display_name, model, security_md_source, cd.Value.Dynamic.DynamicOrderType);
else
vm = OrderTypeVMFactory.create(cd.Value.CustomCase, id, display_name, model, security_md_source);
vm.load_from(cd.Value);
return vm;
}
InlineUserProperty<IOrderTypeVM> get_order_type_vm_prop(InlineOrderProperties p) {
if (!p.order_type_def.has_value)
return new InlineUserProperty<IOrderTypeVM>();
return new InlineUserProperty<IOrderTypeVM>(
create_order_type_vm(p.order_type_def.value, p.order_type_def.value.CustomCase.ToString(),
OrderUtils.order_type_display_name(p.order_type_def.value.CustomCase)),
p.order_type_def.force_override);
}
IOrderTypeVM get_default_order_type_vm() {
var ot = model.factory.default_order_type(security);
if (order_types.TryGetFirst(vm => vm.order_type == ot, out IOrderTypeVM result))
return result;
return order_types.FirstOrDefault();
}
void on_selected_order_type_changed(IOrderTypeVM old_val, IOrderTypeVM new_val) {
if (new_val == null) {
assert(false);
} else {
assert(order_types.Contains(new_val));
new_val.init();
if (new_val is INotifyDataErrorInfo ndei) {
assert_no_param_errors();
_order_type_param_errors_sub = ndei.subscribe_errors_changed((s, e) => assert_no_param_errors());
void assert_no_param_errors() => assert(!ndei.HasErrors, "order type pararmeters invalid.");
_selected_favorite_algo_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_favorite_algo_template));
// items source views
algo_templates_view = CollectionViewSource.GetDefaultView(algo_templates);
var favorite_algo_templates_view = new ListCollectionView(ObservableAggregateCollection.create(_algo_definitions.AsCollection(), d => d.templates));
favorite_algo_templates_view.LiveGroupingProperties.Add(nameof(AlgoDefinitionTemplateVM.owner_key));
favorite_algo_templates_view.LiveFilteringProperties.Add(nameof(AlgoDefinitionTemplateVM.is_favorite));
favorite_algo_templates_view.Filter = item => (item as AlgoDefinitionTemplateVM)?.is_favorite ?? false;
favorite_algo_templates_view.IsLiveFiltering = true;
this.favorite_algo_templates_view = favorite_algo_templates_view;
// commands
save_definition_cmd = new AsyncCommand<AlgoDefinitionVM>(save_definition_async);
save_template_cmd = new AsyncCommand<AlgoDefinitionTemplateVM>(save_template_async);
remove_template_cmd = new AsyncCommand<AlgoDefinitionTemplateVM>(tvm => _model.algo_model.remove_template(tvm.key));
toggle_is_favorite_cmd = new DelegateCommand<AlgoDefinitionTemplateVM>(tvm => _favorite_templates.Add(tvm));
_algo_template_collection_model = new EditableCollectionModel<AlgoDefinitionTemplateVM, AlgoDefinitionVM>(d => selected_algo_definition == null ? default : selected_algo_definition.template_factory(), d => d != null);
redo_cmd = ObservantCommand.create(
t => t?.redo(),
t => t == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => t.can_redo_changed += cb, cb => t.can_redo_changed -= cb, () => t.can_redo).OnDispatcher(),
out IObserver<AlgoDefinitionTemplateVM> redo_observer);
undo_cmd = ObservantCommand.create(
t => t?.undo(),
t => t == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => t.can_undo_changed += cb, cb => t.can_undo_changed -= cb, () => t.can_undo).OnDispatcher(),
out IObserver<AlgoDefinitionTemplateVM> undo_observer);
undo_definition_cmd = ObservantCommand.create(
d => d?.undo(),
d => d == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => d.can_undo_changed += cb, cb => d.can_undo_changed -= cb, () => d.can_undo).OnDispatcher(),
out IObserver<AlgoDefinitionVM> undo_definition_observer);
redo_definition_cmd = ObservantCommand.create(
d => d?.redo(),
d => d == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => d.can_redo_changed += cb, cb => d.can_redo_changed -= cb, () => d.can_redo).OnDispatcher(),
out IObserver<AlgoDefinitionVM> redo_definition_observer);
revert_definition_cmd = ObservantCommand.create(
d => d.load_committed(),
d => d == null ? Observable.Return(false) : d.subscribe_is_definition_dirty(),
out IObserver<AlgoDefinitionVM> revert_definition_observer);
var nullable_security_md_source = security_md_source.Select(smd => new SecurityMD?(smd)).RefCountReplay(1);
//
_dispose = new CompositeDisposable(
_selected_algo_definition.subscribe_changed(_selected_algo_definition_Changed),
as_demuxer().subscribe<AlgoDefinitionTemplateVM>(nameof(selected_algo_template)).Subscribe(
undo_observer,
redo_observer),
as_demuxer().subscribe<AlgoDefinitionVM>(nameof(selected_algo_definition)).Subscribe(
undo_definition_observer,
redo_definition_observer,
revert_definition_observer),
algo_definitions.Subscribe((s, e) => {
if (e.OldItems != null)
e.OldItems.OfType<IDisposable>().DisposeAll();
if (e.NewItems != null) {
foreach (AlgoDefinitionVM d in e.NewItems) {
switch (d.key.mode) {
case AlgoKey.Mode.Persisted:
if (_model.algo_model.ui_configuration.include_custom_templates && _model.algo_model.templates_enabled())
d.prepend_custom_template();
break;
case AlgoKey.Mode.Factory:
if (_model.algo_model.ui_configuration.include_legacy_custom_templates && _model.algo_model.templates_enabled())
d.prepend_custom_template();
break;
}
}
}
}),
security_md_source.Select(smd => model.factory.default_algos(smd.security)).Table(s => s.key).Subscribe(factory_defs => {
using (_selected_algo_definition.begin_update())
AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, factory_defs, fd => {
var vm = AlgoDefinitionVM.create(_model, fd, init_format: OrderDataHelper.get_algo_format(security.ContractCase));
vm.selected_format = OrderDataHelper.get_algo_format(security.ContractCase);
return vm;
});
}),
model.algo_model.definitions.Subscribe(_definitions_buffer),
_definitions_buffer.OnDispatcher().Subscribe(u => {
AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, u, def_data => {
var def_vm = AlgoDefinitionVM.create(model, def_data, true, OrderDataHelper.get_algo_format(security.ContractCase));
def_vm.selected_format = OrderDataHelper.get_algo_format(security.ContractCase);
def_vm.favorite_index = _get_favorite_algo_index(def_vm.key);
return def_vm;
});
}),
model.algo_model.metadata_service.subscribe_metadata().OnDispatcher().Subscribe(_on_template_metadata),
ObservableAutoWrapper.connect_item_hooks(algo_definitions, vm =>
Disposable.Create(
vm.connect_data(nullable_security_md_source),
security_source.Subscribe(s => {
var fmt = OrderDataHelper.get_algo_format(s.ContractCase);
foreach (var d in algo_definitions)
d.selected_format = fmt;
}),
vm), true)) {
() => Disposable.dispose(ref _template_collection_sync)
};
async Task save_template_async(AlgoDefinitionTemplateVM template) {
using (_preserve_selection_by_index())
await AlgoPersistenceHelper.persist_template(model, algo_definitions, template);
}
async Task save_definition_async(AlgoDefinitionVM definition) {
switch (definition.key.mode) {
case AlgoKey.Mode.Persisted:
await AlgoPersistenceHelper.persist_definition(model, algo_definitions, definition);
break;
case AlgoKey.Mode.Factory:
case AlgoKey.Mode.Unpersisted:
using (_definitions_buffer.buffer_updates()) {
var persisted_key_lookup = await AlgoPersistenceHelper.persist_definition(model, algo_definitions, definition);
if (persisted_key_lookup.TryGetValue(definition.key, out AlgoKey pkey) && _algo_definitions.TryGetValue(pkey, out AlgoDefinitionVM pdef))
selected_algo_definition = pdef;
if (definition.key.mode == AlgoKey.Mode.Factory) {
/// Revert the factory definition to its original state.
/// Note: this won't revert the parameters in the algo popup since the newly persisted definition (<see cref="pdef"/>) is selected now.
definition.load_committed();
}
}
break;
}
}
}
IDisposable _template_collection_sync;
void _selected_algo_definition_Changed(AlgoDefinitionVM old_value, AlgoDefinitionVM new_value, SelectionReason reason) {
Disposable.dispose(ref _template_collection_sync);
if (new_value != null) {
_template_collection_sync = ObservableAutoWrapper.connect_two_way(new_value.templates_with_custom, algo_templates);
} else {
algo_templates.Clear();
}
if (open_algo_popup_on_select) {
if (reason == SelectionReason.UserSelectedNewValue && new_value?.algo_root is IAlgoVM ar && ar.can_expand)
ar.is_expanded = true;
}
if (selected_algo_template == null && _model.algo_model.templates_enabled()) {
if (new_value != null)
selected_algo_template = new_value.templates.FirstOrDefault(tvm => tvm.is_default, tvm => _favorite_templates.ContainsKey(tvm.key), tvm => true) ?? new_value.templates_with_custom.FirstOrDefault();
} else {
RaisePropertyChanged(nameof(selected_algo_template));
}
RaisePropertyChanged(nameof(selected_algo_definition), nameof(selected_favorite_algo_definition), nameof(can_expand), nameof(is_expanded));
_selected_favorite_algo_template.Value = selected_algo_template is AlgoDefinitionTemplateVM t && t.is_favorite ? t : null;
_algo_template_collection_model.OnNext(new_value);
}
public SecurityImmutable security => _security.Value;
public ReadOnlyObservableCollection<AccountTuple> accounts => _accounts.items;
public AccountTuple? selected_account { get => _accounts.selected_item; set => _accounts.selected_item = value; }
public ReadOnlyObservableCollection<TimeInForce> time_in_forces => _time_in_force.items;
public TimeInForce selected_time_in_force { get => _time_in_force.selected_item; set => _time_in_force.selected_item = value; }
public ReadOnlyObservableCollection<IOrderTypeVM> order_types => _order_type.items;
public IOrderTypeVM selected_order_type { get => _order_type.selected_item; set => _order_type.selected_item = value; }
public CustomOrderDefinitionImmutable? definition => selected_algo_template?.algo_root?.definition;
public int favorite_algos_column_count { get => _favorite_algos_column_count; private set => Set(ref _favorite_algos_column_count, value); }
// items sources
public ObservableCollection<AlgoDefinitionVM> algo_definitions => _algo_definitions;
public ObservableCollection<AlgoDefinitionTemplateVM> algo_templates { get; } = new ObservableCollection<AlgoDefinitionTemplateVM>();
public ICollectionView<AlgoDefinitionVM> algo_definitions_view => _algo_definitions_view;
public ICollectionView<AlgoDefinitionVM> favorite_algo_definitions_view => _favorite_algo_definitions_view;
public ICollectionView algo_templates_view { get; }
public ICollectionView favorite_algo_templates_view { get; }
// selected items
public AlgoDefinitionVM selected_algo_definition {
get => _selected_algo_definition.selected_item;
set => _selected_algo_definition.selected_item = value;
}
public AlgoDefinitionTemplateVM selected_algo_template {
get => selected_algo_definition?.selected_template;
set {
if (value != selected_algo_template) {
if (value == null) {
if (selected_algo_definition != null)
selected_algo_definition.selected_template = null;
_selected_favorite_algo_template.set(null);
} else {
value.owner.selected_template = value;
_selected_algo_definition.select_explicit(value.owner); // idempotent
_selected_favorite_algo_template.Value = value.is_favorite ? value : null; // idempotent
}
RaisePropertyChanged();
}
}
}
public AlgoDefinitionTemplateVM selected_favorite_algo_template {
get => _selected_favorite_algo_template.Value;
set {
if (_selected_favorite_algo_template.set_new(value)) {
if (value != null) {
value.owner.selected_template = value;
if (value.owner != selected_algo_definition)
_selected_algo_definition.select_explicit(value.owner);
RaisePropertyChanged(nameof(selected_algo_template));
}
}
}
}
public AlgoDefinitionVM selected_favorite_algo_definition {
get => selected_algo_definition?.is_favorite ?? false ? selected_algo_definition : null;
set {
if (value != null)
_selected_algo_definition.select_explicit(value);
RaisePropertyChanged();
}
}
public bool can_expand => selected_algo_definition?.algo_root?.can_expand ?? false;
public bool is_expanded {
get => selected_algo_definition?.algo_root?.is_expanded ?? false;
set {
if (selected_algo_definition?.algo_root is IAlgoVM vm) {
if (vm.is_expanded != value) {
vm.is_expanded = value;
RaisePropertyChanged();
}
}
}
}
public bool open_algo_popup_on_select { get => _open_algo_popup_on_select; set => Set(ref _open_algo_popup_on_select, value); }
// commands
public ICommand save_definition_cmd { get; }
public ICommand save_template_cmd { get; }
public ICommand revert_definition_cmd { get; }
public ICommand undo_cmd { get; }
public ICommand redo_cmd { get; }
public ICommand undo_definition_cmd { get; }
public ICommand redo_definition_cmd { get; }
public ICommand remove_template_cmd { get; }
public ICommand toggle_is_favorite_cmd { get; }
public IEditableCollectionModel<AlgoDefinitionTemplateVM> algo_template_collection_model => _algo_template_collection_model;
public IObservable<AccountTuple?> observe_account(bool start_immediately = false) =>
_accounts.observe_current(start_immediately);
@@ -191,8 +345,8 @@ namespace mbts.spark {
public IObservable<TimeInForce> observe_time_in_force(bool start_immediately = false) =>
_time_in_force.observe_current(start_immediately);
public IObservable<IOrderTypeVM> observe_order_type(bool start_immediately = false) =>
_order_type.observe_current(start_immediately);
public IObservable<IAlgoVM> observe_order_type(bool start_immediately = false) =>
_selected_algo_template.observe_current(start_immediately).Select(t => t.algo_root);
public OrderDefinition create(Side side) {
if (HasErrors)
@@ -200,14 +354,59 @@ namespace mbts.spark {
var order = _model.factory.order(security, selected_account);
order.TimeInForce = selected_time_in_force;
order.Side = side;
selected_order_type.assign_to(order.CustomDef);
if (_model.algo_model.templates_enabled()) {
selected_algo_template.algo_root.assign_to(order.CustomDef);
} else {
selected_algo_definition.algo_root.assign_to(order.CustomDef);
if (selected_algo_definition.key.mode == AlgoKey.Mode.Persisted)
order.AlgoTemplateKey = selected_algo_definition.key.persisted.id_uint;
}
return order;
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
Disposable.dispose(ref _order_type_param_errors_sub);
_order_type.items.OfType<IDisposable>().DisposeAll();
public OrderMetadata get_metadata(CustomOrderDefinition.CustomOneofCase order_type) =>
_model.factory.get_metadata(order_type);
public void on_favorite_algos(LadderFavoriteAlgosSettings value) {
_favorite_algos_index = value.favorite_algos.Select((v, i) => (v, i)).ToDictionaryCrushed(t => t.v, t => t.i);
foreach (var d in algo_definitions) {
d.favorite_index = _get_favorite_algo_index(d.key);
foreach (var t in d.templates) {
if (t.key.mode == AlgoKey.Mode.Persisted)
t.is_favorite = _favorite_algos_index.ContainsKey(t.key);
}
}
favorite_algos_column_count = value.column_count;
}
}
}
int? _get_favorite_algo_index(AlgoKey key) =>
key.mode == AlgoKey.Mode.Persisted && _favorite_algos_index.TryGetValue(key, out int i) ? i : (int?)null;
void _on_template_metadata(IReadOnlyDictionary<AlgoKey, AlgoDefinitionMetadata> meta) {
_algo_metadata = meta;
var curr_selected_template = selected_algo_template;
if (curr_selected_template?.is_favorite ?? false)
selected_favorite_algo_template = curr_selected_template;
algo_definitions_view.Refresh();
}
// This preserves the selected items through a save op.
// When a definition/template is persisted for the first time, its unpersisted-placeholder item is removed and replaced with a new persisted one.
// If an unpersisted item is selected when it is removed, the view will automatically select null - this method is a workaround for that.
IDisposable _preserve_selection_by_index() {
(int? selected_def_index, int? selected_tmp_index) = AlgoPersistenceHelper.selection_snapshot(algo_definitions, selected_algo_definition, selected_algo_template);
return new CompositeDisposable(_definitions_buffer.buffer_updates()) {
() => {
if (selected_def_index is int di && algo_definitions.check_index(di)) {
var def = algo_definitions[di];
if (selected_tmp_index is int ti && def.templates.check_index(ti)) {
selected_algo_template = def.templates[ti];
} else {
selected_algo_definition = def;
}
}
}
};
}
}
}
+36 -2
View File
@@ -1,4 +1,6 @@
using System;
using bts.utils;
using mbts.spark;
using System;
namespace bts.api.orderman {
public readonly struct OrderSecurity: IEquatable<OrderSecurity> {
@@ -22,4 +24,36 @@ namespace bts.api.orderman {
public static bool operator != (OrderSecurity left, OrderSecurity right) => !left.Equals(right);
}
}
struct OrderSecurityAlgoMeta : IEquatable<OrderSecurityAlgoMeta> {
public readonly OrderRecordImmutable order;
public readonly SecurityImmutable? security;
public readonly AlgoData? algo;
public readonly AlgoDefinitionMetadata? meta;
public OrderSecurityAlgoMeta(OrderRecordImmutable order, SecurityImmutable? security, AlgoData? algo, AlgoDefinitionMetadata? meta) {
this.order = order;
this.security = security;
this.algo = algo;
this.meta = meta;
}
public bool Equals(OrderSecurityAlgoMeta other) =>
order == other.order &&
security == other.security &&
algo == other.algo &&
meta == other.meta;
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
order.GetHashCode(),
security?.GetHashCode() ?? 0,
algo?.GetHashCode() ?? 0,
meta?.GetHashCode() ?? 0);
public static bool operator ==(OrderSecurityAlgoMeta a, OrderSecurityAlgoMeta b) => a.Equals(b);
public static bool operator !=(OrderSecurityAlgoMeta a, OrderSecurityAlgoMeta b) => !a.Equals(b);
}
}
@@ -1,246 +1,15 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using bts.api.orderman;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineCoverOrderProperties
{
public InlineCoverOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class CoverOrderVM : OrderTypeVMBase<CoverOrderDefinition, CoverOrderDefinitionImmutable> {
readonly Property<int> _hedge_ticks;
var hedgetype = CustomOneofCase.Limit;
this.selected_hedge_order_type = new InlineUserProperty<OrderTemplateHeader>(new OrderTemplateHeader(hedgetype), true);
this.hedge_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
public CoverOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) =>
_hedge_ticks = add_property(nameof(hedge_ticks), CoverOrderDefinition.HedgeTicksFieldNumber, 1);
hedge_ticks = new InlineUserProperty<int>(1, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<OrderTemplateHeader> selected_hedge_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> hedge_order_types;
public readonly InlineUserProperty<int> hedge_ticks;
}
class CoverOrderVM : OrderTypeVMBase<CoverOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineCoverOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _hedge_order_choices;
IOrderTypeVM _hedge_order;
IDisposable _hedge_order_errors_sub;
public int hedge_ticks { get; set; } = 1;
public CoverOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineCoverOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name)
{ }
public CoverOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineCoverOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (_hedge_order_choices != null && (_hedge_order == null || p.selected_hedge_order_type.force_override))
{
_select_hedge_order(p.selected_hedge_order_type.value.key.type);
}
if (p.hedge_ticks.force_override)
{
hedge_ticks = p.hedge_ticks.value;
RaisePropertyChanged(nameof(hedge_ticks));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
if (_hedge_order == null )
_select_hedge_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.cover_order();
i.HedgeTicks = hedge_ticks;
child_order.assign_to(i.Child);
if (hedge_order != null)
hedge_order.assign_to(i.Hedge);
value.Cover = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public ICollection<IOrderTypeVM> hedge_order_types
{
get
{
if (_hedge_order_choices == null)
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _hedge_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public IOrderTypeVM hedge_order
{
get
{
init();
return _hedge_order;
}
set
{
Disposable.dispose(ref _hedge_order_errors_sub);
_hedge_order = value;
_hedge_order?.init();
if (_hedge_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_hedge_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(hedge_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
if (_hedge_order_choices != null)
_hedge_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
if (_hedge_order == null && _security.HasValue)
_select_hedge_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _select_hedge_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_hedge_order_type.has_value ?
_inline_props.selected_hedge_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_hedge_order(ot);
}
void _select_hedge_order(CustomOneofCase ot)
{
_hedge_order = hedge_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_hedge_order == null)
_hedge_order = hedge_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(hedge_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
if ((_hedge_order == null ) || (_hedge_order is INotifyDataErrorInfo hdei && hdei.HasErrors))
set_error(nameof(hedge_order), string.Empty, true);
else clear_error(nameof(hedge_order));
}
public int hedge_ticks { get => _hedge_ticks.Value; set => _hedge_ticks.set(value); }
}
}
}
@@ -0,0 +1,110 @@
using bts.spark;
using mbts.spark.utilities;
using mbts.ui.shell;
using mbts.utils;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using AlgoDef = bts.api.orderman.CustomOrderDefinition;
using AlgoDefi = bts.api.orderman.CustomOrderDefinitionImmutable;
using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
namespace mbts.spark {
class DefaultAlgoVM : DisposableViewModelBase, IAlgoVM, IDynamicAlgoVMImpl, IObserver<SecurityMD?>, IObserver<OrdersModel> {
static readonly AlgoDefi _empty = new AlgoDefi(new AlgoDef());
readonly VersionContainer<AlgoDefi> _definition;
AlgoFormats _format;
AlgoEditingPermissions _editing_permissions;
SecurityMD? _security_md;
OrdersModel _model;
public DefaultAlgoVM() =>
_definition = new VersionContainer<AlgoDefi>(() =>
impl?.definition ?? _empty);
public event Action definition_changed;
public IAlgoVM impl { get; private set; }
public AlgoKey id { get; } = new AlgoKey(AlgoType.None);
public AlgoType order_type => _definition.value.CustomCase;
public bool is_bts_type => false;
public OrderMetadata meta => OrderDataHelper.get_metadata(order_type);
public bool can_expand => impl?.can_expand ?? false;
public bool is_expanded {
get => false;
set {
if (impl != null)
impl.is_expanded = value;
}
}
public bool can_edit_values => impl?.can_edit_values ?? false;
public bool can_edit_structure => impl?.can_edit_structure ?? false;
public bool can_save_values => impl?.can_save_values ?? false;
public bool can_save_structure => impl?.can_save_structure ?? false;
public string display_name => impl?.display_name ?? "(Default)";
public AlgoDefi definition => _definition.value;
public ObservableCollection<IAlgoSelector> child_algo_selectors { get; } = new ObservableCollection<IAlgoSelector>();
public void assign_to(AlgoDef value) => value.MergeFrom(definition.CloneToMutable());
public bool key_match(KeyEventArgs e) => false;
public void load_from(AlgoDefi value) => impl?.load_from(value);
public void set_permissions(AlgoEditingPermissions editing_permissions) {
_editing_permissions = editing_permissions;
impl?.set_permissions(editing_permissions);
}
public Task<AlgoDefi?> load_from_async(AlgoDefi definition) =>
impl?.load_from_async(definition) ?? Task.FromResult<AlgoDefi?>(definition);
protected override void Dispose(bool disposing) =>
_clear_impl();
void _clear_impl() {
if (impl != null) {
impl.definition_changed -= _on_impl_definition_changed;
(impl as IDisposable)?.Dispose();
impl = null;
}
}
void IObserver<OrdersModel>.OnCompleted() { }
void IObserver<OrdersModel>.OnError(Exception error) { }
void IObserver<OrdersModel>.OnNext(OrdersModel model) {
_model = model;
(impl as IObserver<OrdersModel>)?.OnNext(model);
}
void IObserver<SecurityMD?>.OnCompleted() { }
void IObserver<SecurityMD?>.OnError(Exception error) { }
void IObserver<SecurityMD?>.OnNext(SecurityMD? security_md) {
_security_md = security_md;
if (security_md.HasValue)
_format = OrderDataHelper.get_algo_format(security_md.Value.security.ContractCase);
var orig_def = definition;
var fmt_type = OrderDataHelper.get_default_algo(_format);
switch (fmt_type) {
case AlgoType.None: _clear_impl(); break;
default:
if (impl != null && impl.order_type == fmt_type)
break;
_clear_impl();
impl = OrderTypeVMFactory.create(new AlgoKey(fmt_type), fmt_type.display_name(), fmt_type, is_expanded: true);
(impl as IObserver<OrdersModel>)?.OnNext(_model);
break;
}
if (impl != null) {
(impl as IObserver<SecurityMD?>)?.OnNext(security_md);
impl.definition_changed += _on_impl_definition_changed;
}
_on_impl_definition_changed();
}
void _on_impl_definition_changed() {
var orig_def = definition;
_definition.increment_version();
if (!OrderDataHelper.EqualsHelpers.equals(definition, orig_def))
definition_changed?.Invoke();
if (order_type != orig_def.CustomCase)
RaisePropertyChanged(nameof(order_type), nameof(meta));
}
}
}
@@ -1,19 +1,12 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
namespace mbts.spark
{
namespace mbts.spark {
[Export]
public class DynamicOrderHelper
{
@@ -35,20 +28,11 @@ namespace mbts.spark
foreach(var p in d.ParamDesc)
dorder.Dynamic.OrderParams.Add( p.ParamName, new DynamicOrderParam() );
defs.Add(new CustomOrderDefinitionImmutable(dorder));
var de = get_descriptor("");
}
}
internal IDictionary<string, DynamicOrderParamVM> get_parameters(string dyntype)
{
Dictionary<string, DynamicOrderParamVM> par = new Dictionary<string, DynamicOrderParamVM>();
var order = _dynamic_types.DynamicOrderDesc.FirstOrDefault(x => x.DynamicOrderType == dyntype);
if (order != null)
{
foreach (var p in order.ParamDesc)
par[p.ParamName] = new DynamicOrderParamVM() { param = new DynamicOrderParam(), descriptor = p };
}
return par;
}
internal DynamicOrderDescriptor get_descriptor(string dynamic_type) =>
_dynamic_types.DynamicOrderDesc.FirstOrDefault(d => d.DynamicOrderType == dynamic_type);
}
}
@@ -1,21 +1,58 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using Google.Protobuf.Reflection;
using mbts.ui.shell;
using mbts.utils;
using System;
using System.Collections.Generic;
namespace mbts.spark {
abstract class DynamicOrderParamVM : ViewModelBase {
DynamicOrderParam _param = new DynamicOrderParam();
namespace mbts.spark
{
protected DynamicOrderParamVM(DynamicOrderParamDescriptor descriptor) =>
this.descriptor = descriptor;
class DynamicOrderParamVM : mbts.ui.shell.ViewModelBase
{
public DynamicOrderParamVM() { }
public DynamicOrderParamDescriptor descriptor { get; set; }
public DynamicOrderParam param { get; set; }
public DynamicOrderParam param {
get => _param;
set {
_param = value;
on_param_changed();
}
}
protected abstract void on_param_changed();
public static DynamicOrderParamVM create(DynamicOrderParamDescriptor descriptor) {
ExceptionAssert.Argument.NotNull(descriptor, nameof(descriptor));
switch (descriptor.ParamType.DescriptorCase) {
case DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive:
switch (descriptor.ParamType.Primitive) {
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool: return new DynamicOrderParamVM<bool>(descriptor, DynamicOrderParam.AsBoolFieldNumber);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble: return new DynamicOrderParamVM<double>(descriptor, DynamicOrderParam.AsDoubleFieldNumber);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return new DynamicOrderParamVM<uint>(descriptor, DynamicOrderParam.AsInt32FieldNumber);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return new DynamicOrderParamVM<uint>(descriptor, DynamicOrderParam.AsUint32FieldNumber);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return new DynamicOrderParamVM<string>(descriptor, DynamicOrderParam.AsStringFieldNumber);
default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.Primitive, nameof(descriptor));
}
default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.DescriptorCase, nameof(descriptor));
}
}
}
class DynamicOrderParamVM<T> : DynamicOrderParamVM {
readonly FieldDescriptor _field_desc;
public DynamicOrderParamVM(DynamicOrderParamDescriptor descriptor, int field_number) : base(descriptor) =>
_field_desc = DynamicOrderParam.Descriptor.FindFieldByNumber(field_number);
public T value {
get => ConvertUtils.try_convert<T>(_field_desc.Accessor.GetValue(param));
set {
_field_desc.Accessor.SetValue(param, value);
RaisePropertyChanged();
}
}
protected override void on_param_changed() => RaisePropertyChanged(nameof(value));
}
}
@@ -1,194 +1,132 @@
using bts.api;
using bts.api.orderman;
using bts.api.orderman;
using mbts.collections;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using System.Threading.Tasks;
namespace mbts.spark
{
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class DynamicOrderVM : OrderTypeVMBase<DynamicOrderDefinition, DynamicOrderDefinitionImmutable> {
readonly ObservableKeyedCollection<DynamicOrderParamVM, string> _parameters = new ObservableKeyedCollection<DynamicOrderParamVM, string>(vm => vm.descriptor.ParamName);
readonly Property<string> _dyn_type;
OrdersModel _model;
bool _active;
static partial class OrderTypeVMFactory
{
class InlineDynamicOrderProperties
{
public InlineDynamicOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
}
class DynamicOrderVM : OrderTypeVMBase<DynamicOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineDynamicOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
string _dyn_type;
IDictionary<string, DynamicOrderParamVM> _parameters;
IEnumerable<string> _order_def_tags;
public DynamicOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string dyn_type, string id, string display_name)
: this(model, security_md_source, dyn_type, security_md_source.Select(smd =>
new InlineDynamicOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name)
{ }
public DynamicOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string dyn_type,
IObservable<InlineDynamicOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dyn_type = dyn_type;
_parameters = model.dynamic_helper.get_parameters(dyn_type);
_order_def_tags = _parameters.Values.Where(x => x.descriptor.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive &&
x.descriptor.ParamType.Primitive == DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef).Select(xx=>xx.descriptor.ParamName);
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
_inline_props = p;
_validate();
})
);
_validate();
public DynamicOrderVM(AlgoKey key, string dyn_type, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_dyn_type = add_property(nameof(this.dyn_type), DynamicOrderDefinition.DynamicOrderTypeFieldNumber, dyn_type);
_parameters = new ObservableKeyedCollection<DynamicOrderParamVM, string>(vm => vm.descriptor.ParamName);
_resources.AddRange(
_dyn_type.Subscribe(_ => _reset_dynamic_types()),
ObservableAutoWrapper.connect_item_hooks(_parameters, p => {
p.PropertyChanged += on_param_prop_changed;
return Disposable.Create(() => p.PropertyChanged -= on_param_prop_changed);
}, true));
void on_param_prop_changed(object sender, PropertyChangedEventArgs e) => raise_definition_changed();
}
public override string type_name => _dyn_type;
public IEnumerable<DynamicOrderParamVM> parameters => _parameters.Values.Where(x =>
{
return x.descriptor.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated ||
(x.descriptor.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive &&
x.descriptor.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef);
});
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.dynamic_order();
i.DynamicOrderType = _dyn_type;
set_parameter_dictionary(i.OrderParams);
value.Dynamic = i;
public string dyn_type => _dyn_type.Value;
public ObservableCollection<DynamicOrderParamVM> parameters {
get {
_ensure_init();
return _parameters;
}
}
void set_parameter_dictionary(Google.Protobuf.Collections.MapField<string, DynamicOrderParam> par)
{
foreach(var vm in _parameters.Values)
par[vm.descriptor.ParamName] = vm.param;
protected override void assign_to_internal(DynamicOrderDefinition dynamic_def) {
foreach (var vm in _parameters.Values)
dynamic_def.OrderParams[vm.descriptor.ParamName] = vm.param;
}
if (child_order != null)
{
var newkid = new DynamicOrderParam();
var cust = new CustomOrderDefinition();
newkid.AsOrderDef = cust;
child_order.assign_to(newkid.AsOrderDef);
foreach(var child in _order_def_tags)
par[child] = newkid;
protected override void load_from_internal(DynamicOrderDefinitionImmutable dyn_defi) {
foreach (var p in _parameters) {
if (dyn_defi.OrderParams.TryGetValue(p.descriptor.ParamName, out DynamicOrderParam dop)) {
p.param = dop;
} else {
p.param.ClearValue();
}
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
protected override async Task on_load_from_async(CustomOrderDefinitionImmutable defi) {
await Wait.until_true(() => _model != null, TimeSpan.FromSeconds(60));
_ensure_init();
}
void _ensure_init() {
if (!_active) {
_active = true;
// lazy initialization is required to avoid a stack overflow (otherwise, the algo-hierarchy would grow recursively without stopping).
_reset_dynamic_types();
}
}
protected override void on_model_internal(OrdersModel model) {
_model = model;
_reset_dynamic_types();
}
public bool has_child => _order_def_tags.Any();
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
void _reset_dynamic_types() {
if (!_active)
return;
var value_descs = new Dictionary<string, DynamicOrderParamDescriptor>();
var child_descs = new Dictionary<string, DynamicOrderParamDescriptor>();
if (_model != null) {
var desc = _model.dynamic_helper.get_descriptor(dyn_type);
if (desc != null) {
foreach (var p in desc.ParamDesc) {
if (_is_value_param_desc(p)) {
value_descs[p.ParamName] = p;
} else if (_is_child_algo_desc(p)) {
child_descs[p.ParamName] = p;
}
}
}
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
_parameters.SyncWithDictionary(value_descs, DynamicOrderParamVM.create);
using (reset_selectors()) {
foreach (var kv in child_descs) {
add_selector(kv.Key, get_child, set_child);
// local methods
CustomOrderDefinitionImmutable? get_child(DynamicOrderDefinitionImmutable dyn_defi) {
if (dyn_defi.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam p) && p.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef)
return new CustomOrderDefinitionImmutable(p.AsOrderDef);
return null;
}
void set_child(DynamicOrderDefinition dyn_def, CustomOrderDefinition child) =>
dyn_def.OrderParams[kv.Key] = new DynamicOrderParam { AsOrderDef = child };
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
static bool _is_child_algo_desc(DynamicOrderParamDescriptor desc) =>
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive &&
desc.ParamType.Primitive == DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef;
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
static bool _is_value_param_desc(DynamicOrderParamDescriptor desc) =>
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated ||
(desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive && desc.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef);
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
public class SelectorVM : ViewModelBase {
readonly IAlgoSelector _selector;
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
public SelectorVM(IAlgoSelector selector) {
_selector = selector;
_selector.selected_algo_changed += _on_selected_algo_changed;
}
public IAlgoVM selected_algo { get => _selector.selected_algo; set => _selector.selected_algo = value; }
public ObservableCollection<IAlgoVM> algos => _selector.algos;
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
public void Dispose() =>
_selector.selected_algo_changed -= _on_selected_algo_changed;
void _on_selected_algo_changed(IAlgoVM oldval, IAlgoVM newval) =>
RaisePropertyChanged(nameof(selected_algo));
}
}
}
@@ -1,34 +1,94 @@
using bts.api.orderman;
using bts.spark;
using bts.utils;
using mbts.collections;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using static bts.api.orderman.CustomOrderDefinition;
using System.Windows.Media;
namespace mbts.spark {
interface IOrderTypeVM : IPropertyWrapperVM<CustomOrderDefinition, CustomOrderDefinitionImmutable> {
string id { get; }
CustomOneofCase order_type { get; }
string type_name { get; }
interface IAlgoVM : IPropertyWrapperVM<CustomOrderDefinition, CustomOrderDefinitionImmutable>, IPropertyChangedDemuxer {
event Action definition_changed;
AlgoKey id { get; }
CustomOrderDefinition.CustomOneofCase order_type { get; }
bool is_bts_type { get; }
OrderMetadata meta { get; }
bool has_editable_properties { get; }
bool editable_properties_open { get; set; }
bool can_expand { get; }
bool is_expanded { get; set; }
bool can_edit_values { get; }
bool can_edit_structure { get; }
bool can_save_values { get; }
bool can_save_structure { get; }
string display_name { get; }
CustomOrderDefinitionImmutable definition { get; }
ObservableCollection<IAlgoSelector> child_algo_selectors { get; }
bool key_match(KeyEventArgs e);
void init();
void set_permissions(AlgoEditingPermissions editing_permissions);
Task<CustomOrderDefinitionImmutable?> load_from_async(CustomOrderDefinitionImmutable definition);
}
interface IHierarchicalOrderTypeVM : IOrderTypeVM {
ICollection<IOrderTypeVM> child_order_types { get; }
IOrderTypeVM child_order { get; }
interface IDynamicAlgoVMImpl {
IAlgoVM impl { get; }
}
delegate void AlgoLoaded(bool reset_edit_stack);
interface ILazyAlgo {
bool is_loaded { get; }
}
interface IAlgoSelector : IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)> {
event PropertyChange<IAlgoVM> selected_algo_changed;
ObservableKeyedCollection<IAlgoVM, AlgoKey> algos { get; }
IReadOnlyObservableCollection<IAlgoVM> algos_view { get; }
IAlgoVM selected_algo { get; set; }
void load_algo_data(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo);
}
static class OrderTypeVMExtensions {
public static IEqualityComparer<IOrderTypeVM> key_comparer =>
EqualityComparer.Create<IOrderTypeVM, OrderTemplateKey>(a => a.key());
public static AlgoData create_def_data(this IAlgoVM vm) =>
new AlgoData(vm.definition, vm.display_name, vm.id);
public static OrderTemplateKey key(this IOrderTypeVM vm) =>
new OrderTemplateKey(vm.order_type, vm.id);
public static void load_structure(this IAlgoVM vm, CustomOrderDefinitionImmutable def) {
var mdef = def.CloneToMutable();
// assign values from vm.definition to mdef (values will be assigned at each common structure-level, e.g. Iceberg->Iceberg->Limit and Iceberg->Iceberg->Lean have 2 common structure-levels)
OrderDataHelper.copy_values(vm.definition, ref mdef);
vm.load_from(new CustomOrderDefinitionImmutable(mdef));
}
public static IObservable<CustomOrderDefinitionImmutable> subscribe_definition(this IAlgoVM vm) =>
Observable.Create<CustomOrderDefinitionImmutable>(o => {
o.OnNext(vm.definition);
vm.definition_changed += on_definition_changed;
return Disposable.Create(() => vm.definition_changed -= on_definition_changed);
void on_definition_changed() => o.OnNext(vm.definition);
});
public static IDisposable connect_data<T>(this IAlgoSelector selector, IObservable<T> data_source) =>
ObservableAutoWrapper.connect_item_hooks(selector.algos, vm => {
var cd = new CompositeDisposable();
if (vm is IObserver<T> o)
cd.Add(data_source.Subscribe(o));
cd.AddRange(ObservableAutoWrapper.connect_item_hooks(vm.child_algo_selectors, s => connect_data(s, data_source)));
return cd;
});
public static Color safe_get_badge_color(this IAlgoVM vm) =>
vm == null ? default : vm.meta.Color.rgb_color();
public static IDisposable load_algo_data_recursive(this IAlgoSelector selector, IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) {
selector.load_algo_data(algo_data, default_algo);
return ObservableAutoWrapper.connect_item_hooks(selector.algos, vm =>
ObservableAutoWrapper.connect_item_hooks(vm.child_algo_selectors, s => load_algo_data_recursive(s, algo_data, default_algo)));
}
}
}
@@ -1,144 +1,16 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using bts.api.orderman;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class InlineIcebergOrderProperties {
public InlineIcebergOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types) {
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
show_quantity = new InlineUserProperty<double>(1, true);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<double> show_quantity;
}
class IcebergOrderVM : OrderTypeVMBase<IcebergOrderDefinition, IcebergOrderDefinitionImmutable> {
readonly Property<double> _show_quantity;
class IcebergOrderVM : OrderTypeVMBase<IcebergOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineIcebergOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public IcebergOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineIcebergOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public IcebergOrderVM(OrdersModel model,
IObservable<SecurityMD> security_md_source,
IObservable<InlineIcebergOrderProperties> inline_properties, string id, string display_name)
: base(model, id, display_name) {
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override) {
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override)) {
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.show_quantity.force_override) {
show_quantity = p.show_quantity.value;
RaisePropertyChanged(nameof(show_quantity));
}
_inline_props = p;
_validate();
})
);
_validate();
public IcebergOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_show_quantity = add_property(nameof(show_quantity), IcebergOrderDefinition.ShowQuantityFieldNumber, double.NaN);
}
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null) {
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
}
return _child_order_choices;
}
}
public IOrderTypeVM child_order {
get {
init();
return _child_order;
}
set {
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei) {
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public double show_quantity { get; set; } = 0;
public override void assign_to(CustomOrderDefinition value) {
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors) {
var i = factory.iceberg_order();
i.ShowQuantity = show_quantity;
child_order.assign_to(i.Child);
value.Iceberg = i;
}
}
public void Dispose() {
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init() {
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order() {
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot) {
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate() {
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
public double show_quantity { get => _show_quantity.Value; set => _show_quantity.set(value); }
}
}
}
@@ -1,166 +1,17 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using bts.spark;
using JoinDef = bts.api.orderman.JoinOrderDefinition;
using JoinDefi = bts.api.orderman.JoinOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineJoinOrderProperties
{
public InlineJoinOrderProperties (OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
join_threshold = new InlineUserProperty<bts.spark.QuantityMeasure>(
new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1}, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class JoinOrderVM : OrderTypeVMBase<JoinDef, JoinDefi> {
readonly Property<QuantityMeasureImmutable> _join_threshold;
public readonly InlineUserProperty<bts.spark.QuantityMeasure> join_threshold;
}
public JoinOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) =>
_join_threshold = add_property<QuantityMeasure, QuantityMeasureImmutable>(nameof(join_threshold), JoinDef.JoinThresholdFieldNumber, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 }));
class JoinOrderVM : OrderTypeVMBase<JoinOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineJoinOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public bts.spark.QuantityMeasure join_threshold { get; set; } = new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 };
public JoinOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineJoinOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public JoinOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineJoinOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.join_threshold.force_override)
{
join_threshold = p.join_threshold.value;
RaisePropertyChanged(nameof(join_threshold));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.join_order();
i.JoinThreshold = join_threshold;
child_order.assign_to(i.Child);
value.Join = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
public QuantityMeasureImmutable join_threshold { get => _join_threshold.Value; set => _join_threshold.set(value); }
}
}
}
@@ -1,185 +1,29 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using bts.spark;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using LeanDef = bts.api.orderman.LeanOrderDefinition;
using LeanDefi = bts.api.orderman.LeanOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineLeanOrderProperties
{
public InlineLeanOrderProperties (OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
cross_threshold = new InlineUserProperty<bts.spark.QuantityMeasure>(
new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1}, false);
max_chase_ticks = new InlineUserProperty<uint>(2, false);
trade_toward_behavior = new InlineUserProperty<LeanOrderDefinition.Types.OnToward>(LeanOrderDefinition.Types.OnToward.NoChange, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<bts.spark.QuantityMeasure> cross_threshold;
public readonly InlineUserProperty<uint> max_chase_ticks;
public readonly InlineUserProperty<LeanOrderDefinition.Types.OnToward> trade_toward_behavior;
}
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class LeanOrderVM : OrderTypeVMBase<LeanDef, LeanDefi> {
readonly Property<QuantityMeasureImmutable> _cross_threshold;
readonly Property<uint> _max_chase_ticks;
readonly Property<LeanDef.Types.OnToward> _trade_toward_behavior;
class LeanOrderVM : OrderTypeVMBase<LeanOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineLeanOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public bts.spark.QuantityMeasure cross_threshold { get; set; } = new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 };
public uint max_chase_ticks { get; set; } = 2;
public LeanOrderDefinition.Types.OnToward trade_toward_behavior { get; set; } = LeanOrderDefinition.Types.OnToward.NoChange;
public LeanOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineLeanOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public LeanOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineLeanOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.cross_threshold.force_override)
{
cross_threshold = p.cross_threshold.value;
RaisePropertyChanged(nameof(cross_threshold));
}
if (p.max_chase_ticks.force_override)
{
max_chase_ticks = p.max_chase_ticks.value;
RaisePropertyChanged(nameof(max_chase_ticks));
}
if (p.trade_toward_behavior.force_override)
{
trade_toward_behavior = p.trade_toward_behavior.value;
RaisePropertyChanged(nameof(trade_toward_behavior));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.lean_order();
i.CrossThreshold = cross_threshold;
i.MaxChaseTicks = max_chase_ticks;
i.TradeTowardBehavior = trade_toward_behavior;
child_order.assign_to(i.Child);
value.Lean = i;
}
public LeanOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_trade_toward_behavior = add_property(nameof(trade_toward_behavior), LeanDef.TradeTowardBehaviorFieldNumber, LeanDef.Types.OnToward.NoChange);
_cross_threshold = add_property<QuantityMeasure, QuantityMeasureImmutable>(nameof(cross_threshold), LeanDef.CrossThresholdFieldNumber, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 }));
_max_chase_ticks = add_property(nameof(max_chase_ticks), LeanDef.MaxChaseTicksFieldNumber, 2u);
}
public IEnumerable<LeanOrderDefinition.Types.OnToward> trade_toward_types => EnumHelper.get_values_except<LeanOrderDefinition.Types.OnToward>();
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
// trade toward behavior
public LeanDef.Types.OnToward trade_toward_behavior { get => _trade_toward_behavior.Value; set => _trade_toward_behavior.set(value); }
public IEnumerable<LeanDef.Types.OnToward> trade_toward_types => EnumHelper.get_values_except<LeanDef.Types.OnToward>();
// auxiliary
public QuantityMeasureImmutable cross_threshold { get => _cross_threshold.Value; set => _cross_threshold.set(value); }
public uint max_chase_ticks { get => _max_chase_ticks.Value; set => _max_chase_ticks.set(value); }
}
}
}
@@ -2,11 +2,12 @@
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class LimitOrderVM : OrderTypeVMBase<LimitOrderDefinition> {
internal LimitOrderVM(OrdersModel model) : base(model, "Limit", OrderUtils.order_type_display_name(CustomOrderDefinition.CustomOneofCase.Limit)) { }
class LimitOrderVM : OrderTypeVMBase<LimitOrderDefinition, LimitOrderDefinitionImmutable> {
internal LimitOrderVM()
: this(new AlgoKey(CustomOrderDefinition.CustomOneofCase.Limit), CustomOrderDefinition.CustomOneofCase.Limit.display_name()) { }
public override void assign_to(CustomOrderDefinition value) =>
value.Limit = factory.limit_order();
internal LimitOrderVM(AlgoKey key, string display_name)
: base(key, display_name, AlgoEditingPermissions.None) { }
}
}
}
@@ -2,11 +2,12 @@
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class MarketOrderVM : OrderTypeVMBase<MarketOrderDefinition> {
internal MarketOrderVM(OrdersModel model) : base(model, "Market", OrderUtils.order_type_display_name(CustomOrderDefinition.CustomOneofCase.Market)) { }
class MarketOrderVM : OrderTypeVMBase<MarketOrderDefinition, MarketOrderDefinitionImmutable> {
internal MarketOrderVM()
: this (new AlgoKey(CustomOrderDefinition.CustomOneofCase.Market), CustomOrderDefinition.CustomOneofCase.Market.display_name()) { }
public override void assign_to(CustomOrderDefinition parent) =>
parent.Market = factory.market_order();
internal MarketOrderVM(AlgoKey key, string display_name)
: base(key, display_name, AlgoEditingPermissions.None) { }
}
}
}
@@ -1,257 +1,24 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using OCODef = bts.api.orderman.OCOOrderDefinition;
using OCODefi = bts.api.orderman.OCOOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineOCOOrderProperties
{
public InlineOCOOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class OCOOrderVM : OrderTypeVMBase<OCODef, OCODefi> {
readonly Property<int> _other_ticks;
readonly Property<RelativeSide> _other_side;
var othertype = CustomOneofCase.Limit;
this.selected_other_order_type = new InlineUserProperty<OrderTemplateHeader>(new OrderTemplateHeader(othertype), true);
this.other_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
other_ticks = new InlineUserProperty<int>(1, false);
other_side = new InlineUserProperty<bts.api.RelativeSide>(bts.api.RelativeSide.Same, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<OrderTemplateHeader> selected_other_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> other_order_types;
public readonly InlineUserProperty<int> other_ticks;
public readonly InlineUserProperty<bts.api.RelativeSide> other_side;
}
class OCOOrderVM : OrderTypeVMBase<OCOOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineOCOOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _other_order_choices;
IOrderTypeVM _other_order;
IDisposable _other_order_errors_sub;
public int other_ticks { get; set; } = 1;
public bts.api.RelativeSide other_side { get; set; } = bts.api.RelativeSide.Same;
public OCOOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineOCOOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name)
{ }
public OCOOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineOCOOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (_other_order_choices != null && (_other_order == null || p.selected_other_order_type.force_override))
{
_select_other_order(p.selected_other_order_type.value.key.type);
}
if (p.other_ticks.force_override)
{
other_ticks = p.other_ticks.value;
RaisePropertyChanged(nameof(other_ticks));
}
if (p.other_side.force_override)
{
other_side = p.other_side.value;
RaisePropertyChanged(nameof(other_side));
}
_inline_props = p;
_validate();
})
);
_validate();
public OCOOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_other_ticks = add_property(nameof(other_ticks), OCODef.OtherTicksFieldNumber, 1);
_other_side = add_property(nameof(other_side), OCODef.OtherSideFieldNumber, RelativeSide.Same);
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
if (_other_order == null )
_select_other_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.oco_order();
i.OtherTicks = other_ticks;
i.OtherSide = other_side;
child_order.assign_to(i.Child);
if (other_order != null)
other_order.assign_to(i.Other);
value.Oco = i;
}
}
public IEnumerable<bts.api.RelativeSide> other_side_types => EnumHelper.get_values_except<bts.api.RelativeSide>(bts.api.RelativeSide.Undefined);
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public ICollection<IOrderTypeVM> other_order_types
{
get
{
if (_other_order_choices == null)
_other_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _other_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public IOrderTypeVM other_order
{
get
{
init();
return _other_order;
}
set
{
Disposable.dispose(ref _other_order_errors_sub);
_other_order = value;
_other_order?.init();
if (_other_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_other_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(other_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
if (_other_order_choices != null)
_other_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
if (_other_order == null && _security.HasValue)
_select_other_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _select_other_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_other_order_type.has_value ?
_inline_props.selected_other_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_other_order(ot);
}
void _select_other_order(CustomOneofCase ot)
{
_other_order = other_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_other_order == null)
_other_order = other_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(other_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
if ((_other_order == null ) || (_other_order is INotifyDataErrorInfo hdei && hdei.HasErrors))
set_error(nameof(other_order), string.Empty, true);
else clear_error(nameof(other_order));
}
public int other_ticks { get => _other_ticks.Value; set => _other_ticks.set(value); }
public IEnumerable<RelativeSide> other_side_types => EnumHelper.get_values_except(RelativeSide.Undefined);
public RelativeSide other_side { get => _other_side.Value; set => _other_side.set(value); }
}
}
}
@@ -1,164 +1,17 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using OffsetDef = bts.api.orderman.OffsetOrderDefinition;
using OffsetDefi = bts.api.orderman.OffsetOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineOffsetOrderProperties
{
public InlineOffsetOrderProperties (OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
tick_offset_on_deploy = new InlineUserProperty<uint>(0, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<uint> tick_offset_on_deploy;
}
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class OffsetOrderVM : OrderTypeVMBase<OffsetDef, OffsetDefi> {
readonly Property<uint> _tick_offset_on_deploy;
class OffsetOrderVM : OrderTypeVMBase<OffsetOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineOffsetOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public uint tick_offset_on_deploy { get; set; } = 0;
public OffsetOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineOffsetOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public OffsetOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineOffsetOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.tick_offset_on_deploy.force_override)
{
tick_offset_on_deploy = p.tick_offset_on_deploy.value;
RaisePropertyChanged(nameof(tick_offset_on_deploy));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.offset_order();
i.TickOffsetOnDeploy = tick_offset_on_deploy;
child_order.assign_to(i.Child);
value.Offset = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
public OffsetOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_tick_offset_on_deploy = add_property(nameof(tick_offset_on_deploy), OffsetDef.TickOffsetOnDeployFieldNumber, 0u);
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
public uint tick_offset_on_deploy { get => _tick_offset_on_deploy.Value; set => _tick_offset_on_deploy.set(value); }
}
}
}
@@ -1,96 +1,523 @@
using bts.api;
using bts.api.orderman;
using bts.spark;
using bts.utils;
using Google.Protobuf;
using Google.Protobuf.Reflection;
using mbts.collections;
using mbts.spark.utilities;
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.Dynamic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using static bts.api.orderman.CustomOrderDefinition;
using AlgoDef = bts.api.orderman.CustomOrderDefinition;
using AlgoDefi = bts.api.orderman.CustomOrderDefinitionImmutable;
using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
public static IOrderTypeVM market(OrdersModel model) => new MarketOrderVM(model);
public static IOrderTypeVM limit(OrdersModel model) => new LimitOrderVM(model);
public static IOrderTypeVM stop(OrdersModel model, string id, string display_name) => new StopOrderVM(model, id, display_name);
public static IOrderTypeVM stop_limit(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new StopLimitOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM time_box(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new TimeBoxOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM lean(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new LeanOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM join(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new JoinOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM top(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new TopOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM cover(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new CoverOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM oco(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new OCOOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM pricer(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new PricerOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM offset(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new OffsetOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM trigger(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new TriggerOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM iceberg(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name) => new IcebergOrderVM(model, security_md_source, id, display_name);
public static IOrderTypeVM spreader(OrdersModel model, IObservable<SecurityImmutable> security_source, string id, string display_name) => new SpreaderOrderVM(model, security_source, id, display_name);
public static IOrderTypeVM dynamic(OrdersModel model, IObservable<SecurityMD> security_md_source, string dynamic_type, string id, string display_name) => new DynamicOrderVM(model, security_md_source, dynamic_type, id, display_name);
enum AlgoEditingPermissions {
None = 0,
AllowEditValues = 1,
AllowEditStructure = 1 << 1,
AllowSaveValues = 1 << 2,
AllowSaveStructure = 1 << 3,
}
public static IOrderTypeVM create(CustomOneofCase order_type, string id, string display_name, OrdersModel model,
IObservable<SecurityMD> security_md_source, string dynamic_type = null ) {
switch (order_type) {
case CustomOneofCase.Market: return market(model);
case CustomOneofCase.Limit: return limit(model);
case CustomOneofCase.Stop: return stop(model, id, display_name);
case CustomOneofCase.StopLimit: return stop_limit(model, security_md_source, id, display_name);
case CustomOneofCase.TimeBox: return time_box(model, security_md_source, id, display_name);
case CustomOneofCase.Lean: return lean(model, security_md_source, id, display_name);
case CustomOneofCase.Join: return join(model, security_md_source, id, display_name);
case CustomOneofCase.Top: return top(model, security_md_source, id, display_name);
case CustomOneofCase.Cover: return cover(model, security_md_source, id, display_name);
case CustomOneofCase.Oco : return oco(model, security_md_source, id, display_name);
case CustomOneofCase.Pricer: return pricer(model, security_md_source, id, display_name);
case CustomOneofCase.Offset: return offset(model, security_md_source, id, display_name);
case CustomOneofCase.Trigger: return trigger(model, security_md_source, id, display_name);
case CustomOneofCase.Iceberg: return iceberg(model, security_md_source, id, display_name);
case CustomOneofCase.Spreader: return spreader(model, security_md_source.Select(smd => smd.security), id, display_name);
case CustomOneofCase.Dynamic: return dynamic(model, security_md_source, dynamic_type, id, /*display_name*/ dynamic_type);
static partial class OrderTypeVMFactory {
public const AlgoEditingPermissions default_editing_permissions = AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowEditStructure;
public static IAlgoVM market() => new MarketOrderVM();
public static IAlgoVM limit() => new LimitOrderVM();
public static IAlgoVM stop(AlgoKey key, string display_name) => new StopOrderVM(key, display_name, default_editing_permissions);
public static IAlgoVM stop_limit(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new StopLimitOrderVM(key, display_name, editing_permissions);
public static IAlgoVM time_box(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TimeBoxOrderVM(key, display_name, editing_permissions);
public static IAlgoVM tick(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TickOrderVM(key, display_name, editing_permissions);
public static IAlgoVM lean(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new LeanOrderVM(key, display_name, editing_permissions);
public static IAlgoVM join(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new JoinOrderVM(key, display_name, editing_permissions);
public static IAlgoVM top(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TopOrderVM(key, display_name, editing_permissions);
public static IAlgoVM cover(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new CoverOrderVM(key, display_name, editing_permissions);
public static IAlgoVM oco(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OCOOrderVM(key, display_name, editing_permissions);
public static IAlgoVM pricer(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new PricerOrderVM(key, display_name, editing_permissions);
public static IAlgoVM offset(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new OffsetOrderVM(key, display_name, editing_permissions);
public static IAlgoVM trigger(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new TriggerOrderVM(key, display_name, editing_permissions);
public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions);
public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions);
public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions);
public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) {
var vm = create(def_data.key, def_data.name, def_data.value.CustomCase, editing_permissions, is_expanded);
vm.load_from(def_data.value);
//vm.is_expanded = is_expanded && vm.can_expand;
vm.is_expanded = is_expanded && vm.can_expand;
return vm;
}
public static IAlgoVM create(AlgoKey key, string name, AlgoType algo_type, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) {
IAlgoVM vm;
switch (algo_type) {
case AlgoType.Market: vm = new MarketOrderVM(key, name); break;
case AlgoType.Limit: vm = new LimitOrderVM(key, name); break;
case AlgoType.Stop: vm = stop(key, name); break;
case AlgoType.StopLimit: vm = stop_limit(key, name, editing_permissions); break;
case AlgoType.TimeBox: vm = time_box(key, name, editing_permissions); break;
case AlgoType.Tick: vm = tick(key, name, editing_permissions); break;
case AlgoType.Lean: vm = lean(key, name, editing_permissions); break;
case AlgoType.Join: vm = join(key, name, editing_permissions); break;
case AlgoType.Top: vm = top(key, name, editing_permissions); break;
case AlgoType.Cover: vm = cover(key, name, editing_permissions); break;
case AlgoType.Oco : return oco(key, name, editing_permissions);
case AlgoType.Pricer: return pricer(key, name, editing_permissions);
case AlgoType.Offset: vm = offset(key, name, editing_permissions); break;
case AlgoType.Trigger: vm = trigger(key, name, editing_permissions); break;
case AlgoType.Iceberg: vm = iceberg(key, name, editing_permissions); break;
case AlgoType.Spreader: vm = spreader(key, name, editing_permissions); break;
case AlgoType.Dynamic: vm = dynamic(key, name, name, editing_permissions); break;
case AlgoType.None: vm = new DefaultAlgoVM(); break;
default: throw new NotImplementedException();
}
return vm;
}
static class OrderTypeVMUtils {
static readonly IReadOnlyDictionary<Type, FieldDescriptor> _algo_type_index =
AlgoDef.Descriptor.Fields.InFieldNumberOrder()
.ToDictionary(fd => fd.MessageType.ClrType);
public static FieldDescriptor find_descriptor<T>() =>
_algo_type_index.TryGetValue(typeof(T), out FieldDescriptor fd) ?
fd : throw new NotSupportedException($"No {nameof(AlgoDef)} {nameof(FieldDescriptor)} exists for type '{typeof(T)}.'");
public static Func<TMutable, TImmutable> immutable_factory<TMutable, TImmutable>() where TMutable : IMessage, new() where TImmutable : IImmutableMessage =>
_ImmutableActivator<TMutable, TImmutable>.factory;
static class _ImmutableActivator<TMutable, TImmutable> where TMutable : IMessage, new() where TImmutable : IImmutableMessage {
public static readonly Func<TMutable, TImmutable> factory =
m => (TImmutable)Activator.CreateInstance(typeof(TImmutable), m);
}
}
#region OrderTypeVM Base Classes
private abstract class OrderTypeVMBase : ViewModelBaseWithValidation, IOrderTypeVM {
protected readonly OrdersModel model;
protected OrderFactory factory => model.factory;
abstract class OrderTypeVMBase<TMutable, TImmutable> : DisposableViewModelBase, IAlgoVM, IObserver<SecurityMD?>, IObserver<OrdersModel> where TMutable : class, IMessage, new() where TImmutable : struct, IImmutableMessage {
/// TODO: maybe use explicit delegates rather than rely on reflection <see cref="_descriptor"/> <see cref="_create_immutable"/>.
static readonly FieldDescriptor _descriptor = OrderTypeVMUtils.find_descriptor<TMutable>();
static readonly Func<TMutable, TImmutable> _create_immutable = OrderTypeVMUtils.immutable_factory<TMutable, TImmutable>();
readonly IDictionary<string, object> _children_vm = new ExpandoObject();
protected CompositeDisposable _resources = new CompositeDisposable();
protected OrderTypeVMBase(OrdersModel model, string id, string display_name) {
this.model = model;
readonly List<(Action<TMutable> assign, Action<TMutable> load)> _auto_props = new List<(Action<TMutable> assign, Action<TMutable> load)>();
readonly ObservableKeyedCollection<AlgoSelectorData, string> _child_algo_selector_data = new ObservableKeyedCollection<AlgoSelectorData, string>(sd => sd.prop_name);
readonly ObservableAutoWrapper<IAlgoSelector, AlgoSelectorData> _child_algo_selectors;
readonly Property<bool> _is_expanded, _can_save_values, _can_save_structure;
readonly DeferrableActionWrapper _def_change_notifier;
protected OrderTypeVMBase(AlgoKey id, string display_name, AlgoEditingPermissions editing_permissions) {
this.id = id;
this.display_name = display_name;
this.editing_permissions = editing_permissions;
_child_algo_selectors = new ObservableAutoWrapper<IAlgoSelector, AlgoSelectorData>(_child_algo_selector_data, sd => sd.selector);
_can_save_values = backing(nameof(can_save_values), true);
_can_save_structure = backing(nameof(can_save_structure), true);
_is_expanded = backing<bool>(nameof(is_expanded));
foreach (var c in OrderDataHelper.get_child_algo_data(order_type)) {
_children_vm[c.name] = add_selector(c.name, c.descriptor);
}
_def_change_notifier = new DeferrableActionWrapper(() => definition_changed?.Invoke());
PropertyChanged += (s, e) => {
switch (e.PropertyName) {
// ignore props that don't affect the resultant AlgoDef
case nameof(is_expanded):
case nameof(can_edit_values):
case nameof(can_edit_structure):
case nameof(can_save_values):
case nameof(can_save_structure):
return;
default:
_def_change_notifier.execute();
return;
}
};
_resources.Add(ObservableAutoWrapper.connect_item_hooks(_child_algo_selector_data, sd => {
CompositeDisposable def_sub = null;
sd.selector.selected_algo_changed += subscribe_new_algo;
return new CompositeDisposable(
ObservableAutoWrapper.connect_item_hooks(sd.selector.algos, a => {
a.set_permissions(this.editing_permissions);
return a as IDisposable ?? Disposable.empty;
}, true)) {
() => {
sd.selector.selected_algo_changed -= subscribe_new_algo;
Disposable.dispose(ref def_sub);
}
};
void subscribe_new_algo(IAlgoVM old_algo, IAlgoVM new_algo) {
RaisePropertyChanged(sd.prop_name);
Disposable.replace(ref def_sub, new CompositeDisposable());
if (assert(new_algo != null, sd.prop_name, "No algo specified.")) {
def_sub.Add(new_algo.subscribe_definition().Subscribe(_ => _def_change_notifier.execute()));
if (new_algo is INotifyDataErrorInfo ndei)
def_sub.Add(ndei.subscribe_has_errors().Subscribe(has_errors => assert(!has_errors, sd.prop_name, "Algo has invalid parameters.")));
}
}
}, true));
}
public abstract CustomOneofCase order_type { get; }
public abstract string type_name { get; }
public AlgoEditingPermissions editing_permissions { get; private set; }
public event Action definition_changed;
public AlgoDefi definition => new AlgoDefi(this.created_assigned());
public AlgoType order_type => OrderDataHelper.get_order_type(new TMutable());
public bool is_bts_type => display_name.StartsWith("BTS");
public string id { get; }
public string display_name { get; }
public OrderMetadata meta => factory.get_metadata(order_type);
public virtual bool has_editable_properties => !meta.NoProps;
public virtual bool editable_properties_open { get; set; }
public AlgoKey id { get; }
public string display_name { get; private set; }
public OrderMetadata meta => OrderDataHelper.get_metadata(order_type);
public virtual bool can_expand => !meta.NoProps;
public virtual bool is_expanded {
get => _is_expanded.Value;
set => _is_expanded.Value = value;
}
public dynamic children_vm => _children_vm;
public ObservableCollection<IAlgoSelector> child_algo_selectors => _child_algo_selectors;
public bool can_edit_values => EnumHelper.includes_flag(editing_permissions, AlgoEditingPermissions.AllowEditValues);
public bool can_edit_structure => EnumHelper.includes_flag(editing_permissions, AlgoEditingPermissions.AllowEditStructure);
public bool can_save_values => _can_save_values.Value;
public bool can_save_structure => _can_save_structure.Value;
protected OrdersModel model { get; private set; }
protected SecurityMD? security_md { get; private set; }
protected SecurityImmutable? security => security_md?.security;
public abstract void assign_to(CustomOrderDefinition value);
public void assign_to(AlgoDef value) {
var algo = new TMutable();
foreach (var (assign, load) in _auto_props)
assign(algo);
_descriptor.Accessor.SetValue(value, algo);
foreach (var sd in _child_algo_selector_data) {
if (sd.selector.selected_algo != null)
sd.set_order(value, sd.selector.selected_algo.created_assigned());
}
assign_to_internal(algo);
}
public virtual void init() { }
public void set_permissions(AlgoEditingPermissions editing_permissions) {
using (detect_property_changes(nameof(can_edit_values), nameof(can_edit_structure), nameof(can_save_values), nameof(can_save_structure)))
this.editing_permissions = editing_permissions;
on_permissions_changed();
}
public bool key_match(KeyEventArgs key) =>
key.Key == (Key.A + display_name[0] - 'A');
!string.IsNullOrEmpty(display_name) && key.Key == (Key.A + display_name[0] - 'A');
public void load_from(CustomOrderDefinitionImmutable value) {
if (value.CustomCase == order_type) load_from_internal(value);
public void load_from(AlgoDefi value) {
if (value.CustomCase != order_type)
return;
using (_def_change_notifier.defer_execution()) {
foreach (var sd in _child_algo_selector_data) {
var inner_def = sd.get_order(value);
if (inner_def.HasValue) {
if (security.HasValue) {
inner_def = OrderDataHelper.fit_to_type(inner_def.Value, security.Value.ContractCase);
if (!inner_def.HasValue)
continue;
}
var vm = sd.selector.algos.GetOrAdd(OrderDataHelper.get_shallow_factory_key(inner_def.Value), k => create(k, inner_def.Value.display_name(), inner_def.Value.CustomCase));
vm.load_from(inner_def.Value);
sd.selector.selected_algo = vm;
}
}
var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable();
var algoi = _create_immutable(algom);
foreach (var (assign, load) in _auto_props)
load(algom);
load_from_internal(algoi);
}
}
protected virtual void load_from_internal(CustomOrderDefinitionImmutable value) { }
public virtual async Task<AlgoDefi?> load_from_async(AlgoDefi defi) {
if (defi.CustomCase != order_type)
return null;
using (_def_change_notifier.defer_execution()) {
// TODO: each level of the order hierarchy could load in parallel
await on_load_from_async(defi);
foreach (var sd in _child_algo_selector_data) {
var inner_def = sd.get_order(defi);
if (inner_def.HasValue) {
var vm = sd.selector.algos.GetOrAdd(OrderDataHelper.get_shallow_factory_key(inner_def.Value), k => create(k, inner_def.Value.display_name(), inner_def.Value.CustomCase));
await vm.load_from_async(inner_def.Value);
sd.selector.selected_algo = vm;
}
}
var algom = _descriptor.Accessor.GetValue(defi.CloneToMutable()) as TMutable ?? new TMutable();
var algoi = _create_immutable(algom);
foreach (var (assign, load) in _auto_props)
load(algom);
load_from_internal(algoi);
return defi;
}
}
protected virtual Task on_load_from_async(AlgoDefi defi) => Task.CompletedTask;
protected virtual void assign_to_internal(TMutable value) { }
protected virtual void load_from_internal(TImmutable value) { }
protected void raise_definition_changed() =>
_def_change_notifier.execute();
protected virtual void validate() { }
protected virtual void on_permissions_changed() {
foreach (var vm in child_algo_selectors.SelectMany(s => s.algos.AsCollection()))
vm.set_permissions(editing_permissions);
}
protected override void Dispose(bool disposing) =>
Disposable.dispose(ref _resources);
#region Chidl Algo Selectors (add/remove/reset)
protected IAlgoSelector add_selector(string vm_prop_name, FieldDescriptor inner_desc) {
return add_selector(vm_prop_name, def => {
if (_descriptor.Accessor.GetValue(def.CloneToMutable()) is TMutable mval) {
if (inner_desc.Accessor.GetValue(mval) is AlgoDef inner_def)
return new AlgoDefi(inner_def);
}
return null;
}, (mdef, inner_def) => {
if (_descriptor.Accessor.GetValue(mdef) is TMutable mval)
inner_desc.Accessor.SetValue(mval, inner_def);
});
}
protected IAlgoSelector add_selector(string prop_name, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order) =>
add_selector(prop_name, get_order, set_order, (s, e) => validate());
protected IAlgoSelector add_selector(string prop_name, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order, EventHandler<DataErrorsChangedEventArgs> on_errors_changed) {
var rv = new AlgoSelector();
_child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, get_order, set_order);
return rv;
}
protected IAlgoSelector add_selector(string prop_name, Func<TImmutable, AlgoDefi?> get_algo, Action<TMutable, AlgoDef> set_algo) {
var rv = new AlgoSelector();
_child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, def => _descriptor.Accessor.GetValue(def.CloneToMutable()) is TMutable mval ? get_algo(_create_immutable(mval)) : null,
(def, child_def) => {
if (_descriptor.Accessor.GetValue(def) is TMutable mval)
set_algo(mval, child_def);
});
return rv;
}
protected bool remove_selector(string prop_name) =>
_child_algo_selector_data.Remove(prop_name);
/// TODO: maybe <see cref="_child_algo_selector_data"/> should just be a protected field?
/// Conversely, it is nice to hide these sort of implementation-specific details from inheriting classes.
/// Fwiw, as of 2/12/2019, the only class that needs the ability to add/remove selectors dynamically is <see cref="DynamicOrderVM"/>.
/// The other implementations simply add a whatever selectors they need in their constructor.
protected IDisposable reset_selectors() {
var to_remove = _child_algo_selector_data.Keys.ToList();
_child_algo_selector_data.CollectionChanged += on_change;
void on_change(object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Reset:
throw new InvalidOperationException($"{nameof(_child_algo_selector_data)} was reset; unable to continue processing incremental changes.");
default:
// catches Replace/Remove/Add ops (Add ops account for cases where the item was effectively replaced by a remove/re-add)
if (e.NewItems != null) {
foreach (AlgoSelectorData sd in e.NewItems)
to_remove.Remove(sd.prop_name);
}
break;
}
}
return Disposable.Create(() => {
_child_algo_selector_data.CollectionChanged -= on_change;
foreach (var id in to_remove)
_child_algo_selector_data.Remove(id);
});
}
#endregion
#region Auto-Properties (non-child-algo params)
protected Property<T> add_property<T>(string prop_name, int target_field_number, T init_value = default) {
var prop = backing(prop_name, init_value);
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
_auto_props.Add((mval => {
if (mval != null)
field_desc.Accessor.SetValue(mval, prop.Value);
}, mval => {
prop.set(mval == null ? default : ConvertUtils.try_convert<T>(field_desc.Accessor.GetValue(mval)));
}));
return prop;
}
protected UserProperty<T> add_user_property<T>(string prop_name, int target_field_number, T init_value = default) {
var prop = user_backing(prop_name, init_value);
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
add_property(
mdef => ConvertUtils.try_convert<T>(field_desc.Accessor.GetValue(mdef)),
(mdef, val) => field_desc.Accessor.SetValue(mdef, val),
val => prop.bypass_setter(val),
() => prop.Value);
return prop;
}
protected Property<TImmutableValue> add_property<TMutableValue, TImmutableValue>(string prop_name, int target_field_number, TImmutableValue init_value = default) where TMutableValue : class, IMessage, new() where TImmutableValue : IImmutableMessage {
var prop = backing(prop_name, init_value);
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
var immutable_factory = OrderTypeVMUtils.immutable_factory<TMutableValue, TImmutableValue>();
add_property<TMutableValue>(
mdef => field_desc.Accessor.GetValue(mdef) as TMutableValue,
(mdef, mval) => field_desc.Accessor.SetValue(mdef, mval),
mval => prop.set(immutable_factory(mval ?? new TMutableValue())),
() => {
// TODO: perhaps CloneToMutable() should be a member of IImmutableMessage.
// this method makes things so simple for the caller...but this dynamic cast is a little sketch.
return ((dynamic)prop.Value).CloneToMutable();
});
return prop;
}
protected void add_property<TValue>(Func<TMutable, TValue> get_from_def, Action<TMutable, TValue> assign_to_def, Action<TValue> set_local, Func<TValue> get_local) =>
_auto_props.Add((def => {
assign_to_def(def, get_local());
}, def => {
set_local(get_from_def(def));
}));
protected virtual void on_model_internal(OrdersModel model) { }
protected virtual void on_security_md_internal(SecurityMD? security_md) { }
// model
void IObserver<OrdersModel>.OnNext(OrdersModel model) {
if (this.model != null) {
// this is not expected to happen, if it does just log and continue.
// it should be investigated at some point, bc it is a redundant update, but there is no need to sound the alarm and crash.
bts.Log.Ui.warn("Redundant OrdersModel update detected.");
return;
}
this.model = model;
on_model_internal(model);
_reset();
}
void IObserver<OrdersModel>.OnError(Exception error) { }
void IObserver<OrdersModel>.OnCompleted() { }
// security md
void IObserver<SecurityMD?>.OnNext(SecurityMD? security_md) {
this.security_md = security_md;
on_security_md_internal(security_md);
_reset();
}
void IObserver<SecurityMD?>.OnError(Exception error) { }
void IObserver<SecurityMD?>.OnCompleted() { }
IDisposable _hook;
void _reset() {
if (model != null && security.HasValue) {
var algo_data = model.factory.default_algos(security.Value);
var default_algo = new AlgoKey(OrderDataHelper.get_default_algo(OrderDataHelper.get_algo_format(security.Value.ContractCase)));
foreach (var sd in _child_algo_selectors)
sd.load_algo_data_recursive(algo_data, default_algo);
Disposable.replace(ref _hook, ObservableAutoWrapper.connect_item_hooks(child_algo_selectors, s => {
s.load_algo_data_recursive(algo_data, default_algo);
return Disposable.empty;
}));
}
}
public IDisposable Subscribe(IObserver<OrdersModel> observer) => throw new NotImplementedException();
#endregion
}
private abstract class OrderTypeVMBase<T> : OrderTypeVMBase where T : Google.Protobuf.IMessage, new() {
protected OrderTypeVMBase(OrdersModel model, string id, string display_name) : base(model, id, display_name) { }
struct AlgoSelectorData {
public readonly string prop_name;
public readonly AlgoSelector selector;
public readonly Func<AlgoDefi, AlgoDefi?> get_order;
public readonly Action<AlgoDef, AlgoDef> set_order;
public override CustomOneofCase order_type =>
OrderDataHelper.get_order_type(new T());
public AlgoSelectorData(string id, AlgoSelector selector, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order) {
this.prop_name = id;
this.selector = selector;
this.get_order = get_order;
this.set_order = set_order;
}
}
public override string type_name => new T().Descriptor.Name;
class AlgoSelector : IAlgoSelector, INotifyPropertyChanged {
IAlgoVM _algo;
IReadOnlyDictionary<AlgoKey, AlgoData> _pending_data;
AlgoKey? _pending_default;
public AlgoSelector() =>
algos_view = ObservableAutoWrapper.create_sorted_wrapper(algos, AlgoCollectionHelper.algo_vm_comparer);
public void load_algo_data(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) {
_pending_data = algo_data;
_pending_default = default_algo;
_sync_formats();
selected_algo_changed += (o, n) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(selected_algo)));
}
public event PropertyChange<IAlgoVM> selected_algo_changed;
public event PropertyChangedEventHandler PropertyChanged;
public bool initialized { get; private set; }
public ObservableKeyedCollection<IAlgoVM, AlgoKey> algos { get; } =
new ObservableKeyedCollection<IAlgoVM, AlgoKey>(vm => vm.id);
public IReadOnlyObservableCollection<IAlgoVM> algos_view { get; }
public IAlgoVM selected_algo {
get {
if (!initialized) {
initialized = true;
_sync_formats();
if (_algo != null && _algo.can_expand)
_algo.is_expanded = true;
}
return _algo;
}
set {
// this is a hack around a wpf snafu: in the AlgoStudio, the ComboBox bound to order_types/value, does not have a stable DataContext.
// Its DataContext is bound to the selected-definition/template. When this changes, the ItemsSource changes, and the [ComboBox]view always sets its SelectedItem to null.
// We must do something to prevent this, it isn't a mere annoyance that forces the user to re-select the ordertype after they select another template.
// In AlgoStudio, the ComboBox is only enabled for definining a new algo-structure, for templates it is disabled, so the user can't even open the dropdown!
// There is probably a better solution/workaround for this problem, but in the meantime this does the trick.
if (value == null && _algo != null && algos.Contains(_algo))
return;
_select_algo(value);
}
}
void _select_algo(IAlgoVM new_algo) {
if (new_algo != _algo) {
var old_algo = _algo;
_algo = new_algo;
selected_algo_changed?.Invoke(old_algo, new_algo);
}
}
void _sync_formats() {
if (initialized && _pending_data != null) {
var fmt_algos = _pending_data;
algos.SyncWithDictionary(fmt_algos, d => create(d, is_expanded: true));
if (_algo == null || !algos.ContainsKey(_algo.id)) {
if (_pending_default.HasValue && algos.TryGetValue(_pending_default.Value, out IAlgoVM match))
selected_algo = match;
}
}
}
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnNext((IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo) value) =>
load_algo_data(value.algo_data, value.default_algo);
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnCompleted() { }
void IObserver<(IReadOnlyDictionary<AlgoKey, AlgoData> algo_data, AlgoKey? default_algo)>.OnError(Exception error) { }
}
#endregion
}
@@ -1,173 +1,20 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using PricerDef = bts.api.orderman.PricerOrderDefinition;
using PricerDefi = bts.api.orderman.PricerOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlinePricerOrderProperties
{
public InlinePricerOrderProperties (OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
price_offset_ticks = new InlineUserProperty<int>(0, false);
price_factor = new InlineUserProperty<double>(0, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<int> price_offset_ticks;
public readonly InlineUserProperty<double> price_factor;
}
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class PricerOrderVM : OrderTypeVMBase<PricerDef, PricerDefi> {
readonly Property<int> _price_offset_ticks;
readonly Property<double> _price_factor;
class PricerOrderVM : OrderTypeVMBase<PricerOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlinePricerOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public int price_offset_ticks { get; set; } = 0;
public double price_factor { get; set; } = 1.0;
public PricerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlinePricerOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public PricerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlinePricerOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.price_offset_ticks.force_override)
{
price_offset_ticks = p.price_offset_ticks.value;
RaisePropertyChanged(nameof(price_offset_ticks));
}
if (p.price_factor.force_override)
{
price_factor = p.price_factor.value;
RaisePropertyChanged(nameof(price_factor));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.pricer_order();
i.PriceOffsetTicks = price_offset_ticks;
i.PriceFactor = price_factor;
child_order.assign_to(i.Child);
value.Pricer = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
public PricerOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_price_offset_ticks = add_property(nameof(price_offset_ticks), PricerDef.PriceOffsetTicksFieldNumber, 1);
_price_factor = add_property(nameof(price_factor), PricerDef.PriceFactorFieldNumber, 1.0);
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
public int price_offset_ticks { get => _price_offset_ticks.Value; set => _price_offset_ticks.set(value); }
public double price_factor { get => _price_factor.Value; set => _price_factor.set(value); }
}
}
}
@@ -1,111 +1,158 @@
using bts.api;
using bts;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Windows.Input;
using SpreaderDef = bts.api.orderman.SpreaderOrderDefinition;
using SpreaderDefi = bts.api.orderman.SpreaderOrderDefinitionImmutable;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class SpreaderOrderVM : OrderTypeVMBase<SpreaderOrderDefinition>, IOrderTypeVM, IDisposable {
readonly Property<SpreaderOrderDefinitionImmutable?> _template;
class SpreaderOrderVM : OrderTypeVMBase<SpreaderDef, SpreaderDefi>, IAlgoVM, ILazyAlgo, IObserver<SecurityMD?>, IObserver<OrdersModel> {
readonly Property<SpreaderDefi?> _template;
readonly StrategyEditorWrapper _strategy_editor_wrapper;
IDisposable _dispose;
OrdersModel _model;
SecurityMD? _security_md;
IDisposable _strategy_sub;
public SpreaderOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source, string id, string display_name)
: this(model, security_source, security_source.SelectMany(s => model.spreader.security_strategy(s.Id)
.Select(strategy => {
var so = model.factory.spreader_order();
so.Security = s.CloneToMutable();
so.ExecutionStrategy = strategy.CloneToMutable();
var soi = new SpreaderOrderDefinitionImmutable(so);
return new InlineUserProperty<SpreaderOrderDefinitionImmutable>(soi, true);
})), id, display_name) { }
public SpreaderOrderVM(
OrdersModel model,
IObservable<SecurityImmutable> security_source,
IObservable<InlineUserProperty<SpreaderOrderDefinitionImmutable>> order_template_source, string id, string display_name)
: base(model, id, display_name) {
_template = backing(nameof(template), new SpreaderOrderDefinitionImmutable?());
public SpreaderOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_template = backing<SpreaderDefi?>(nameof(template));
/// <see cref="_strategy_editor_wrapper"/> depends on <see cref="_template"/> (i.e. initialize the latter first).
_strategy_editor_wrapper = new StrategyEditorWrapper(this);
_dispose = Disposable.Create(
_strategy_editor_wrapper,
_template.OnDispatcher().Subscribe(vals => {
_validate();
}),
order_template_source.OnDispatcher().Subscribe(prop => {
if (prop.force_override || (!template.HasValue && prop.has_value)) {
_template.Value = prop.value;
_validate();
}
})
);
_validate();
concat_disposable(_strategy_editor_wrapper, _template.Subscribe(vals => validate()));
validate();
}
public SpreaderOrderDefinitionImmutable? template => _template.Value;
public SpreaderDefi? template { get => _template.Value; private set => _template.set(value); }
public SyntheticEditorVM strategy_editor => _strategy_editor_wrapper.vm;
public IEnumerable<DialogSkirtItem> skirt_items => _strategy_editor_wrapper.skirt_items;
public override bool editable_properties_open {
get => base.editable_properties_open;
public override bool is_expanded {
get => base.is_expanded;
set {
if (!value && template.HasValue && strategy_editor != null) {
var mutable_template = template.Value.CloneToMutable();
mutable_template.ExecutionStrategy = _strategy_editor_wrapper.vm.get_strategy().CloneToMutable();
_template.Value = new SpreaderOrderDefinitionImmutable(mutable_template);
_template.Value = new SpreaderDefi(mutable_template);
}
base.editable_properties_open = value;
base.is_expanded = value;
}
}
public bool is_loaded { get; private set; }
public override void assign_to(CustomOrderDefinition value) {
if (template.HasValue) {
value.Spreader = template.Value.CloneToMutable();
}
}
protected override void assign_to_internal(SpreaderDef value) =>
value.MergeFrom(template.HasValue ? template.Value.CloneToMutable() : new SpreaderDef());
public void Dispose() =>
Disposable.dispose(ref _dispose);
protected override void load_from_internal(SpreaderDefi value) =>
_template.set(value);
void _validate() {
protected override void validate() {
base.validate();
if (!template.HasValue)
set_error(nameof(template), "Waiting for security and/or strategy.", true);
else clear_error(nameof(template));
}
// lazily initializes SyntheticEditorVM and associated dialog skirt items
void IObserver<SecurityMD?>.OnCompleted() { }
void IObserver<SecurityMD?>.OnError(Exception error) { }
void IObserver<SecurityMD?>.OnNext(SecurityMD? security_md) {
_security_md = security_md;
_reset_strategy_sub();
}
void IObserver<OrdersModel>.OnCompleted() { }
void IObserver<OrdersModel>.OnError(Exception error) { }
void IObserver<OrdersModel>.OnNext(OrdersModel model) {
_model = model;
_reset_strategy_sub();
}
void _reset_strategy_sub() {
Disposable.dispose(ref _strategy_sub);
if (_model != null) {
if (_security_md.HasValue) {
_strategy_sub = _model.spreader.security_strategy(_security_md.Value.security.Id)
.Select(strategy => new SpreaderDefi?(_model.factory.spreader_orderi(_security_md.Value.security, strategy)))
.OnDispatcher()
.Subscribe(s => {
is_loaded = true;
_template.set(s);
});
}
}
}
/// <summary>
/// Lazily initializes <see cref="SyntheticEditorVM"/> and associated dialog skirt items.
/// </summary>
class StrategyEditorWrapper : IDisposable {
readonly SpreaderOrderVM _owner;
readonly PropertyUpdateGate _template_gate = new PropertyUpdateGate();
SyntheticEditorVM _vm;
DialogSkirtItem _save_strategy_item;
IDisposable _vm_strategy_sub;
bool _is_disposed;
public StrategyEditorWrapper(SpreaderOrderVM owner) {
_owner = owner;
_owner._template.Changed += _order_template_changed;
_owner._template.Changed += _on_template_changed;
}
public SyntheticEditorVM vm { get { _init(); return _vm; } }
public IEnumerable<DialogSkirtItem> skirt_items { get { _init(); yield return _save_strategy_item; } }
public void Dispose() {
Disposable.dispose(ref _vm);
_owner._template.Changed -= _order_template_changed;
}
void _init() {
if (_vm == null && _owner.template.HasValue) {
var def = _owner.template.Value;
_vm = new SyntheticEditorVM(_owner.model.spreader, def.Security, def.ExecutionStrategy, _owner.model.security_has_working_orders(def.Security.Id));
_save_strategy_item = new DialogSkirtItem("Save Strategy", _vm.commit);
public SyntheticEditorVM vm {
get {
_ensure_init();
return _vm;
}
}
void _order_template_changed(SpreaderOrderDefinitionImmutable? oldval, SpreaderOrderDefinitionImmutable? newval) {
if (_vm != null && newval.HasValue)
_vm.set_synthetic(newval.Value.Security, newval.Value.ExecutionStrategy);
public IEnumerable<DialogSkirtItem> skirt_items {
get {
_ensure_init();
yield return _save_strategy_item;
}
}
OrdersModel _model => _owner._model;
SpreaderDefi? _template { get => _owner.template; set => _owner.template = value; }
public void Dispose() {
Log.assert(!_is_disposed);
_is_disposed = true;
Disposable.dispose(ref _vm);
Disposable.dispose(ref _vm_strategy_sub);
_owner._template.Changed -= _on_template_changed;
}
static SyntheticEditorVM _mk_vm(OrdersModel model, SpreaderOrderDefinitionImmutable def) =>
new SyntheticEditorVM(model.spreader, def.Security, def.ExecutionStrategy, model.security_has_working_orders(def.Security.Id));
static DialogSkirtItem _mk_save_item(ICommand commit) =>
new DialogSkirtItem("Save Strategy", commit);
void _ensure_init() {
if (_vm == null && _model != null && _template.HasValue && _template.Value.HasSecurity) {
Log.isnull(_save_strategy_item);
Log.isnull(_vm_strategy_sub);
var tmp = _template.Value;
_vm = new SyntheticEditorVM(_model.spreader, tmp.Security, tmp.ExecutionStrategy, _model.security_has_working_orders(tmp.Security.Id));
_save_strategy_item = new DialogSkirtItem("Save Strategy", _vm.commit);
_vm_strategy_sub = _vm.strategy_observable.Subscribe(s => {
Log.assert(_template.HasValue);
_template_gate.try_update(() => _template = _template.Value.with(execution_strategy: s.CloneToMutable()));
});
_owner.RaisePropertyChanged(nameof(strategy_editor), nameof(skirt_items));
}
}
void _on_template_changed(SpreaderOrderDefinitionImmutable? oldval, SpreaderOrderDefinitionImmutable? newval) =>
_template_gate.try_update(() => {
if (_vm != null && newval.HasValue && newval.Value.HasExecutionStrategy && newval.Value.HasSecurity) {
_vm.set_synthetic(newval.Value.Security, newval.Value.ExecutionStrategy);
} else _ensure_init();
});
}
}
}
@@ -1,96 +1,68 @@
using bts.api;
using bts.api.orderman;
using mbts.co2;
using mbts.ui;
using System;
using System.Reactive.Linq;
using StopLimitDef = bts.api.orderman.StopLimitOrderDefinition;
using StopLimitDefi = bts.api.orderman.StopLimitOrderDefinitionImmutable;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class InlineStopLimitOrderProperties {
readonly Func<InlineUserProperty<double>> _get_stop_price;
class StopLimitOrderVM : OrderTypeVMBase<StopLimitDef, StopLimitDefi>, IObserver<SecurityMD?> {
readonly UserProperty<double> _stop_price;
SecurityMD? _security_md;
ulong _bbo_time_ref;
public static IObservable<InlineStopLimitOrderProperties> subscribe(IObservable<SecurityMD> security_md_source) {
ulong time = 0;
return security_md_source.Select(smd => new InlineStopLimitOrderProperties(() => {
smd.md.get_bbo(ref time, out NativePriceSize bid, out NativePriceSize ask);
return new InlineUserProperty<double>(bid.price);
}));
public StopLimitOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_stop_price = add_user_property(nameof(stop_price), StopLimitDef.StopPriceFieldNumber, double.NaN);
_resources.Add(_stop_price.Subscribe(_ => validate()));
}
public InlineStopLimitOrderProperties(Func<InlineUserProperty<double>> get_stop_price) =>
_get_stop_price = get_stop_price;
public InlineUserProperty<double> stop_price => _get_stop_price();
}
private class StopLimitOrderVM : OrderTypeVMBase<StopLimitOrderDefinition>, IDisposable {
UserProperty<double> _stop_price;
InlineStopLimitOrderProperties _inline_props;
IDisposable _dispose;
internal StopLimitOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source.Select(smd => smd.security.spec_or_default()), InlineStopLimitOrderProperties.subscribe(security_md_source), id, display_name) { }
internal StopLimitOrderVM(OrdersModel model, IObservable<ContractSpecificationImmutable> spec_source, IObservable<InlineStopLimitOrderProperties> inline_properties, string id, string display_name)
: base(model, id, display_name) {
_stop_price = new UserProperty<double>(backing(nameof(stop_price), double.NaN));
_dispose = Disposable.Create(
spec_source.OnDispatcher().Subscribe(s => {
spec = s;
RaisePropertyChanged(nameof(spec));
}), inline_properties.OnDispatcher().Subscribe(p => _inline_props = p));
}
public override bool editable_properties_open {
get => base.editable_properties_open;
public override bool is_expanded {
get => base.is_expanded;
set {
if (value) {
if (_update_inline_props())
_validate();
}
base.editable_properties_open = value;
if (value)
_ensure_init_stop_price();
base.is_expanded = value;
}
}
public double stop_price {
get => _stop_price.Value;
set {
_stop_price.Value = value;
_validate();
}
public double stop_price { get => _stop_price.Value; set => _stop_price.Value = value; }
public ContractSpecificationImmutable? spec => _security_md.spec_or_default();
protected override void load_from_internal(StopLimitDefi value) {
// TODO: the StopLimitOrderDefinition, StopLimitOrderDefinitionImmutable needs relative vs absolute prices to function as a useful template (talk to Pedro)
_stop_price.bypass_setter(value.StopPrice);
}
public ContractSpecificationImmutable spec { get; private set; } =
SecurityDataHelper.Defaults.ContractSpecificationImmutable;
public override void assign_to(CustomOrderDefinition value) {
_update_inline_props();
_validate();
if (!HasErrors) {
var sl = factory.stop_limit_order();
sl.StopPrice = stop_price;
value.StopLimit = sl;
}
}
public void Dispose() => Disposable.dispose(ref _dispose);
// no need to constantly poll the md, just check the inline props when the popup opens, and right before sending an order
// (if the user never looks at the popup, assume that the bid_price will be used)
// TODO: add settings so the trigger-price can default to something relative to the md, e.g "bid-price" or "ask-price - nticks" or "best-bid-price with a minimum size of 10"
bool _update_inline_props() {
var inline_stop_price = _inline_props.stop_price;
if (inline_stop_price.has_value && (inline_stop_price.force_override || !_stop_price.setter_called)) {
_stop_price.bypass_setter(inline_stop_price.value);
return true;
} else return false;
bool _ensure_init_stop_price() {
if (_security_md.HasValue && !_stop_price.setter_called && _security_md.Value.md.get_bbo(ref _bbo_time_ref, out NativePriceSize bid, out NativePriceSize ask)) {
if (!double.IsNaN(bid.price)) {
_stop_price.bypass_setter(bid.price);
return true;
} else if (!double.IsNaN(ask.price)) {
_stop_price.bypass_setter(ask.price);
return true;
}
}
return false;
}
void _validate() {
protected override void validate() {
using (validation())
validation_assert(!DoubleHelper.IsNaNOrInfinity(stop_price), string.Empty, nameof(stop_price));
}
void IObserver<SecurityMD?>.OnCompleted() { }
void IObserver<SecurityMD?>.OnError(Exception error) { }
void IObserver<SecurityMD?>.OnNext(SecurityMD? security_md) {
_security_md = security_md;
RaisePropertyChanged(nameof(spec));
}
}
}
}
@@ -1,36 +1,26 @@
using bts.api;
using bts.api.orderman;
using StopDef = bts.api.orderman.StopOrderDefinition;
using StopDefi = bts.api.orderman.StopOrderDefinitionImmutable;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class StopOrderVM : OrderTypeVMBase<StopOrderDefinition> {
double _stop_price = 0;
class StopOrderVM : OrderTypeVMBase<StopDef, StopDefi> {
readonly Property<double> _stop_price;
internal StopOrderVM(OrdersModel model, string id, string display_name) : base(model, id, display_name) { }
public StopOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) =>
_stop_price = add_property(nameof(stop_price), StopDef.StopPriceFieldNumber, 0.0);
public double stop_price {
get => _stop_price;
get => _stop_price.Value;
set {
_stop_price = value;
_validate();
_stop_price.set(value);
validate();
}
}
public ContractSpecificationImmutable spec { get; private set; } =
SecurityDataHelper.Defaults.ContractSpecificationImmutable;
public override void assign_to(CustomOrderDefinition value) {
if (!HasErrors) {
var s = factory.stop_order();
s.StopPrice = stop_price;
value.Stop = s;
}
}
void _validate() {
if (DoubleHelper.IsNaNOrInfinity(_stop_price))
set_error(nameof(stop_price), string.Empty, true);
else clear_error(nameof(stop_price));
protected override void validate() {
base.validate();
assert(!DoubleHelper.IsNaNOrInfinity(stop_price), nameof(stop_price), "Invalid stop price");
}
}
}
@@ -0,0 +1,28 @@
using bts.spark;
using TickDef = bts.api.orderman.TickOrderDefinition;
using TickDefi = bts.api.orderman.TickOrderDefinitionImmutable;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class TickOrderVM : OrderTypeVMBase<TickDef, TickDefi> {
readonly Property<uint> _tick_offset_on_deploy, _cross_ticks, _max_chase_ticks;
readonly Property<QuantityMeasureImmutable> _cross_threshold;
readonly Property<bool> _detach_on_toward;
public TickOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_tick_offset_on_deploy = add_property(nameof(max_chase_ticks), TickDef.TickOffsetOnDeployFieldNumber, 0u);
_cross_threshold = add_property<QuantityMeasure, QuantityMeasureImmutable>(nameof(cross_threshold), TickDef.CrossThresholdFieldNumber, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 }));
_max_chase_ticks = add_property(nameof(max_chase_ticks), TickDef.MaxChaseTicksFieldNumber, 10u);
_cross_ticks = add_property(nameof(cross_ticks), TickDef.CrossTicksFieldNumber, 0u);
_detach_on_toward = add_property(nameof(detach_on_toward), TickDef.DetachOnTowardFieldNumber, true);
}
public QuantityMeasureImmutable cross_threshold { get => _cross_threshold.Value; set => _cross_threshold.set(value); }
public uint cross_ticks { get => _cross_ticks.Value; set => _cross_ticks.set(value); }
public uint tick_offset_on_deploy { get => _tick_offset_on_deploy.Value; set => _tick_offset_on_deploy.set(value); }
public uint max_chase_ticks { get => _max_chase_ticks.Value; set => _max_chase_ticks.set(value); }
public bool detach_on_toward { get => _detach_on_toward.Value; set => _detach_on_toward.set(value); }
}
}
}
@@ -1,78 +1,30 @@
using bts.api;
using bts.api.orderman;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class InlineTimeBoxOrderProperties {
public InlineTimeBoxOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types) {
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
start = new InlineUserProperty<DateTime>(DateTime.Now, true);
stop = new InlineUserProperty<DateTime>(DateTime.Now.AddMinutes(5), true);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<DateTime> start, stop;
}
class TimeBoxOrderVM : OrderTypeVMBase<TimeBoxOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
class TimeBoxOrderVM : OrderTypeVMBase<TimeBoxOrderDefinition, TimeBoxOrderDefinitionImmutable> {
const double _start_immediately_delay_ms = 500;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineTimeBoxOrderProperties _inline_props;
TimeTextTuple _absolute_start = TimeTextTuple.FromDateTime(DateTime.Now.AddMinutes(5)), _absolute_stop = TimeTextTuple.FromDateTime(DateTime.Now.AddMinutes(10));
TimeSpan? _relative_start = TimeSpan.FromMinutes(5), _relative_stop = TimeSpan.FromMinutes(5);
StartMode _start_mode = StartMode.In;
StopMode _stop_mode = StopMode.After;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public TimeBoxOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTimeBoxOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public TimeBoxOrderVM(OrdersModel model,
IObservable<SecurityMD> security_md_source,
IObservable<InlineTimeBoxOrderProperties> inline_properties, string id, string display_name)
: base(model, id, display_name) {
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override) {
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override)) {
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.start.force_override) {
absolute_start = TimeTextTuple.FromDateTime(p.start.value);
RaisePropertyChanged(nameof(absolute_start));
}
if (p.stop.force_override) {
absolute_stop = TimeTextTuple.FromDateTime(p.stop.value);
RaisePropertyChanged(nameof(absolute_stop));
}
_inline_props = p;
_validate();
})
);
_validate();
public TimeBoxOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
add_property(def => def.Start, (def, val) => def.Start = val, val => absolute_start = TimeTextTuple.FromDateTime(val.ToDateTime()), () => {
_validate(out DateTime? start_time, out DateTime? _);
return start_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
});
add_property(def => def.Stop, (def, val) => def.Stop = val, val => absolute_stop = TimeTextTuple.FromDateTime(val.ToDateTime()), () => {
_validate(out DateTime? _, out DateTime? stop_time);
return stop_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
});
validate();
}
public enum StartMode {
@@ -91,40 +43,11 @@ namespace mbts.spark {
public IEnumerable<StartMode> start_modes => EnumHelper.get_values<StartMode>();
public IEnumerable<StopMode> stop_modes => EnumHelper.get_values<StopMode>();
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null) {
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
}
return _child_order_choices;
}
}
public IOrderTypeVM child_order {
get {
init();
return _child_order;
}
set {
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei) {
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public StartMode start_mode {
get => _start_mode;
set {
_start_mode = value;
_validate();
validate();
RaisePropertyChanged(nameof(show_absolute_start), nameof(show_relative_start));
}
}
@@ -132,61 +55,27 @@ namespace mbts.spark {
get => _stop_mode;
set {
_stop_mode = value;
_validate();
validate();
RaisePropertyChanged(nameof(show_absolute_stop), nameof(show_relative_stop));
}
}
public TimeTextTuple absolute_start { get => _absolute_start; set { _absolute_start = value; _validate(); } }
public TimeTextTuple absolute_stop { get => _absolute_stop; set { _absolute_stop = value; _validate(); } }
public TimeSpan? relative_start { get => _relative_start; set { _relative_start = value; _validate(); } }
public TimeSpan? relative_stop { get => _relative_stop; set { _relative_stop = value; _validate(); } }
public TimeTextTuple absolute_start { get => _absolute_start; set { _absolute_start = value; validate(); } }
public TimeTextTuple absolute_stop { get => _absolute_stop; set { _absolute_stop = value; validate(); } }
public TimeSpan? relative_start { get => _relative_start; set { _relative_start = value; validate(); } }
public TimeSpan? relative_stop { get => _relative_stop; set { _relative_stop = value; validate(); } }
public bool show_absolute_start => _start_mode == StartMode.At;
public bool show_relative_start => _start_mode == StartMode.In;
public bool show_absolute_stop => _stop_mode == StopMode.At;
public bool show_relative_stop => _stop_mode == StopMode.After;
public override void assign_to(CustomOrderDefinition value) {
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
var (start_time, stop_time) = _validate();
if (!HasErrors) {
var tb = factory.time_box_order();
tb.Start = start_time.Value.ToUniversalTime().ToGoogleTime();
tb.Stop = stop_time.Value.ToUniversalTime().ToGoogleTime();
child_order.assign_to(tb.Child);
value.TimeBox = tb;
}
}
protected override void validate() =>
_validate(out DateTime? start, out DateTime? stop);
public void Dispose() {
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
void _validate(out DateTime? start, out DateTime? stop) =>
_validate_time_params(out start, out stop);
public override void init() {
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order() {
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot) {
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
(DateTime? start_time, DateTime? stop_time) _validate() {
assert(_child_order != null && !(_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors), nameof(child_order));
void _validate_time_params(out DateTime? start, out DateTime? stop) {
// ti.start_name is null if mode is Now, stop_name if mode is WhenCompleted
var now = DateTime.Now;
var ti = get_time_info();
@@ -200,7 +89,8 @@ namespace mbts.spark {
set_error(ti.stop_name, string.Empty, false);
else clear_error(ti.stop_name);
}
return (ti.start_time, ti.stop_time);
start = ti.start_time;
stop = ti.stop_time;
//
(DateTime? start_time, string start_name, DateTime? stop_time, string stop_name) get_time_info() {
DateTime? start_time = null, stop_time = null;
@@ -1,178 +1,21 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using bts.spark;
using TopDef = bts.api.orderman.TopOrderDefinition;
using TopDefi = bts.api.orderman.TopOrderDefinitionImmutable;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineTopOrderProperties
{
public InlineTopOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class TopOrderVM : OrderTypeVMBase<TopDef, TopDefi> {
readonly Property<uint> _watch_level_tick_offset;
readonly Property<QuantityMeasureImmutable> _top_threshold;
watch_level_tick_offset = new InlineUserProperty<uint>(0, false);
top_threshold = new InlineUserProperty<bts.spark.QuantityMeasure>(
new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 }, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<uint> watch_level_tick_offset;
public readonly InlineUserProperty<bts.spark.QuantityMeasure> top_threshold;
}
class TopOrderVM : OrderTypeVMBase<TopOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineTopOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public uint watch_level_tick_offset { get; set; } = 0;
public bts.spark.QuantityMeasure top_threshold { get; set; } = new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 };
public TopOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTopOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name)
{ }
public TopOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineTopOrderProperties> inline_properties, string id, string display_name) : base(model, id, display_name)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value.key.type);
}
if (p.watch_level_tick_offset.force_override)
{
watch_level_tick_offset = p.watch_level_tick_offset.value;
RaisePropertyChanged(nameof(watch_level_tick_offset));
}
if (p.top_threshold.force_override)
{
top_threshold = p.top_threshold.value;
RaisePropertyChanged(nameof(top_threshold));
}
_inline_props = p;
_validate();
})
);
_validate();
public TopOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_watch_level_tick_offset = add_property(nameof(watch_level_tick_offset), TopDef.WatchLevelTickOffsetFieldNumber, 0u);
_top_threshold = add_property<QuantityMeasure, QuantityMeasureImmutable>(nameof(top_threshold), TopDef.TopThresholdFieldNumber, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 }));
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.top_order();
i.WatchLevelTickOffset = watch_level_tick_offset;
i.TopThreshold = top_threshold;
child_order.assign_to(i.Child);
value.Top = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
public uint watch_level_tick_offset { get => _watch_level_tick_offset.Value; set => _watch_level_tick_offset.set(value); }
public QuantityMeasureImmutable top_threshold { get => _top_threshold.Value; set => _top_threshold.set(value); }
}
}
}
@@ -1,240 +1,146 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
using TriggerDef = bts.api.orderman.TriggerOrderDefinition;
using TriggerDefi = bts.api.orderman.TriggerOrderDefinitionImmutable;
using OrderpriceOneofCase = bts.api.orderman.TriggerAction.OrderpriceOneofCase;
using PayupPriceType = bts.api.orderman.TriggerPayupPrice.Types.TriggerPayupPriceType;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class InlineTriggerOrderProperties {
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
public readonly InlineUserProperty<TriggerPriceType> trigger_price_type;
public readonly InlineUserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType> payup_price_type;
public readonly InlineUserProperty<double> fixed_price;
public readonly InlineUserProperty<int> payup_ticks;
public readonly InlineUserProperty<bool> use_fixed_price, is_priceout_checked, is_timeout_checked;
public readonly InlineUserProperty<int> timeout_secs;
public InlineTriggerOrderProperties(OrderTemplateHeader selected_child_order_type, IReadOnlyCollection<OrderTemplateHeader> child_order_types) {
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<OrderTemplateHeader>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>>(child_order_types, true);
trigger_price_type = new InlineUserProperty<TriggerPriceType>(TriggerPriceType.Bid, false);
payup_price_type = new InlineUserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType>();
use_fixed_price = new InlineUserProperty<bool>(false);
fixed_price = new InlineUserProperty<double>();
payup_ticks = new InlineUserProperty<int>();
is_priceout_checked = new InlineUserProperty<bool>();
is_timeout_checked = new InlineUserProperty<bool>();
timeout_secs = new InlineUserProperty<int>(10);
}
}
class TriggerOrderVM : OrderTypeVMBase<TriggerOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
readonly IObservable<SecurityMD> _security_md_source;
readonly UserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType> _payup_price_type;
class TriggerOrderVM : OrderTypeVMBase<TriggerDef, TriggerDefi>, IObserver<SecurityMD?> {
readonly UserProperty<PayupPriceType> _payup_price_type;
readonly UserProperty<TriggerPriceType> _trigger_price_type;
readonly UserProperty<OrderpriceOneofCase> _order_price_case;
readonly UserProperty<double> _fixed_price;
readonly UserProperty<int> _payup_ticks, _timeout_secs;
readonly UserProperty<bool> _use_fixed_price, _is_timeout_checked, _is_priceout_checked;
SecurityMD? _security_md;
SecurityImmutable? _security => _security_md.security();
ObservableCollection<OrderTemplateHeader> _order_types = new ObservableCollection<OrderTemplateHeader>();
ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader> _child_order_choices;
InlineTriggerOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
readonly UserProperty<bool> _is_timeout_checked, _is_priceout_checked;
ulong _bbo_ref = 0, _last_trade_ref = 0;
double _best_bid = double.NaN, _best_ask = double.NaN, _last_trade_price = double.NaN;
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTriggerOrderProperties(new OrderTemplateHeader(model.factory.default_order_type(smd.security)), model.factory.default_order_types(smd.security).Select(t => new OrderTemplateHeader(t)).ToList())), id, display_name) { }
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, IObservable<InlineTriggerOrderProperties> inline_properties, string id, string display_name)
: base(model, id, display_name) {
public TriggerOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_trigger_price_type = create_user_prop(nameof(trigger_price_type), TriggerPriceType.Bid);
_use_fixed_price = create_user_prop(nameof(use_fixed_price), true);
_order_price_case = create_user_prop(nameof(order_price_case), OrderpriceOneofCase.Payup);
_fixed_price = create_user_prop(nameof(fixed_price), double.NaN);
_payup_price_type = create_user_prop(nameof(payup_price_type), TriggerPayupPrice.Types.TriggerPayupPriceType.Trigger);
_payup_price_type = create_user_prop(nameof(payup_price_type), PayupPriceType.Trigger);
_payup_ticks = create_user_prop(nameof(payup_ticks), 0);
_is_priceout_checked = create_user_prop(nameof(is_priceout_checked), false);
_is_timeout_checked = create_user_prop(nameof(is_timeout_checked), false);
_timeout_secs = create_user_prop(nameof(timeout_secs), 0);
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => {
_security_md = smd;
_refresh_md();
if (double.IsNaN(fixed_price) || !_fixed_price.setter_called) {
switch (trigger_price_type) {
case TriggerPriceType.Bid: _fixed_price.bypass_setter(_best_bid); break;
case TriggerPriceType.Ask: _fixed_price.bypass_setter(_best_ask); break;
case TriggerPriceType.LastTradePrice: _fixed_price.bypass_setter(_last_trade_price); break;
}
}
}),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override) {
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override)) {
_select_child_order(p.selected_child_order_type.value.key.type);
}
// trigger price
_trigger_price_type.on_inline_prop(p.trigger_price_type);
// fixed price
_use_fixed_price.on_inline_prop(p.use_fixed_price);
_fixed_price.on_inline_prop(p.fixed_price);
// payup
_payup_price_type.on_inline_prop(p.payup_price_type);
_payup_ticks.on_inline_prop(p.payup_ticks);
// exit
_is_priceout_checked.on_inline_prop(p.is_priceout_checked);
_is_timeout_checked.on_inline_prop(p.is_timeout_checked);
_timeout_secs.on_inline_prop(p.timeout_secs);
_inline_props = p;
_validate();
})
);
_validate();
_timeout_secs = create_user_prop(nameof(timeout_secs), 10);
validate();
//
UserProperty<T> create_user_prop<T>(string name, T default_value = default) {
var rv = user_backing(name, default_value);
rv.Changed += validation_callback;
return rv;
}
void validation_callback<T>(T oldval, T newval) => _validate();
void validation_callback<T>(T oldval, T newval) => validate();
}
// trigger price
/// trigger price
public IEnumerable<TriggerPriceType> trigger_price_types => EnumHelper.get_values_except(TriggerPriceType.LastTradePrice);
public TriggerPriceType trigger_price_type { get => _trigger_price_type.Value; set => _trigger_price_type.Value = value; }
// fixed price
public bool use_fixed_price { get => _use_fixed_price.Value; set => _use_fixed_price.Value = value; }
public OrderpriceOneofCase order_price_case { get => _order_price_case.Value; set => _order_price_case.Value = value; }
// fixed
public double fixed_price { get => _fixed_price.Value; set => _fixed_price.Value = value; }
// payup
public IEnumerable<TriggerPayupPrice.Types.TriggerPayupPriceType> payup_price_types => new[] { TriggerPayupPrice.Types.TriggerPayupPriceType.Trigger };
public TriggerPayupPrice.Types.TriggerPayupPriceType payup_price_type { get => _payup_price_type.Value; set => _payup_price_type.Value = value; }
public IEnumerable<PayupPriceType> payup_price_types => new[] { PayupPriceType.Trigger };
public PayupPriceType payup_price_type { get => _payup_price_type.Value; set => _payup_price_type.Value = value; }
public int payup_ticks { get => _payup_ticks.Value; set => _payup_ticks.Value = value; }
// exit
/// exit
public bool is_priceout_checked { get => _is_priceout_checked.Value; set => _is_priceout_checked.Value = value; }
public bool is_timeout_checked { get => _is_timeout_checked.Value; set => _is_timeout_checked.Value = value; }
public int timeout_secs { get => _timeout_secs.Value; set => _timeout_secs.Value = value; }
//
public ContractSpecificationImmutable spec => _security.spec_or_default();
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, OrderTemplateHeader>(_order_types, ot => create(ot.key.type, ot.key.name, ot.display_name, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order {
get {
init();
return _child_order;
}
set {
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei) {
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public override void assign_to(CustomOrderDefinition value) {
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors) {
var i = factory.trigger_order();
i.TriggerAction = new TriggerAction {
SecurityId = _security.Value.Id,
};
i.TriggerCondition = new TriggerCondition() {
PriceType = trigger_price_type,
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() },
};
i.ExitCondition = new TriggerExitCondition {
ConditionalCancel = is_priceout_checked,
TimeoutEnabled = is_timeout_checked,
TimeoutSeconds = (uint)(timeout_secs)
};
if (use_fixed_price) {
protected override void assign_to_internal(TriggerDef trigger_def) {
trigger_def.TriggerAction = new TriggerAction();
if (security.HasValue)
trigger_def.TriggerAction.SecurityId = security.Value.Id;
trigger_def.TriggerCondition = new TriggerCondition() {
PriceType = trigger_price_type,
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() },
};
trigger_def.ExitCondition = new TriggerExitCondition {
ConditionalCancel = is_priceout_checked,
TimeoutEnabled = is_timeout_checked,
TimeoutSeconds = (uint)(timeout_secs)
};
switch (order_price_case) {
case OrderpriceOneofCase.Price:
// should already be null, setting it here for clarity
i.TriggerAction.Payup = null;
i.TriggerAction.Price = fixed_price;
} else {
i.TriggerAction.Price = double.NaN;
i.TriggerAction.Payup = new TriggerPayupPrice {
trigger_def.TriggerAction.Payup = null;
trigger_def.TriggerAction.Price = fixed_price;
break;
case OrderpriceOneofCase.Payup:
trigger_def.TriggerAction.Price = double.NaN;
trigger_def.TriggerAction.Payup = new TriggerPayupPrice {
PayupTicks = payup_ticks,
PayupPriceType = payup_price_type
};
}
child_order.assign_to(i.Child);
value.Trigger = i;
break;
}
}
public void Dispose() {
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init() {
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
protected override void load_from_internal(TriggerDefi trigger_defi) {
if (trigger_defi.HasTriggerCondition) {
trigger_price_type = trigger_defi.TriggerCondition.PriceType;
}
if (trigger_defi.HasExitCondition) {
var exit_condition = trigger_defi.ExitCondition;
is_priceout_checked = exit_condition.ConditionalCancel;
is_timeout_checked = exit_condition.TimeoutEnabled;
if (exit_condition.TimeoutSeconds < int.MaxValue)
timeout_secs = (int)exit_condition.TimeoutSeconds;
}
if (trigger_defi.HasTriggerAction) {
var trigger_action = trigger_defi.TriggerAction;
if (trigger_action.HasPayup) {
order_price_case = OrderpriceOneofCase.Payup;
fixed_price = double.NaN;
var payup = trigger_action.Payup;
payup_ticks = payup.PayupTicks;
payup_price_type = payup.PayupPriceType;
} else {
order_price_case = OrderpriceOneofCase.Price;
fixed_price = trigger_action.Price;
}
}
}
void _refresh_md() {
if (_security.HasValue) {
_security_md.Value.md.get_bbo(ref _bbo_ref, out co2.NativePriceSize bid, out co2.NativePriceSize ask);
if (security.HasValue) {
security_md.Value.md.get_bbo(ref _bbo_ref, out co2.NativePriceSize bid, out co2.NativePriceSize ask);
_best_bid = bid.price;
_best_ask = ask.price;
_security_md.Value.md.get_last_trade(ref _last_trade_ref, out co2.NativePriceSize ps, out DateTime ts, out ulong v);
security_md.Value.md.get_last_trade(ref _last_trade_ref, out co2.NativePriceSize ps, out DateTime ts, out ulong v);
}
}
void _select_child_order() {
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value.key.type :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
protected override void validate() {
using (validation(nameof(fixed_price), nameof(order_price_case))) {
switch (order_price_case) {
case OrderpriceOneofCase.Price: validation_assert(!double.IsNaN(fixed_price), "Fixed price is invalid.", nameof(fixed_price)); break;
case OrderpriceOneofCase.None: validation_assert(false, "Please specify order price case (Fixed/Payup).", nameof(order_price_case)); break;
case OrderpriceOneofCase.Payup: break;
default: throw ExceptionBuilder.Argument.unexpected_case(order_price_case, nameof(order_price_case));
}
}
assert(!is_timeout_checked || timeout_secs > 0, nameof(timeout_secs), "Please specify valid Timeout(secs).");
}
void _select_child_order(CustomOneofCase ot) {
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate() {
assert(!use_fixed_price || !double.IsNaN(fixed_price), nameof(fixed_price));
assert(!is_timeout_checked || timeout_secs > 0, nameof(timeout_secs));
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
protected override void on_security_md_internal(SecurityMD? security_md) {
_refresh_md();
if (double.IsNaN(fixed_price) || !_fixed_price.setter_called) {
switch (trigger_price_type) {
case TriggerPriceType.Bid: _fixed_price.bypass_setter(_best_bid); break;
case TriggerPriceType.Ask: _fixed_price.bypass_setter(_best_ask); break;
case TriggerPriceType.LastTradePrice: _fixed_price.bypass_setter(_last_trade_price); break;
}
}
}
}
}
+45 -16
View File
@@ -4,6 +4,7 @@ using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.spark;
using bts.utils;
using mbts.collections;
using mbts.spark.utilities;
using mbts.utils;
@@ -19,7 +20,6 @@ using System.Threading.Tasks;
using OrderUpdate = bts.api.core.TableUpdate<(bts.api.SecurityImmutable? sec, bts.api.orderman.OrderRecordImmutable order), uint>;
namespace mbts.spark {
[Export]
class OrdersModel : IDisposable {
readonly IBus _bus;
@@ -35,9 +35,8 @@ namespace mbts.spark {
IDisposable _dispose;
[ImportingConstructor]
private OrdersModel(IBus bus, OrderFactory factory, OrderService service, PositionService position_service,
SpreaderModel spreader, ErrorReporter error, DynamicOrderHelper dynamic_helper, AdminModel admin_model,
SecurityStore sstore) {
OrdersModel(IBus bus, OrderFactory factory, OrderService service, PositionService position_service,
SpreaderModel spreader, DynamicOrderHelper dynamic_helper, AdminModel admin_model, IAlgoStudioModel algo_model, SecurityStore sstore, ErrorReporter error) {
_bus = bus;
_factory = factory;
_service = service;
@@ -45,6 +44,8 @@ namespace mbts.spark {
_spreader = spreader;
_error = error;
_dynamic_helper = dynamic_helper;
this.admin_model = admin_model;
this.algo_model = algo_model;
var scheduler = ThreadPoolScheduler.Instance;
var interval = TimeSpan.FromMilliseconds(100);
on_orders =
@@ -67,19 +68,45 @@ namespace mbts.spark {
.filter(t => t.sec.HasValue)
.Select(t => t.sec.Value);
on_fills =
_activity = new OrderActivitySummarizer(bus, on_orders);
_security_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_positions_demuxer = new TableUpdateDemuxer<PositionUnitImmutable, int, uint>(o => o.RecordId, p => p.SecurityId);
var algo_meta_join = algo_model.definitions.LeftJoin<AlgoData, AlgoDefinitionMetadata, (AlgoData algo, AlgoDefinitionMetadata? meta), AlgoKey>(
algo_model.metadata_service.subscribe_metadata().Table(m => m.id),
d => d.key,
m => m.id,
(algo, k, meta) => (algo, meta),
(algo, k) => (algo, null),
t => t.algo.key);
var order_secs_algo_meta_join = on_orders.LeftJoin(
algo_meta_join,
t => t.order.Key,
am => am.algo.key,
t => new AlgoKey(new bts.persist.algo.AlgoPersistedKey(t.order.Def.AlgoTemplateKey)),
(os, okey, am, mkey) => new OrderSecurityAlgoMeta(os.order, os.sec, am.algo, am.meta),
(os, okey, mkey) => new OrderSecurityAlgoMeta(os.order, os.sec, null, null),
ot => ot.order.Key);
on_order_tuples = order_secs_algo_meta_join;
var on_fills =
_service.subscribei_fills()
.Naggle(interval, scheduler)
.PermissionFilter(admin_model.on_admin_data)
.join(sstore, f => f.SecurityKey)
.Table().Cache();
_activity = new OrderActivitySummarizer(bus, on_orders);
on_fill_tuples = FillTupleSource.create_observable(on_orders, on_fills);
_security_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_positions_demuxer = new TableUpdateDemuxer<PositionUnitImmutable, int, uint>(o => o.RecordId, p => p.SecurityId);
var fill_order_tuples_join = on_fills.LeftJoin(
on_order_tuples,
f => f.FillKey,
o => o.order.Key,
f => f.OrderKey,
(f, fk, o, ok) => new FillTuple(f, o),
(f, fk, ok) => new FillTuple(f, null),
f => f.fill.FillKey);
on_fill_tuples = fill_order_tuples_join;
_dispose = Disposable.Create(
//on_orders.AddRemoveOnly().Subscribe(_security_orders_demuxer),
on_positions.AddRemoveOnly().Subscribe(_security_positions_demuxer),
on_orders.Select(t => t.order, o => o.Key).Subscribe(_security_orders_demuxer),
on_positions.Subscribe(_security_positions_demuxer),
order_secs_algo_meta_join.Connect(),
algo_meta_join.Connect(),
fill_order_tuples_join.Connect(),
_bus.subscribe(SparkTags.CreateOrder).Subscribe(a => send_order(a.definition, a.price, a.size).ignore()),
_bus.subscribe(SparkTags.RecreateOrder).Subscribe(a => a.ForEach(x => send_order(x.definition, x.price, x.size).ignore())),
_bus.subscribe(SparkTags.CancelOrders).Subscribe(x => cancel_orders(x).ignore()),
@@ -93,16 +120,18 @@ namespace mbts.spark {
public SpreaderModel spreader => _spreader;
public DynamicOrderHelper dynamic_helper => _dynamic_helper;
public IObservable<OrderUpdate> on_orders { get; }
public IObservable<TableUpdate<OrderSecurityAlgoMeta, uint>> on_order_tuples { get; }
public IObservable<IIncrementalUpdate<SecurityImmutable, uint>> on_order_securities { get; }
public IObservable<TableUpdate<(SecurityImmutable?,FillImmutable), string>> on_fills { get; }
public IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> on_fill_tuples { get; }
public IObservable<TableUpdate<FillTuple, string>> on_fill_tuples { get; }
public IObservable<IReadOnlyDictionary<uint,OrderSecurity>> working_orders { get; }
public IObservable<TableUpdate<PositionUnitImmutable, int>> on_positions { get; }
public AdminModel admin_model { get; }
public IAlgoStudioModel algo_model { get; }
public IObservable<ITableUpdateTransform<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
public IObservable<TableUpdate<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
_security_orders_demuxer.subscribe(security);
public IObservable<ITableUpdateTransform<PositionUnitImmutable, int>> on_security_positions(uint security) =>
public IObservable<TableUpdate<PositionUnitImmutable, int>> on_security_positions(uint security) =>
_security_positions_demuxer.subscribe(security);
#endregion
+4
View File
@@ -11,6 +11,7 @@
<ResourceDictionary Source="/view/Resources/Buttons.xaml" />
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml"/>
<ResourceDictionary Source="/view/Resources/MenuItems.xaml" />
<ResourceDictionary Source="/view/Controls/EditableTextBlock/EditableTextBlock.xaml"/>
<ResourceDictionary Source="/view/Controls/DragDropItemsControl/DragDropItemsControl.xaml" />
<ResourceDictionary Source="/view/Controls/DragDropItemsControl/DraggableContentControl.xaml" />
<ResourceDictionary Source="/view/Controls/DragDropItemsControl/DragDropListBox.xaml" />
@@ -35,6 +36,9 @@
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DiscreteValuesFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/TimeFilterControl.xaml"/>
<ResourceDictionary Source="/Modules/Spreader/ExecutionStrategyEditor.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoContentTemplateSelector.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoPickerNodeView.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Override xp/win7 style themes with Win8 style flat for certain controls -->
+102 -9
View File
@@ -9,23 +9,53 @@ using System.Windows.Input;
using System.Windows.Media;
using static mbts.spark.SparkTags;
namespace bts.spark
{
namespace bts.spark {
public abstract class SparkCommand {
public SparkCommand(string title, ImageSource icon) {
this.title = title;
string _title;
bool _show_in_toolbar, _show_in_context_menu;
public SparkCommand(string title, ImageSource icon, bool show_in_toolbar = true, bool show_in_context_menu = true) {
_title = title;
this.icon = icon;
_show_in_toolbar = show_in_toolbar;
_show_in_context_menu = show_in_context_menu;
}
public event Action title_changed, show_in_toolbar_changed, show_in_context_menu_changed;
public string title {
get => _title;
set {
if (_title != value) {
_title = value;
title_changed?.Invoke();
}
}
}
public string title { get; }
public ImageSource icon { get; }
public bool show_in_toolbar {
get => _show_in_toolbar;
set {
if (_show_in_toolbar != value) {
_show_in_toolbar = value;
show_in_toolbar_changed?.Invoke();
}
}
}
public bool show_in_context_menu {
get => _show_in_context_menu;
set {
if (_show_in_context_menu != value) {
_show_in_context_menu = value;
show_in_context_menu_changed?.Invoke();
}
}
}
public abstract void execute(IBus bus);
public virtual bool canExecute() => true;
public virtual void raiseCanExecuteChanged() {
CanExecuteChanged?.Invoke(this, null);
}
public event EventHandler CanExecuteChanged;
public virtual event EventHandler CanExecuteChanged;
public static PartialCommand<T> create<T>(string title, ImageSource icon, ITag<T> tag) =>
new PartialCommand<T>(title, icon, tag);
@@ -53,8 +83,6 @@ namespace bts.spark
public static SparkCommandParamObserver<T> create<T>(string title, ImageSource icon, ITag<T> tag, IObservable<T> parameter, IObservable<bool> can_execute) =>
new SparkCommandParamObserver<T>(title, icon, tag, parameter, can_execute);
}
public static class SparkCommandExtensions {
@@ -174,6 +202,17 @@ namespace bts.spark
public SparkCommandCommand(string title, ImageSource icon, ICommand a) : base(title, icon) {
_a = a;
}
public override event EventHandler CanExecuteChanged {
add {
_a.CanExecuteChanged += value;
base.CanExecuteChanged += value;
}
remove {
_a.CanExecuteChanged -= value;
base.CanExecuteChanged -= value;
}
}
public override void execute(IBus bus) {
_a.Execute(null);
}
@@ -212,7 +251,56 @@ namespace bts.spark
public void Dispose() => Disposable.dispose(ref _subs);
}
class ObservantSparkCommandCommand<T> : SparkCommand, IObserver<T> {
readonly Func<T, string> _fmt_title;
readonly Func<T, bool> _get_can_execute;
readonly Action<T> _execute;
T _parameter;
bool _can_execute;
public ObservantSparkCommandCommand(ImageSource icon, Func<T, string> fmt_title, Func<T, bool> get_can_execute, Action<T> execute, T init_parameter = default)
: base("", icon) {
_fmt_title = fmt_title;
_get_can_execute = get_can_execute;
_execute = execute;
OnNext(init_parameter);
}
public override bool canExecute() => _can_execute;
public override void execute(IBus bus) => _execute(_parameter);
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value) {
_parameter = value;
title = _fmt_title(value);
if (_can_execute != _get_can_execute(value)) {
_can_execute = !_can_execute;
raiseCanExecuteChanged();
}
}
}
class ReactiveSparkCommand : SparkCommand, IDisposable {
readonly Action _execute;
bool _can_execute;
IDisposable _subs;
public ReactiveSparkCommand(IObservable<string> title, ImageSource icon, Action execute, IObservable<bool> can_execute) : base("", icon) {
_execute = execute;
_subs = new System.Reactive.Disposables.CompositeDisposable(title.Subscribe(t => this.title = t),
can_execute.Subscribe(ce => {
if (_can_execute != ce) {
_can_execute = ce;
raiseCanExecuteChanged();
}
}));
}
public override void execute(IBus bus) => _execute();
public override bool canExecute() => _can_execute;
public void Dispose() => Disposable.dispose(ref _subs);
}
public class SparkCommandVM : mbts.ui.shell.ViewModelBase, ICommand {
readonly SparkCommand _cmd;
readonly IBus _bus;
@@ -220,10 +308,15 @@ namespace bts.spark
public SparkCommandVM(SparkCommand cmd, IBus bus) {
_cmd = cmd;
_bus = bus;
cmd.title_changed += () => RaisePropertyChanged(nameof(title));
cmd.show_in_toolbar_changed += () => RaisePropertyChanged(nameof(show_in_toolbar));
cmd.show_in_context_menu_changed += () => RaisePropertyChanged(nameof(show_in_context_menu));
}
public string title => _cmd.title;
public ImageSource icon => _cmd.icon;
public bool show_in_toolbar => _cmd.show_in_toolbar;
public bool show_in_context_menu => _cmd.show_in_context_menu;
public ICommand command => this;
event EventHandler ICommand.CanExecuteChanged { add { _cmd.CanExecuteChanged += value; } remove { _cmd.CanExecuteChanged -= value; } }
@@ -51,6 +51,10 @@ namespace bts.spark
public static SparkCommand PickOrderTicket =>
SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowPickOne, ShowOrderTicketFromSecurity);
// Algo Studio
public static PartialCommand<AlgoStudioWindowFactory.StartupData> ShowAlgoStudio =>
SparkCommand.create(AlgoStudioWindow.NAME, Icons.Tetris, SparkTags.ShowAlgoStudioTag);
// Spreader
public static PartialCommand<SecurityCriteria> ShowSyntheticCreate =>
SparkCommand.create("Create Synthetic", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag);
+1
View File
@@ -66,6 +66,7 @@ namespace mbts.spark
public static ITag<SecurityImmutable> ShowSyntheticStrategyTag { get; } = new SparkTag<SecurityImmutable>(nameof(ShowSyntheticStrategyTag));
public static ITag<Nothing> ShowSyntheticManagementTag { get; } = new SparkTag<Nothing>(nameof(ShowSyntheticManagementTag));
public static ITag<SecurityCriteria> ShowTimeAndSalesTag { get; } = new SparkTag<SecurityCriteria>("Show TimeAndSales");
public static ITag<AlgoStudioWindowFactory.StartupData> ShowAlgoStudioTag { get; } = new SparkTag<AlgoStudioWindowFactory.StartupData>($"Show {AlgoStudioWindow.NAME}");
#endregion
#region Ladder
@@ -1,3 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -5,76 +6,170 @@ using System.Collections.Specialized;
using System.Linq;
namespace mbts.ui.controls {
static class ObservableAggregateCollection {
public static ObservableAggregateCollection<TInner> create<TInner, TOutter>(ObservableCollection<TOutter> source, Func<TOutter, ObservableCollection<TInner>> select_inner) {
var rv = new ObservableAggregateCollection<TInner>();
var aggregator = new Aggregator<TInner>(rv);
foreach (var o in source)
aggregator.add_collection(select_inner(o));
source.CollectionChanged += _mk_outter_collection_changed_handler(aggregator, select_inner);
return rv;
}
public static IDisposable connect<TInner, TOutter>(ObservableCollection<TInner> aggregate, ObservableCollection<TOutter> source, Func<TOutter, ObservableCollection<TInner>> select_inner) {
aggregate.Clear();
var aggregator = new Aggregator<TInner>(aggregate);
foreach (var o in source)
aggregator.add_collection(select_inner(o));
var handler = _mk_outter_collection_changed_handler(aggregator, select_inner);
source.CollectionChanged += handler;
return Disposable.Create(() => source.CollectionChanged -= handler);
}
static NotifyCollectionChangedEventHandler _mk_outter_collection_changed_handler<TInner, TOutter>(Aggregator<TInner> aggregator, Func<TOutter, ObservableCollection<TInner>> select_inner) {
return (s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: add_collections(e.NewStartingIndex, e.NewItems); break;
case NotifyCollectionChangedAction.Remove: remove_collections(e.OldStartingIndex, e.OldItems); break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
remove_collections(e.OldStartingIndex, e.OldItems);
add_collections(e.NewStartingIndex, e.NewItems);
break;
case NotifyCollectionChangedAction.Reset:
aggregator.clear_collections();
foreach (TOutter o in (IEnumerable<TOutter>)s)
aggregator.add_collection(select_inner(o));
break;
}
};
void add_collections(int new_item_index, IList new_items) {
foreach (TOutter o in new_items)
aggregator.insert_collection(new_item_index++, select_inner(o));
}
void remove_collections(int old_item_index, IList old_items) {
foreach (TOutter o in old_items)
aggregator.remove_collection_at(old_item_index);
}
}
internal class Aggregator<T> : IDisposable {
readonly ObservableCollection<T> _target;
readonly List<ObservableCollection<T>> _collections = new List<ObservableCollection<T>>();
bool _is_disposed;
public Aggregator(ObservableCollection<T> target, params ObservableCollection<T>[] collections) {
_target = target;
foreach (var c in collections)
add_collection(c);
}
public void add_collection(ObservableCollection<T> collection) {
_check_disposed();
_target.AddRange(collection);
_collections.Add(collection);
collection.CollectionChanged += _on_collection_changed;
}
public void remove_collection(ObservableCollection<T> collection) {
_check_disposed();
_remove_collection_items(collection, out int _, out int collection_index);
_collections.RemoveAt(collection_index);
collection.CollectionChanged -= _on_collection_changed;
}
public void insert_collection(int index, ObservableCollection<T> collection) {
_check_disposed();
if (index < 0 || index > _collections.Count) throw new ArgumentOutOfRangeException(nameof(index));
if (index == _collections.Count)
add_collection(collection);
else {
_collections.Insert(index, collection);
_on_collection_changed(collection, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection, 0));
collection.CollectionChanged += _on_collection_changed;
}
}
public void remove_collection_at(int index) {
_check_disposed();
remove_collection(_collections[index]);
}
public void clear_collections() {
_check_disposed();
foreach (var c in _collections)
c.CollectionChanged -= _on_collection_changed;
_collections.Clear();
_target.Clear();
}
public void Dispose() {
if (!_is_disposed) {
foreach (var c in _collections)
c.CollectionChanged -= _on_collection_changed;
_is_disposed = true;
}
}
void _on_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
_check_disposed();
int offset = _get_collection_start(sender);
switch (e.Action) {
case NotifyCollectionChangedAction.Add: _target.InsertRange(e.NewStartingIndex + offset, e.NewItems); break;
case NotifyCollectionChangedAction.Remove: _target.RemoveRange(e.OldStartingIndex + offset, e.OldItems.Count); break;
case NotifyCollectionChangedAction.Move: _target.Move(e.OldStartingIndex + offset, e.NewStartingIndex + offset); break;
case NotifyCollectionChangedAction.Replace:
_target.RemoveRange(e.OldStartingIndex + offset, e.OldItems.Count);
_target.InsertRange(e.NewStartingIndex + offset, e.NewItems);
break;
case NotifyCollectionChangedAction.Reset:
var c = (ObservableCollection<T>)sender;
_remove_collection_items(c, out int starting_index, out int _);
_add_items(c, starting_index);
break;
}
}
void _add_items(IList items, int index) {
foreach (T item in items)
_target.Insert(index++, item);
}
void _remove_collection_items(ObservableCollection<T> collection, out int starting_index, out int collection_index) {
int ex_count = 0;
int i = 0;
for (; i < _collections.Count; i++) {
if (_collections[i] == collection)
break;
else ex_count += _collections[i].Count;
}
starting_index = ex_count;
collection_index = i;
for (++i; i < _collections.Count; i++)
ex_count += _collections[i].Count;
_target.RemoveRange(starting_index, _target.Count - ex_count);
}
int _get_collection_start(object sender) =>
_collections.TakeWhile(c => c != sender).Sum(c => c.Count);
void _check_disposed() {
if (_is_disposed)
throw new ObjectDisposedException("ObservableCollectionAggregator");
}
}
}
class ObservableAggregateCollection<T> : ObservableCollection<T> {
readonly List<ObservableCollection<T>> _collections = new List<ObservableCollection<T>>();
ObservableAggregateCollection.Aggregator<T> _aggregator;
public ObservableAggregateCollection(params ObservableCollection<T>[] collections) {
foreach (var c in collections)
add_collection(c);
}
public ObservableAggregateCollection(params ObservableCollection<T>[] collections) =>
_aggregator = new ObservableAggregateCollection.Aggregator<T>(this, collections);
public void add_collection(ObservableCollection<T> collection) {
this.AddRange(collection);
_collections.Add(collection);
collection.CollectionChanged += _on_collection_changed;
}
public void remove_collection(ObservableCollection<T> collection) {
_remove_collection_items(collection, out int _, out int collection_index);
_collections.RemoveAt(collection_index);
collection.CollectionChanged -= _on_collection_changed;
}
public void clear_collections() {
foreach (var c in _collections)
c.CollectionChanged -= _on_collection_changed;
Clear();
}
void _on_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
int offset = _get_collection_start(sender);
switch (e.Action) {
case NotifyCollectionChangedAction.Add: this.InsertRange(e.NewStartingIndex + offset, e.NewItems); break;
case NotifyCollectionChangedAction.Remove: this.RemoveRange(e.OldStartingIndex + offset, e.OldItems.Count); break;
case NotifyCollectionChangedAction.Move: Move(e.OldStartingIndex + offset, e.NewStartingIndex + offset); break;
case NotifyCollectionChangedAction.Replace:
this.RemoveRange(e.OldStartingIndex + offset, e.OldItems.Count);
this.InsertRange(e.NewStartingIndex + offset, e.NewItems);
break;
case NotifyCollectionChangedAction.Reset:
var c = (ObservableCollection<T>)sender;
_remove_collection_items(c, out int starting_index, out int _);
_add_items(c, starting_index);
break;
}
}
void _add_items(IList items, int index) {
foreach (T item in items)
Insert(index++, item);
}
void _remove_items(IList items, int index) {
foreach (var item in items)
RemoveAt(index);
}
void _remove_collection_items(ObservableCollection<T> collection, out int starting_index, out int collection_index) {
int ex_count = 0;
int i = 0;
for (; i < _collections.Count; i++) {
if (_collections[i] == collection)
break;
else ex_count += _collections[i].Count;
}
starting_index = ex_count;
collection_index = i;
for (++i; i < _collections.Count; i++)
ex_count += _collections[i].Count;
this.RemoveRange(starting_index, Count - ex_count);
}
int _get_collection_start(object sender) =>
_collections.TakeWhile(c => c != sender).Sum(c => c.Count);
public void add_collection(ObservableCollection<T> collection) => _aggregator.add_collection(collection);
public void remove_collection(ObservableCollection<T> collection) => _aggregator.remove_collection(collection);
public void insert_collection(int index, ObservableCollection<T> collection) => _aggregator.insert_collection(index, collection);
public void remove_collection_at(int index) => _aggregator.remove_collection_at(index);
public void clear_collections() => _aggregator.clear_collections();
}
}
@@ -35,6 +35,9 @@ namespace mbts.ui.utility
// Note: after we change we can use innser.SyncWith(this.skip/take(prefix_len()))
}
public IReadOnlyList<T> appended_front => _prefix;
public IReadOnlyList<T> appended_back => _suffix;
int prefix { get { return _prefix.Count; } }
int suffix { get { return _suffix.Count; } }
@@ -110,6 +113,15 @@ namespace mbts.ui.utility
base.RemoveAt(e.OldStartingIndex + prefix);
}
break;
case NotifyCollectionChangedAction.Replace: {
// assume that old/new item lists are the same length
var old_en = e.OldItems.GetEnumerator();
var new_en = e.NewItems.GetEnumerator();
int i = e.NewStartingIndex;
while (old_en.MoveNext() && new_en.MoveNext())
SetItem(i, (T)new_en.Current);
}
break;
case NotifyCollectionChangedAction.Reset:
while (Count > prefix + suffix) {
RemoveAt(prefix);
@@ -1,48 +1,316 @@
using System;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using mbts.collections.extensions;
using System.Collections;
using bts.collections;
using bts.utils;
using mbts.utils;
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Disposables;
namespace mbts.ui.utility
{
namespace mbts.ui.utility {
/// <summary>
/// The sole purpose of this class is to offer a less verbose alternative to
/// "new ObservableAutoWrapper<LongTypeName............, AnotherLongTypeName.........>(doodi, poodi)"
/// when the generic types are implicit
/// </summary>
public static class ObservableAutoWrapper
{
static class ObservableAutoWrapper {
public static ObservableAutoWrapper<View, Model> Create<View, Model>(ObservableCollection<Model> models, Func<Model, View> converter) {
return new ObservableAutoWrapper<View, Model>(models, converter);
}
public static IDisposable connect<TCollection, T, TResult>(TCollection source, ObservableCollection<TResult> target, Func<T, TResult> create, Action<T, TResult> on_removed = null)
where TCollection : ICollection<T>, IList, INotifyCollectionChanged {
Action<IList, int> removed_cb = on_removed == null ?
new Action<IList, int>((old_items, i) => target.RemoveAt(i, old_items.Count)) :
new Action<IList, int>((old_items, i) => {
foreach(T item in old_items) {
on_removed(item, target[i]);
target.RemoveAt(i);
}
});
var collection_changed_cb = WPFHelper.create_collection_changed_cb((new_items, i) => {
if (i >= 0 && i < new_items.Count) {
foreach (T item in new_items)
target.Insert(i++, create(item));
} else {
foreach (T item in new_items)
target.Add(create(item));
public static IReadOnlyObservableCollection<T> create_sorted_wrapper<T>(ObservableCollection<T> source, IComparer<T> comparer) =>
new SortedWrapper<T>(source, source, comparer);
public static IDisposable connect_sorted<T>(ObservableCollection<T> source, ObservableCollection<T> target, IComparer<T> comparer) {
target.sync_with(source.Ordered(comparer));
return source.Subscribe(on_source_collection_changed);
// local methods
void on_source_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
foreach (T v in e.NewItems) {
int new_pos = peek_pos(v);
target.Insert(new_pos, v);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (T v in e.OldItems) {
int pos = assert_pos(v);
target.RemoveAt(pos);
}
break;
case NotifyCollectionChangedAction.Move:
// ignore moves - target collection is sorted
break;
case NotifyCollectionChangedAction.Replace:
// if the old/new sorted indices are different, this will be a Remove/re-Add op instead of a Replace op
using (var old_en = e.OldItems.Cast<T>().GetEnumerator())
using (var new_en = e.NewItems.Cast<T>().GetEnumerator()) {
while (old_en.MoveNext()) {
if (!new_en.MoveNext())
throw new InvalidOperationException("e.OldItems and e.NewItems do not have same number of elements in a 'Replace' op, target collection is now out of sync with its source.");
int old_pos = assert_pos(old_en.Current);
int new_pos = peek_pos(new_en.Current);
if (old_pos == new_pos) {
target[new_pos] = new_en.Current;
} else {
target.RemoveAt(old_pos);
target.Insert(new_pos, new_en.Current);
}
}
}
break;
case NotifyCollectionChangedAction.Reset:
target.Clear();
target.sync_with(source.Ordered(comparer));
break;
}
}, removed_cb);
}
int assert_pos(T value) {
int pos = CollectionHelper.binary_search(target, value, comparer);
if (pos < 0)
throw new InvalidOperationException("Failed to remove value, target collection is now out of sync with its source.");
return pos;
}
int peek_pos(T value) {
int pos = CollectionHelper.binary_search(target, value, comparer);
if (pos < 0)
pos = ~pos;
return pos;
}
}
public static IDisposable connect<T, TResult>(ObservableCollection<T> source, ObservableCollection<TResult> target, Func<T, TResult> create, Action<TResult> on_removed = null) =>
connect<ObservableCollection<T>, T, TResult>(source, target, create, null);
public static IDisposable connect<TCollection, T, TResult>(TCollection source, ObservableCollection<TResult> target, Func<T, TResult> create, Action<TResult> on_removed = null)
where TCollection : ICollection<T>, IList, INotifyCollectionChanged {
Action reset_cb;
Action<IList, int> removed_cb,
added_cb = (new_items, i) => {
if (i >= 0 && i < new_items.Count) {
foreach (T item in new_items)
target.Insert(i++, create(item));
} else {
foreach (T item in new_items)
target.Add(create(item));
}
};
if (on_removed == null) {
reset_cb = () => target.SetItems(source.Select(create));
removed_cb = (old_items, i) => {
if (i < 0) {
throw new InvalidOperationException("Source collection invoked a CollectionChanged 'Removed' event without a valid 'OldStartingIndex.'");
} else {
target.RemoveRange(i, old_items.Count);
}
};
} else {
reset_cb = () => {
foreach (var v in target)
on_removed(v);
target.SetItems(source.Select(create));
};
removed_cb = (old_items, i) => {
if (i < 0) {
throw new InvalidOperationException("Source collection invoked a CollectionChanged 'Removed' event without a valid 'OldStartingIndex.'");
} else {
for (int j = 0; j < old_items.Count; j++) {
on_removed(target[i]);
target.RemoveAt(i);
}
}
};
}
var collection_changed_cb = WPFHelper.create_collection_changed_cb(
added_cb,
removed_cb,
on_items_replaced: (old_items, old_i, new_items, new_i) => {
removed_cb(old_items, old_i);
added_cb(new_items, new_i);
},
on_reset: reset_cb);
collection_changed_cb(source, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, source));
return source.Subscribe(collection_changed_cb);
}
public static IDisposable connect<T>(IObservable<ObservableCollection<T>> source, ObservableCollection<T> target) {
IDisposable curr_connection = null;
IDisposable source_sub = source.Subscribe(c => {
Disposable.dispose(ref curr_connection);
curr_connection = connect(c, target);
});
return Disposable.Create(() => {
Disposable.dispose(ref source_sub);
Disposable.dispose(ref curr_connection);
});
}
public static IDisposable connect<T>(ObservableCollection<T> source, ObservableCollection<T> target) {
target.sync_with(source);
return source.Subscribe(source_changed);
void source_changed(object sender, NotifyCollectionChangedEventArgs e) =>
target.ReflectChange(source, _ => _, e);
}
/// <summary>
/// Establishes a 2-way connection between a target collection and a source collection.
/// First, the target is mutated to contain the exact same elements as the source.
/// After that, subsequent changes to either collection are replicated in the other.
/// </summary>
public static IDisposable connect_two_way<T>(IObservable<ObservableCollection<T>> source, ObservableCollection<T> target) {
IDisposable curr_connection = null;
IDisposable source_sub = source.Subscribe(c => {
Disposable.dispose(ref curr_connection);
curr_connection = connect_two_way(c, target);
});
return Disposable.Create(() => {
Disposable.dispose(ref source_sub);
Disposable.dispose(ref curr_connection);
});
}
/// <summary>
/// Establishes a 2-way connection between a target collection and a source collection.
/// First, the target is mutated to contain the exact same elements as the source.
/// After that, subsequent changes to either collection are replicated in the other.
/// </summary>
public static IDisposable connect_two_way<T>(ObservableCollection<T> source, ObservableCollection<T> target) {
target.sync_with(source);
source.CollectionChanged += source_changed;
target.CollectionChanged += target_changed;
return Disposable.Create(() => {
source.CollectionChanged -= source_changed;
target.CollectionChanged -= target_changed;
});
void source_changed(object sender, NotifyCollectionChangedEventArgs e) {
using (target.SuspendHandler(target_changed))
target.ReflectChange(source, _ => _, e);
}
void target_changed(object sender, NotifyCollectionChangedEventArgs e) {
using (source.SuspendHandler(source_changed))
source.ReflectChange(target, _ => _, e);
}
}
public static IDisposable connect_item_hooks<T>(IReadOnlyObservableCollection<T> source, Func<T, IDisposable> get_item_hook) {
var item_hooks = source.Select(get_item_hook).ToList();
return new CompositeDisposable(
Disposable.wrap_collection(item_hooks),
source.Subscribe((s, e) => CollectionHelper.reflect_change(item_hooks, source, get_item_hook, d => d.Dispose(), e)));
}
public static IDisposable connect_item_hooks<T>(ObservableCollection<T> source, Func<T, IDisposable> get_item_hook, bool clear_source_on_dispose = false) {
var item_hooks = source.Select(get_item_hook).ToList();
return new CompositeDisposable(
clear_source_on_dispose ? Disposable.Create(source.Clear) : Disposable.wrap_collection(item_hooks),
source.Subscribe((s, e) => CollectionHelper.reflect_change(item_hooks, source, get_item_hook, d => d.Dispose(), e)));
}
class SortedWrapper<T> : IReadOnlyObservableCollection<T> {
const int _min_capacity = 4;
readonly IComparer<T> _comparer;
T[] _values;
int _size;
readonly INotifyCollectionChanged _src_notifier;
readonly ICollection<T> _src_collection;
public SortedWrapper(INotifyCollectionChanged notifier, ICollection<T> collection, IComparer<T> comparer) {
_src_notifier = notifier;
_src_collection = collection;
_comparer = comparer;
if (collection.Count == 0) {
_values = new T[_min_capacity];
} else {
_values = new T[Math.Max(_min_capacity, collection.Count)];
collection.CopyTo(_values, 0);
Array.Sort(_values, 0, collection.Count, comparer);
}
notifier.CollectionChanged += on_collection_changed;
void on_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
foreach (T v in e.NewItems)
_add_and_notify(v);
break;
case NotifyCollectionChangedAction.Remove:
foreach (T v in e.OldItems)
_remove_and_notify(v);
break;
case NotifyCollectionChangedAction.Move:
// ignore moves - this is a sorted collection.
break;
case NotifyCollectionChangedAction.Replace:
// if the old/new sorted indices are different, this will be a Remove/re-Add op (by definition, can only be a Replace op if they are the same)
using (var old_en = e.OldItems.Cast<T>().GetEnumerator())
using (var new_en = e.NewItems.Cast<T>().GetEnumerator()) {
while (old_en.MoveNext()) {
if (!new_en.MoveNext())
throw new InvalidOperationException("e.OldItems and e.NewItems do not have same number of elements in a 'Replace' op, SortedWrapper is now out of sync with its source.");
int old_pos = _assert_remove(old_en.Current);
int new_pos = _add(new_en.Current);
if (CollectionChanged != null) {
if (old_pos == new_pos) {
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, old_en.Current, new_en.Current, new_pos));
} else {
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, old_en.Current, old_pos));
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new_en.Current, new_pos));
}
}
}
}
break;
case NotifyCollectionChangedAction.Reset:
ArrayHelper.ensure_capacity(ref _values, _src_collection.Count);
if (_size > _src_collection.Count) {
Array.Clear(_values, _src_collection.Count, _size - _src_collection.Count);
}
_src_collection.CopyTo(_values, 0);
_size = _src_collection.Count;
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
break;
}
}
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public T this[int index] => _values[index];
public int Count => _size;
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i < _size; i++)
yield return _values[i];
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
int _assert_remove(T value) {
ArrayHelper.remove_sorted(ref _values, ref _size, value, _comparer, out int? pos);
if (!pos.HasValue)
throw new InvalidOperationException("Failed to remove value, SortedWrapper is now out of sync with its source.");
return pos.Value;
}
void _remove_and_notify(T value) {
int pos = _assert_remove(value);
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, pos));
}
int _add(T value) {
ArrayHelper.add_sorted(ref _values, ref _size, value, _comparer, out int pos);
return pos;
}
void _add_and_notify(T value) {
int pos = _add(value);
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value, pos));
}
}
}
public class ObservableAutoWrapper<View, Model> : ObservableCollection<View>
@@ -149,8 +417,7 @@ namespace mbts.ui.utility
}
}
namespace mbts.ui.utility.test
{
namespace mbts.ui.utility.test {
[TestFixture]
class TestObservableAutoWrapper
@@ -217,4 +484,4 @@ namespace mbts.ui.utility.test
}
}
}
}
@@ -0,0 +1,284 @@
using bts.collections;
using bts.utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace mbts.collections {
interface IReadOnlyObservableKeyedCollection<T, TKey> : ui.utility.IReadOnlyObservableCollection<T>, IReadOnlyDictionary<TKey, T>, INotifyCollectionChanged { }
interface IObservableKeyedCollection<T, TKey> : ui.utility.IObservableCollection<T>, IDictionary<T, TKey> { }
class ObservableKeyedCollection<T, TKey> : ObservableCollection<T>, ui.utility.IObservableCollection<T>, IDictionary<TKey, T>, IReadOnlyObservableKeyedCollection<T, TKey> {
const string _indexer_name = "Item[]";
readonly Func<T, TKey> _key;
readonly Dictionary<TKey, T> _map;
public ObservableKeyedCollection(Func<T, TKey> key)
: this(key, EqualityComparer<TKey>.Default) { }
public ObservableKeyedCollection(Func<T, TKey> key, IEqualityComparer<TKey> key_comparer) {
_key = key;
_map = new Dictionary<TKey, T>(key_comparer);
}
public ICollection<TKey> Keys => _map.Keys;
public ICollection<T> Values => _map.Values;
public bool IsReadOnly => false;
public T this[TKey key] {
get => _map[key];
set {
TKey item_key = _key(value);
if (!key.Equals(item_key))
throw new ArgumentException("Specified key does not match that of specified value.", nameof(value));
if (_map.TryGetValue(key, out T curr)) {
if (ReferenceEquals(value, curr))
return;
int index = Items.IndexOf(curr);
Items[index] = value;
_map[key] = value;
OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, curr, index));
} else {
Items.Add(value);
_map.Add(key, value);
_notify_props_changed();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value, Count - 1));
}
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, T>.Keys => Keys;
IEnumerable<T> IReadOnlyDictionary<TKey, T>.Values => Values;
public IDictionary<TKey, T> AsDictionary() => this;
public ObservableCollection<T> AsCollection() => this;
public bool TryGetValue(TKey key, out T result) =>
_map.TryGetValue(key, out result);
public new bool Add(T item) {
CheckReentrancy();
TKey k = _key(item);
if (_map.ContainsKey(k))
return false;
_map.Add(k, item);
Items.Add(item);
_notify_props_changed();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, Count - 1));
return true;
}
public bool Remove(TKey key) {
if (_map.TryGetValue(key, out T value)) {
int index = Items.IndexOf(value);
if (index < 0) throw new InvalidOperationException("Map out of sync with items.");
_map.Remove(key);
Items.RemoveAt(index);
_notify_props_changed();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, value, index));
return true;
}
return false;
}
public bool Replace(TKey old_key, T new_value) {
if (_map.TryGetValue(old_key, out T old_value)) {
int index = Items.IndexOf(old_value);
if (index < 0) throw new InvalidOperationException("Map out of sync with items.");
_map.Remove(old_key);
_map[_key(new_value)] = new_value;
Items[index] = new_value;
OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, new_value, old_value, index));
return true;
}
return false;
}
public void SyncWithKeys(IEnumerable<TKey> keys, Func<TKey, T> factory) {
var keys_list = new List<TKey>(keys);
var changes = Diff.diff(this.Keys, keys).ToList();
int ch_count = changes.Count;
for (int ch_pos = 0; ch_pos < ch_count; ch_pos++) {
var ch = changes[ch_pos];
for (int i = ch.StartLeft; i < (ch.StartLeft + ch.deletedLeft); i++)
RemoveAt(i);
for (int i = 0; i < ch.insertedRight; i++) {
var k = keys_list[ch.StartRight + i];
var v = factory(k);
int index = ch.StartLeft + i;
Items.Insert(index, v);
_map.Add(k, v);
_notify_props_changed();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, v, index));
}
for (int i = ch_pos + 1; i < ch_count; i++) {
// (f)orward (ch)ange
var fch = changes[i];
if (fch.StartLeft >= ch.StartLeft) {
fch.StartLeft += (fch.insertedRight - fch.deletedLeft);
changes[i] = fch;
}
}
}
}
public void SyncWithDictionary<TModel>(IReadOnlyDictionary<TKey, TModel> dictionary, Func<TModel, T> factory) {
foreach (var k in _map.Keys.Except(dictionary.Keys).ToList())
Remove(k);
foreach (var kv in dictionary) {
if (!ContainsKey(kv.Key))
Add(factory(kv.Value));
}
}
public void SyncWithDictionary<TModel>(IReadOnlyDictionary<TKey, TModel> dictionary, Func<TModel, T> factory, Action<TModel, T> update) {
foreach (var k in _map.Keys.Except(dictionary.Keys).ToList())
Remove(k);
foreach (var kv in dictionary) {
if (TryGetValue(kv.Key, out T curr))
update(kv.Value, curr);
else
Add(factory(kv.Value));
}
}
protected override void ClearItems() {
_map.Clear();
base.ClearItems();
}
protected override void InsertItem(int index, T item) {
CheckReentrancy();
TKey k = _key(item);
if (_map.ContainsKey(k))
throw new InvalidOperationException("[Item]Key already added.");
_map.Add(k, item);
Items.Insert(index, item);
_notify_props_changed();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
protected override void SetItem(int index, T item) {
_remove(index);
base.SetItem(index, item);
_set(item);
}
protected override void RemoveItem(int index) {
_remove(index);
base.RemoveItem(index);
}
void _remove(int index) => _map.Remove(_key(Items[index]));
void _set(T item) => _map[_key(item)] = item;
void _notify_props_changed() {
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name));
}
public bool ContainsKey(TKey key) => _map.ContainsKey(key);
public void Add(TKey key, T value) => this[key] = value;
public void Add(KeyValuePair<TKey, T> item) => this[item.Key] = item.Value;
public bool Contains(KeyValuePair<TKey, T> item) => _map.Contains(item);
public void CopyTo(KeyValuePair<TKey, T>[] array, int arrayIndex) {
int len = Count;
for(int i = 0; i < len; i++) {
T v = Items[i];
array[arrayIndex + i] = new KeyValuePair<TKey, T>(_key(v), v);
}
}
public bool Remove(KeyValuePair<TKey, T> item) => _key(item.Value).Equals(item.Key) ?
Remove(item.Value) : throw new ArgumentException("KeyValuePair.Key does not match KeyValuePair.Value's functional key.");
IEnumerator<KeyValuePair<TKey, T>> IEnumerable<KeyValuePair<TKey, T>>.GetEnumerator() {
/// Don't iterate through <see cref="_map"/>; item-order should match the collection's.
int len = Count;
for (int i = 0; i < len; i++) {
T v = Items[i];
yield return new KeyValuePair<TKey, T>(_key(v), v);
}
}
}
static class ObservableKeyedCollectionExtensions {
public static IReadOnlyObservableKeyedCollection<TResult, TKey> WrapSelector<T, TKey, TResult>(this IReadOnlyObservableKeyedCollection<T, TKey> source, Func<T, TResult> selector) =>
new SelectorWrapper<T, TKey, TResult>(source, selector);
class SelectorWrapper<T, TKey, TResult> : IReadOnlyObservableKeyedCollection<TResult, TKey> {
readonly IReadOnlyObservableKeyedCollection<T, TKey> _src;
readonly IReadOnlyList<T> _src_list;
readonly IReadOnlyDictionary<TKey, T> _src_dictionary;
readonly Func<T, TResult> _selector;
public SelectorWrapper(IReadOnlyObservableKeyedCollection<T, TKey> source, Func<T, TResult> selector) {
_src = source;
_src_list = source;
_src_dictionary = source;
_selector = selector;
_src.CollectionChanged += on_collection_changed;
void on_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
if (CollectionChanged == null)
return;
NotifyCollectionChangedEventArgs wrapped;
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
wrapped = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,
e.NewItems.WrapSelectorHidden(from_obj), e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
wrapped = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
e.OldItems.WrapSelectorHidden(from_obj), e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
wrapped = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace,
e.OldItems.WrapSelectorHidden(from_obj), e.OldItems.WrapSelectorHidden(from_obj), e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Move:
wrapped = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace,
e.OldItems.WrapSelectorHidden(from_obj), e.OldItems.WrapSelectorHidden(from_obj), e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Reset:
wrapped = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
break;
default: throw new InvalidOperationException($"Unexpected {nameof(NotifyCollectionChangedAction)} '{e.Action}.'");
}
CollectionChanged(this, wrapped);
}
TResult from_obj(object obj) => selector(ConvertUtils.try_convert<T>(obj));
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public TResult this[int index] => _selector(_src_list[index]);
public TResult this[TKey key] => _selector(_src_dictionary[key]);
public int Count => _src_list.Count;
public IEnumerable<TKey> Keys => _src.Keys;
public IEnumerable<TResult> Values => _src.Values.Select(_selector);
public bool ContainsKey(TKey key) => _src.ContainsKey(key);
public IEnumerator<TResult> GetEnumerator() {
foreach (var v in _src_list)
yield return _selector(v);
}
public bool TryGetValue(TKey key, out TResult value) {
if (_src.TryGetValue(key, out T sv)) {
value = _selector(sv);
return true;
}
value = default;
return false;
}
IEnumerator<KeyValuePair<TKey, TResult>> IEnumerable<KeyValuePair<TKey, TResult>>.GetEnumerator() {
foreach (var kv in _src_dictionary)
yield return new KeyValuePair<TKey, TResult>(kv.Key, _selector(kv.Value));
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}
+11 -1
View File
@@ -115,7 +115,17 @@ namespace mbts.collections {
}
}
static class SetMapExtensions {
static class SetMap {
public static SetMap<TKey, TValue> create<TKey, TElement, TValue>(IEnumerable<TElement> source, Func<TElement, TKey> key_selector, Func<TElement, TValue> value_selector) =>
create(source, key_selector, value_selector, EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default);
public static SetMap<TKey, TValue> create<TKey, TElement, TValue>(IEnumerable<TElement> source, Func<TElement, TKey> key_selector, Func<TElement, TValue> value_selector, IEqualityComparer<TKey> key_comparer, IEqualityComparer<TValue> value_comparer) {
var sm = new SetMap<TKey, TValue>();
foreach (var el in source)
sm.add(key_selector(el), value_selector(el));
return sm;
}
public static bool removes_key<TKey, TElement>(this SetMap<TKey, TElement> set_map, TKey key, TElement element) {
int count_before = set_map.Count;
if (set_map.remove(key, element))
@@ -1,4 +1,5 @@
using System;
using System.Reactive;
using System.Windows.Input;
namespace mbts.ui {
@@ -31,5 +32,35 @@ namespace mbts.ui {
class ObservantCommand : ObservantCommand<object> {
public ObservantCommand(Action execute) : base(_ => execute()) { }
public ObservantCommand(Action<object> execute) : base(execute) { }
public static ICommand create<T>(Action<T> execute, Func<T, bool> get_can_execute, out IObserver<T> observer) {
T param = default;
bool can_execute = false;
var cmd = new DelegateCommand(() => execute(param), () => can_execute);
observer = new AnonymousObserver<T>(p => {
param = p;
if (can_execute != get_can_execute(param))
cmd.RaiseCanExecuteChanged();
});
return cmd;
}
public static ICommand create<T>(Action<T> execute, Func<T, IObservable<bool>> get_can_execute_source, out IObserver<T> observer) {
T param = default;
bool can_execute = false;
var cmd = new DelegateCommand(() => execute(param), () => can_execute);
IDisposable can_execute_sub = null;
observer = new AnonymousObserver<T>(p => {
param = p;
Disposable.dispose(ref can_execute_sub);
can_execute_sub = get_can_execute_source(p).Subscribe(ce => {
if (can_execute != ce) {
can_execute = ce;
cmd.RaiseCanExecuteChanged();
}
});
}, () => Disposable.dispose(ref can_execute_sub));
return cmd;
}
}
}
@@ -0,0 +1,8 @@
using System;
namespace mbts.ui {
static class WPFExceptionBuilder {
public static InvalidOperationException style_target_type(Type expected, Type actual) =>
new InvalidOperationException($"Expected Style.TargetType to be {expected}, actually {actual}.");
}
}
@@ -0,0 +1,14 @@
using System;
using System.Windows;
namespace mbts.ui {
static class WPFExceptionHelper {
public static void assert_style_target_type(Style style, Type expected, bool allow_null = false) {
if (style == null) {
if (!allow_null)
throw new ArgumentException(nameof(style));
} else if (style.TargetType != expected)
throw WPFExceptionBuilder.style_target_type(expected, style.TargetType);
}
}
}
@@ -217,7 +217,8 @@ namespace mbts.ui {
public static BTSColor off_order { get { return new BTSColor(0x8a, 0x00, 0x5f); } }//8a005f
public static BTSColor top_order { get { return new BTSColor(0xdd, 0x7a, 0x27); } }//dd7a27
public static BTSColor spreader_order { get { return new BTSColor(0xff, 0xff, 0x80); } } //ffff80
}
public static BTSColor default_order => new BTSColor(0x72, 0x9c, 0xcd);
}
public static class AW2 {
public static BTSColor collapsed { get { return BTSCoreColors.blue_light_dark; } }
@@ -663,7 +664,7 @@ namespace mbts.ui {
public static Brush logo_gray_brush { get { return new SolidColorBrush(logo_gray); } }
public static Color common_background => UI.default_background;
public static Brush common_background_brush { get; } = common_background.to_brush().frozen();
public static Brush common_background_brush { get; } = common_background.to_solid_brush().frozen();
public static Color accent1 { get { return UI.accent_light; } }
public static Brush accent1_brush { get { return new SolidColorBrush(accent1); } }
@@ -94,7 +94,15 @@ namespace System.Collections.Generic {
return default_rv;
}
public static TResult FirstOrDefault<T, TResult>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T, TResult> select) {
public static T FirstOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T> default_rv) {
if (source == null) throw new ArgumentNullException(nameof(source));
foreach (T element in source)
if (predicate(element))
return element;
return default_rv();
}
public static TResult SelectFirstOrDefault<T, TResult>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T, TResult> select) {
if (source == null) throw new ArgumentNullException(nameof(source));
foreach (T element in source)
if (predicate(element))
@@ -110,6 +118,16 @@ namespace System.Collections.Generic {
return default_rv;
}
public static T FirstOrDefault<T>(this IEnumerable<T> source, params Func<T, bool>[] predicates_ordered_by_preference) {
foreach (var p in predicates_ordered_by_preference) {
foreach (var el in source) {
if (p(el))
return el;
}
}
return default;
}
public static T LastOrDefault<T>(this IEnumerable<T> source, T default_rv) {
if (source == null) throw new ArgumentNullException(nameof(source));
var list = source as IList<T>;
@@ -185,6 +203,20 @@ namespace System.Collections.Generic {
public static Dictionary<TKey, T> ToDictionary<T, TKey>(this IEnumerable<KeyValuePair<TKey, T>> key_values) =>
key_values.ToDictionary(kv => kv.Key, kv => kv.Value);
public static Dictionary<TKey, T> ToDictionaryCrushed<T, TKey>(this IEnumerable<T> source, Func<T, TKey> key_selector) {
var rv = new Dictionary<TKey, T>();
foreach (T v in source)
rv[key_selector(v)] = v;
return rv;
}
public static Dictionary<TKey, TElement> ToDictionaryCrushed<T, TKey, TElement>(this IEnumerable<T> source, Func<T, TKey> key_selector, Func<T, TElement> element_selector) {
var rv = new Dictionary<TKey, TElement>();
foreach (T v in source)
rv[key_selector(v)] = element_selector(v);
return rv;
}
public static ReadOnlyDictionary<TKey, T> ToReadOnlyDictionary<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> key_selector) =>
new ReadOnlyDictionary<TKey, T>(enumerable.ToDictionary(key_selector));
@@ -535,6 +567,8 @@ namespace System.Collections.ObjectModel
}
}
public static IList<T> AsList<T>(this ObservableCollection<T> collection) => collection;
public static IObservable<IReadOnlyList<T>> ObserveSelf<T>(this ObservableCollection<T> collection) =>
Observable.FromEvent<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(cb => (s, e) => cb(e), h => collection.CollectionChanged += h, h => collection.CollectionChanged -= h).Select(_ => collection);
@@ -16,6 +16,7 @@ using System.Collections.Specialized;
using mbts.spark;
using bts.api;
using bts;
using bts.utils;
namespace mbts
{
@@ -316,6 +317,35 @@ namespace System.Reactive.Linq
public static async Task<(TResult result, bool success)> FirstAsyncTask<T, TResult>(this IObservable<T> source, Func<T, bool> predicate, Func<T, TResult> selector, TimeSpan timeout) where T : class =>
await source.Where(predicate).Select(val => (selector(val), true)).Merge(Observable.Return((default(TResult), false)).Delay(timeout)).FirstAsync();
public static IObservable<T> StartWith<T>(this IObservable<T> source, Func<T> get_value) =>
Observable.Create<T>(o => {
o.OnNext(get_value());
return source.Subscribe(o);
});
public static IObservable<T> StartWith<T>(this IObservable<T> source, Func<T> get_value, Func<bool> can_get_value) =>
Observable.Create<T>(o => {
if (can_get_value())
o.OnNext(get_value());
return source.Subscribe(o);
});
public static IDisposable SubscribeHookLatest<T>(this IObservable<T> source, Func<T, IDisposable> get_hook) {
IDisposable latest_hook = null;
return new Disposables.CompositeDisposable(
source.Subscribe(v => Disposable.replace(ref latest_hook, get_hook(v)))) {
() => Disposable.dispose(ref latest_hook)
};
}
public static IObservable<T> FromEvent<T>(Action<Action> add_handler, Action<Action> remove_handler, Func<T> selector) =>
Observable.Create<T>(o => {
callback();
add_handler(callback);
return Disposable.Create(() => remove_handler(callback));
void callback() => o.OnNext(selector());
});
// This is placed here to intentionally make ObserveOnDispatcher ambiguous with the one provided by Rx
public static IObservable<T> ObserveOnDispatcher<T>(this IObservable<T> source) {
throw new InvalidOperationException("This method can starve the UI of input messages. Please use OnDispatcher() instead");
@@ -324,5 +354,47 @@ namespace System.Reactive.Linq
public static IObservable<T> OnDispatcher<T>(this IObservable<T> source) {
return DispatcherObservable.ObserveOnDispatcher(source, DispatcherPriority.Background);
}
public static IDisposable Subscribe<T>(this IObservable<T> source, params IObserver<T>[] observers) =>
source.Subscribe(new CompositeObserver<T>(observers));
public static IObservable<T> RefCountReplay<T>(this IObservable<T> source, int buffer_size) {
if (buffer_size < 0) throw new ArgumentException("Buffer size is less than zero.", nameof(buffer_size));
if (buffer_size == 0) return source.Publish().RefCount();
int num_subscribers = 0;
ReplaySubject<T> replay = new ReplaySubject<T>(buffer_size);
IDisposable source_sub = null;
return Observable.Create<T>(o => {
if (Interlocked.Increment(ref num_subscribers) == 1)
source_sub = source.Subscribe(replay.OnNext);
IDisposable sub = replay.Subscribe(o);
return Disposable.Create(() => {
sub.Dispose();
if (Interlocked.Decrement(ref num_subscribers) == 0)
source_sub.Dispose();
});
});
}
/// <summary>
/// A less verbose way to call <see cref="Observable.FromEvent{Action{TEventArgs}, TEventArgs}(Action{Action{TEventArgs}}, Action{Action{TEventArgs}})"/>.
/// </summary>
public static IObservable<T> FromAction<T>(Action<T> event_source) =>
Observable.FromEvent<Action<T>, T>(cb => event_source += cb, cb => event_source -= cb);
/// <summary>
/// An inner subscription is made for each value in the source sequence using the specified delegate (<paramref name="subscribe_value"/>).
/// When a new value arrives, the subscription for the previous value is disposed before <paramref name="subscribe_value"/> is invoked with the new value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="subscribe_value"></param>
/// <returns></returns>
public static IDisposable SubscribeEach<T>(this IObservable<T> source, Func<T, IDisposable> subscribe_value) {
IDisposable value_sub = null;
return new Disposables.CompositeDisposable(source.Subscribe(val => Disposable.replace(ref value_sub, subscribe_value(val)))) {
() => Disposable.dispose(ref value_sub)
};
}
}
}
@@ -81,6 +81,24 @@ namespace System.Reflection
});
}
public static Delegate create_property_getter(object obj, string property) =>
create_property_getter(obj, obj.GetType().GetProperty(property) ?? throw new ArgumentException(nameof(property)));
public static Delegate create_property_getter(object obj, PropertyInfo prop_info) =>
prop_info.GetGetMethod()?
.CreateDelegate(
typeof(Func<>).MakeGenericType(prop_info.PropertyType),
obj ?? throw new ArgumentNullException(nameof(obj))
) ?? throw new ArgumentException($"Property '{prop_info.Name}' (from '{prop_info.DeclaringType}') is readonly, or does not have public getter.", nameof(prop_info));
public static Func<T> create_property_getter<T>(object obj, string property) {
var prop_info = (obj ?? throw new ArgumentNullException(nameof(obj))).GetType().GetProperty(property) ?? throw new ArgumentException(nameof(property));
if (!typeof(T).IsAssignableFrom(prop_info.PropertyType))
throw new ArgumentException($"Property type of '{property}' ({prop_info.PropertyType}) is not assignable to 'T' ({typeof(T)}).", nameof(property));
return (Func<T>)prop_info.GetGetMethod()?.CreateDelegate(typeof(Func<T>), obj) ??
throw new ArgumentException($"Property '{property}' (from '{typeof(T)}') is readonly, or does not have public getter.", nameof(property));
}
private static class MyExceptions
{
public static ArgumentException not_generic_type_definition(Type t) { return new ArgumentException("{0} does not represent a generic type definition.".fmt(t.FullName)); }
@@ -4,6 +4,9 @@ using ProtoBuf;
using System;
namespace mbts.spark {
interface IDefaultableSettings {
bool use_defaults { get; set; }
}
/// <summary>
/// The settings Mothership. All window - and any other future user based - settings should have a corresponding default member here.
/// </summary>
@@ -1,4 +1,5 @@
using mbts.spark;
using bts;
using mbts.spark;
using System;
using System.ComponentModel.Composition;
using System.Reactive.Linq;
@@ -24,7 +25,13 @@ namespace mbts.persist {
_persist = persist;
init();
async void init() {
var s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
UserSettings s;
try {
s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
} catch(Exception ex) {
Log.Persist.warn($"Error loading {typeof(UserSettings)} from namespace '{NAME_SPACE}', will restore factory defaults and continue as usual: {ex}");
await save_default(s = UserSettings.factory_defaults);
}
if (s != null)
_set_and_notify(s);
}
@@ -43,7 +50,11 @@ namespace mbts.persist {
public async Task save_default(UserSettings value) {
_set_and_notify(value);
await _persist.set(NAME_SPACE, DEFAULT_KEY, value);
try {
await _persist.set(NAME_SPACE, DEFAULT_KEY, value);
} catch(Exception ex) {
Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}");
}
}
void _set_and_notify(UserSettings value) {
@@ -104,6 +104,25 @@ namespace mbts.persist {
).Where(v => v != null)
.DistinctUntilChanged();
public static IObservable<T> subscribe_current<T>(this IWindowSettingsManager<T> wsm, Func<(T defaults, T instance), T> merge_settings) where T : class, IDefaultableSettings {
return Observable.Create<T>(o => {
IDisposable defaults_sub = wsm.subscribe_default().Subscribe(_ => o.OnNext(get_current()));
wsm.instance_settings_changed += on_instance_settings_changed;
return Disposable.Create(() => {
defaults_sub.Dispose();
wsm.instance_settings_changed -= on_instance_settings_changed;
});
void on_instance_settings_changed(T _) =>
o.OnNext(get_current());
});
T get_current() {
var inst = wsm.instance_settings;
if (inst == null) return wsm.default_settings;
if (inst.use_defaults) return merge_settings((wsm.default_settings, inst));
return inst;
}
}
public static T current_settings<T>(this IWindowSettingsManager<T> wsm) where T : class =>
wsm.instance_settings ?? wsm.default_settings;
}
@@ -1,10 +1,80 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
namespace mbts.utils {
static class CollectionHelper {
public static int binary_search<T>(IList<T> items, T value, IComparer<T> comparer) =>
binary_search(items, value, 0, items.Count, comparer);
public static int binary_search<T>(IList<T> items, T value, int index, int length, IComparer<T> comparer) {
if (comparer == null) comparer = Comparer<T>.Default;
int lo = index;
int hi = index + length - 1;
while (lo <= hi) {
int i = lo + ((hi - lo) >> 1);
int c = comparer.Compare(items[i], value);
if (c == 0) return i;
if (c < 0) {
lo = i + 1;
} else {
hi = i - 1;
}
}
return ~lo;
}
public static void reflect_change<T, TData>(IList<T> target, IEnumerable<TData> source, Func<TData, T> create_item, Action<T> on_removed, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
int i = e.NewStartingIndex;
foreach (TData d in e.NewItems) {
T item = create_item(d);
target.Insert(i++, item);
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex > e.NewStartingIndex) {
i = e.OldStartingIndex;
foreach (TData d in e.OldItems) {
var v = target[i];
target.RemoveAt(i++);
target.Insert(e.NewStartingIndex, v);
}
} else {
foreach (TData d in e.OldItems) {
var v = target[e.OldStartingIndex];
target.RemoveAt(e.OldStartingIndex);
target.Insert(e.NewStartingIndex, v);
}
}
break;
case NotifyCollectionChangedAction.Remove:
for (int x = 0; x < e.OldItems.Count; x++) {
T item = target[e.OldStartingIndex];
target.RemoveAt(e.OldStartingIndex);
on_removed?.Invoke(item);
}
break;
case NotifyCollectionChangedAction.Replace:
i = e.NewStartingIndex;
foreach (TData d in e.NewItems) {
T old_item = target[i];
target[i++] = create_item(d);
on_removed?.Invoke(old_item);
}
break;
case NotifyCollectionChangedAction.Reset:
var old_views = target.ToArray();
target.Clear();
if (on_removed != null) foreach (T item in old_views) on_removed(item);
foreach (TData d in source) target.Add(create_item(d));
break;
}
}
// Note: this is not optimized, be wary of use with large collections
public static void sync_with_never_duplicate<T>(ObservableCollection<T> dest, IEnumerable<T> src) =>
sync_with_never_duplicate(dest, src, EqualityComparer<T>.Default);
@@ -52,5 +122,13 @@ namespace mbts.utils {
rv[i] = selector(source[i]);
return rv;
}
public static IDisposable dispose_on_removed<T>(ObservableCollection<T> collection) =>
collection.Subscribe((s, e) => {
if (e.OldItems != null) {
foreach (T item in e.OldItems)
(item as IDisposable)?.Dispose();
}
});
}
}
@@ -0,0 +1,9 @@
using System;
using System.Reactive.Disposables;
namespace mbts.utils {
static class CompositeDisposableExtensions {
public static void Add(this CompositeDisposable composite_disposable, Action dispose_action) =>
composite_disposable.Add(Disposable.Create(dispose_action));
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reactive;
namespace mbts.utils {
class CompositeObserver<T> : IObserver<T>, IEnumerable<IObserver<T>> {
readonly List<IObserver<T>> _observers;
public CompositeObserver(params IObserver<T>[] observers) =>
_observers = new List<IObserver<T>>(observers);
public void Add(IObserver<T> observer) =>
_observers.Add(observer);
public void OnCompleted() {
foreach (var o in _observers)
o.OnCompleted();
}
public void OnError(Exception error) {
foreach (var o in _observers)
o.OnError(error);
}
public void OnNext(T value) {
foreach (var o in _observers)
o.OnNext(value);
}
public IEnumerator<IObserver<T>> GetEnumerator() => _observers.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _observers.GetEnumerator();
}
static class CompositeObserverExtensions {
public static void Add<T>(this CompositeObserver<T> composite_observer, Action<T> on_next) =>
composite_observer.Add(new AnonymousObserver<T>(on_next));
}
}
@@ -0,0 +1,44 @@
using System;
namespace mbts.utils {
class DeferrableActionWrapper {
readonly Action _action;
bool _is_execution_pending;
int _deferment_count;
public DeferrableActionWrapper(Action action) =>
_action = action ?? throw new ArgumentNullException(nameof(action));
public bool is_execution_deferred => _deferment_count > 0;
public void cancel_pending_execution() {
_is_execution_pending = false;
_deferment_count = 0;
}
public void execute() {
if (is_execution_deferred) {
_is_execution_pending = true;
} else {
_is_execution_pending = false;
_action();
}
}
public IDisposable supress_execution() {
_deferment_count++;
return Disposable.Create(() => _deferment_count--);
}
public IDisposable defer_execution() {
_deferment_count++;
return Disposable.Create(() => {
_deferment_count--;
if (_is_execution_pending && !is_execution_deferred) {
_is_execution_pending = false;
_action();
}
});
}
}
}
@@ -0,0 +1,4 @@
namespace mbts.utils {
delegate bool TryGetValue<T>(out T value);
delegate bool TryGetValue<TKey, TValue>(TKey key, out TValue value);
}
@@ -90,6 +90,11 @@ namespace System.Windows.Threading
#endregion
public static async Task CheckInvokeAsync(this Dispatcher d, Action action) {
if (d.CheckAccess()) action();
else await d.InvokeAsync(action);
}
public static void PushFrame(this Task t) {
DispatcherFrame frame = new DispatcherFrame();
t.ContinueWith(_ => frame.Continue = true);
+134
View File
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
namespace mbts.utils {
class EditStack<T> {
readonly IEqualityComparer<T> _comparer;
readonly List<T> _log = new List<T>();
public EditStack()
: this(EqualityComparer<T>.Default) { }
public EditStack(IEqualityComparer<T> comparer) =>
_comparer = comparer;
public int size => _log.Count;
/// This value represents the index where the next 'pushed' item will go (<see cref="push(T)"/>).
public int pos { get; private set; }
public bool can_undo => pos > 0;
public bool can_redo => pos < _log.Count;
#region Push
public void push(T value) {
int dead_branch_sz = _log.Count - pos - 1;
if (dead_branch_sz < 0)
_log.Add(value);
else {
_log[pos] = value;
if (dead_branch_sz > 0)
_log.RemoveRange(pos + 1, dead_branch_sz);
}
pos++;
}
public bool push_distinct(T value) {
if (pos == 0 || !_comparer.Equals(value, _log[pos - 1])) {
push(value);
return true;
} else return false;
}
#endregion
#region Redo
public bool get_can_redo(T current) => try_peek_redo(current, out T _);
public T redo() =>
can_redo ? _log[pos++] : throw new InvalidOperationException("Already at end of stack.");
public bool try_redo(out T result) {
if (can_redo) {
result = redo();
return true;
}
result = default;
return false;
}
public bool try_peek_redo(T current, out T result) {
int p = pos;
while (p < _log.Count) {
if (!Equals(_log[p], current)) {
result = _log[p];
return true;
}
p++;
}
result = default;
return false;
}
public bool try_peek_redo(out T result) {
if (can_redo) {
result = _log[pos];
return true;
} else {
result = default;
return false;
}
}
#endregion
#region Undo
public bool get_can_undo(T current) => try_peek_undo(current, out T _);
public T undo() =>
try_undo(_log[pos - 1], out T result) ? result : default;
public bool try_undo(T current, out T result) {
int p = pos - 1;
while (p >= 0) {
if (!_comparer.Equals(current, _log[p])) {
result = _log[p];
pos = p + 1;
return true;
}
p--;
}
result = current;
return false;
}
public bool try_undo(out T result) {
if (can_undo)
return try_undo(_log[pos - 1], out result);
result = default;
return false;
}
public bool try_peek_undo(T current, out T result) {
int p = pos - 1;
while (p >= 0) {
if (!Equals(_log[p], current)) {
result = _log[p];
return true;
}
p--;
}
result = default;
return false;
}
#endregion
public void clear() {
_log.Clear();
pos = 0;
}
}
static class EditStackExtensions {
public static void reset<T>(this EditStack<T> edit_stack, T origin_state) {
edit_stack.clear();
edit_stack.push(origin_state);
}
}
}
@@ -69,6 +69,12 @@ namespace mbts.spark {
return rv;
}
public static TMutable created_assigned<TMutable, TImmutable>(this IPropertyWrapperVM<TMutable, TImmutable> vm) where TMutable : new() {
var mval = new TMutable();
vm.assign_to(mval);
return mval;
}
public static TVM init_vm<T, TVM>(T value) where TVM : IPropertyWrapperVM<T>, new() {
var vm = new TVM();
vm.load_from(value);
@@ -0,0 +1,24 @@
namespace mbts.utils {
interface IUndoRedo {
bool can_undo { get; }
bool can_redo { get; }
void undo();
void redo();
}
static class UndoRedoExtensions {
public static bool try_undo(this IUndoRedo undo_redo) {
if (undo_redo.can_undo) {
undo_redo.undo();
return true;
} else return false;
}
public static bool try_redo(this IUndoRedo undo_redo) {
if (undo_redo.can_redo) {
undo_redo.redo();
return true;
} else return false;
}
}
}
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff. Show more