diff --git a/.vscode/launch.json b/.vscode/launch.json
index 40bb8992a..0eaae7c1f 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -42,7 +42,18 @@
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
- },
+ },
+ {
+ "name": "Excel Launch",
+ "type": "clr",
+ "request": "launch",
+ "program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE",
+ "args": ["${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64.xll"],
+ "cwd": "${workspaceRoot}",
+ "stopAtEntry": false,
+ "externalConsole": true,
+ "requireExactSource": false
+ },
{
"name": "Client Tests",
"type": "clr",
@@ -54,7 +65,7 @@
"externalConsole": true,
"requireExactSource": false
},
- {
+ {
"name": "Client Attach",
"type": "clr",
"request": "attach",
@@ -198,7 +209,8 @@
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
- "args": ["test","Co2RelayTests"],
+ // "args": ["test","Co2RelayTests"],
+ "args": ["md", "run", "10"],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
"environment": [],
@@ -264,63 +276,5 @@
"RedirectOutput"
]
},
- {
- "name": "edge-asp051",
- "type": "cppdbg",
- "request": "launch",
- "program": "/home/bts/spark/sparkd",
- "args": ["run"],
- "stopAtEntry": false,
- "cwd": "/home/bts/spark/",
- "environment": [],
- "externalConsole": true,
- "MIMode": "gdb",
- "preLaunchTask": "",
- "setupCommands": [
- {
- "description": "Enable pretty-printing for gdb",
- "text": "enable pretty-printer",
- "ignoreFailures": true
- }
- ],
- "pipeTransport": {
- "pipeCwd": "${workspaceRoot}",
- "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
- "pipeArgs": ["bts@edge-asp051"],
- "debuggerPath": "/usr/bin/gdb"
- },
- "sourceFileMap": {
- "/bts/": "${workspaceRoot}"
- }
- },
- {
- "name": "Docker Launch",
- "type": "cppdbg",
- "request": "launch",
- "program": "/bts/build/gcc_debug/src/server/sparkd/sparkd",
- "args": ["test"],
- "stopAtEntry": false,
- "cwd": "/bts/build/gcc_debug/src/server/sparkd",
- "environment": [],
- "externalConsole": true,
- "MIMode": "gdb",
- "preLaunchTask": "",
- "setupCommands": [
- {
- "description": "Enable pretty-printing for gdb",
- "text": "enable pretty-printer",
- "ignoreFailures": true
- }
- ],
- "pipeTransport": {
- "pipeCwd": "${workspaceRoot}",
- "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
- "pipeArgs": ["-p 2000","root@localhost"],
- "debuggerPath": "/usr/bin/gdb"
- },
- "sourceFileMap": {
- "/bts/": "${workspaceRoot}"
- }
- }
]
}
\ No newline at end of file
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8c2059dc4..534050f90 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -55,6 +55,8 @@ else ()
COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/web ${CMAKE_BINARY_DIR}/server
COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/data_files ${CMAKE_BINARY_DIR}/server
COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/src/lib/libspark.so ${CMAKE_BINARY_DIR}/server
+ COMMAND mkdir ARGS -p ${CMAKE_BINARY_DIR}/server/plugins
+ COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/sdk/examples/order_plugin_example.so ${CMAKE_BINARY_DIR}/server/plugins/
COMMENT "Creating server runtime layout"
DEPENDS sparkd data_files_dir)
diff --git a/doc/user/CMakeDeps.cmake b/doc/user/CMakeDeps.cmake
new file mode 100644
index 000000000..00bd7e37b
--- /dev/null
+++ b/doc/user/CMakeDeps.cmake
@@ -0,0 +1 @@
+set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;/home/ppinto/Dropbox/bts/spark/doc/user/mkdocs.yml;bts-help-theme/404.html;bts-help-theme/base.html;bts-help-theme/content.html;bts-help-theme/css/base.css;bts-help-theme/css/bts.css;bts-help-theme/css/font-awesome.min.css;bts-help-theme/css/highlight.css;bts-help-theme/css/local.css;bts-help-theme/fonts/fontawesome-webfont.eot;bts-help-theme/fonts/glyphicons-halflings-regular.eot;bts-help-theme/img/favicon.ico;bts-help-theme/js/base.js;bts-help-theme/js/bootstrap-3.0.3.min.js;bts-help-theme/js/highlight.pack.js;bts-help-theme/js/jquery-1.10.2.min.js;bts-help-theme/keyboard-modal.html;bts-help-theme/main.html;bts-help-theme/nav-sub.html;bts-help-theme/nav.html;bts-help-theme/search-modal.html;bts-help-theme/toc.html;docs/Help.md;docs/Launcher.md;docs/Logging-In-to-the-System.md;docs/Market.md;docs/My-Windows.md;docs/Settings.md;docs/Spreader.md;docs/Trading.md;docs/images/image1.png;docs/images/image10.png;docs/images/image11.png;docs/images/image12.png;docs/images/image13.png;docs/images/image14.png;docs/images/image15.png;docs/images/image16.png;docs/images/image17.png;docs/images/image18.png;docs/images/image19.png;docs/images/image2.png;docs/images/image20.png;docs/images/image21.png;docs/images/image22.png;docs/images/image23.png;docs/images/image24.png;docs/images/image25.png;docs/images/image26.png;docs/images/image27.png;docs/images/image28.png;docs/images/image29.png;docs/images/image3.png;docs/images/image30.png;docs/images/image31.png;docs/images/image32.png;docs/images/image33.png;docs/images/image34.png;docs/images/image35.png;docs/images/image36.png;docs/images/image37.png;docs/images/image38.png;docs/images/image39.png;docs/images/image4.png;docs/images/image40.png;docs/images/image41.png;docs/images/image42.png;docs/images/image43.png;docs/images/image44.png;docs/images/image45.png;docs/images/image46.png;docs/images/image47.png;docs/images/image48.png;docs/images/image49.png;docs/images/image5.png;docs/images/image50.png;docs/images/image51.png;docs/images/image52.png;docs/images/image53.png;docs/images/image54.png;docs/images/image55.png;docs/images/image56.png;docs/images/image57.png;docs/images/image58.png;docs/images/image59.png;docs/images/image6.png;docs/images/image60.png;docs/images/image61.png;docs/images/image62.png;docs/images/image63.png;docs/images/image64.png;docs/images/image65.png;docs/images/image66.png;docs/images/image67.png;docs/images/image68.png;docs/images/image69.png;docs/images/image7.png;docs/images/image70.png;docs/images/image71.png;docs/images/image72.png;docs/images/image73.png;docs/images/image74.png;docs/images/image76.png;docs/images/image8.png;docs/images/image9.png;docs/index.md;docs/release_notes.md)
\ No newline at end of file
diff --git a/doc/user/CMakeLists.txt b/doc/user/CMakeLists.txt
index 1dfa4d6c5..60f50698f 100644
--- a/doc/user/CMakeLists.txt
+++ b/doc/user/CMakeLists.txt
@@ -16,6 +16,7 @@ set(DOC_GLOBS
favicon.ico
)
file (GLOB_RECURSE All_Deps RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${DOC_GLOBS})
+set (All_Deps ${All_Deps} ${CMAKE_CURRENT_SOURCE_DIR}/build.sh ${CMAKE_CURRENT_SOURCE_DIR}/mkdocs.yml)
update_deps_file("${All_Deps}")
# END DEPENDENCIES
diff --git a/doc/user/bts-help-theme/base.html b/doc/user/bts-help-theme/base.html
index 3f2e7e8b5..a4e965291 100644
--- a/doc/user/bts-help-theme/base.html
+++ b/doc/user/bts-help-theme/base.html
@@ -26,7 +26,6 @@
-
- Child
+
+ Child
+
+
- Top Thresh
+
+ Top Thresh
+
+
-
- Child
+
+ Child
+
+
+
- Hedge Ticks
+
+ Hedge Ticks
+
+
- Hedge
+
+ Hedge
+
+
- Child
+
+ Child
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Tick Offset
+
+ Child
+
+
+
+
@@ -431,7 +526,7 @@
Price
-
+
@@ -595,19 +690,88 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Child
-
+
@@ -86,8 +86,8 @@
-
-
+
+
@@ -95,15 +95,15 @@
-
+
/
-
+
/
-
+
diff --git a/src/client/spark/view/Controls/Time/DateTimePicker.xaml.cs b/src/client/spark/view/Controls/Time/DateTimePicker.xaml.cs
index fcdcb8e9d..77165f730 100644
--- a/src/client/spark/view/Controls/Time/DateTimePicker.xaml.cs
+++ b/src/client/spark/view/Controls/Time/DateTimePicker.xaml.cs
@@ -18,6 +18,11 @@ namespace mbts.ui.controls {
public static readonly RoutedCommand TickTimeComponentCommand = new RoutedCommand();
DTPController _controller;
+ TextBox
+ _month_text,
+ _day_text,
+ _year_text,
+ _time_text;
bool _suspend_notify_vm;
static DateTimePicker() =>
@@ -34,18 +39,25 @@ namespace mbts.ui.controls {
IList _hooks = new List();
+ public void flush_pending_changes() {
+ _month_text?.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
+ _day_text?.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
+ _year_text?.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
+ _time_text?.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
+ }
+
public override void OnApplyTemplate() {
var month = this.assert_template_child("PART_month_tick");
- var month_text = this.assert_template_child("PART_month_text");
+ _month_text = this.assert_template_child("PART_month_text");
var day = this.assert_template_child("PART_day_tick");
- var day_text = this.assert_template_child("PART_day_text");
+ _day_text = this.assert_template_child("PART_day_text");
var year = this.assert_template_child("PART_year_tick");
- var year_text = this.assert_template_child("PART_year_text");
+ _year_text = this.assert_template_child("PART_year_text");
var time = this.assert_template_child("PART_time_tick");
- var time_text = this.assert_template_child("PART_time_text");
+ _time_text = this.assert_template_child("PART_time_text");
if (_controller != null) _controller.PropertyChanged -= _vm_PropertyChanged;
- _controller = new DTPController(time_text);
+ _controller = new DTPController(_time_text);
_controller.result = TimeTuple;
_controller.PropertyChanged += _vm_PropertyChanged;
time.CommandBindings.Add(new CommandBinding(TickTimeComponentCommand, (s, e) => {
@@ -53,53 +65,52 @@ namespace mbts.ui.controls {
}));
time.CommandBindings.Add(new CommandBinding(TextBoxBehavior.SelectAllCommand, TextBoxBehavior.SelectAllCommandExecutedHandler));
- const int delay = 500;
time.SetBinding(TickUpDown.TickCommandProperty, new Binding("tick_time") { Source = _controller });
time.TickUpParameter = 1;
time.TickDownParameter = -1;
time.TickUpAltParameter = 60;
time.TickDownAltParameter = -60;
- time_text.SetBinding(TextBox.TextProperty, new Binding("time_text") { Source = _controller, Delay = delay, ValidatesOnExceptions = true });
- _hooks.Add(time_text.SubscribePreviewTextInput((s, e) => {
- string preview = time_text.PeekText(e);
+ _time_text.SetBinding(TextBox.TextProperty, new Binding("time_text") { Source = _controller, ValidatesOnExceptions = true });
+ _hooks.Add(_time_text.SubscribePreviewTextInput((s, e) => {
+ string preview = _time_text.PeekText(e);
if (RegexFilters.Time.StandardTimeOptionalSeconds.IsMatch(preview)) {
_controller.use_military_time = false;
} else if (RegexFilters.Time.MilitaryTimeOptionalSeconds.IsMatch(preview)) {
_controller.use_military_time = true;
} else {
- e.Handled = true;
+ e.Handled = !RegexFilters.Time.FlexibleTime.IsMatch(preview);
}
}));
month.SetBinding(TickUpDown.TickCommandProperty, new Binding("tick_month") { Source = _controller });
month.TickUpParameter = 1;
month.TickDownParameter = -1;
- month_text.SetBinding(TextBox.TextProperty, new Binding("month_text") { Source = _controller, Delay = delay });
- _hooks.Add(month_text.SubscribePreviewTextInput((s, e) =>
- e.Handled = !RegexFilters.Time.MonthAbbrev.IsMatch(month_text.PeekText(e))
+ _month_text.SetBinding(TextBox.TextProperty, new Binding("month_text") { Source = _controller });
+ _hooks.Add(_month_text.SubscribePreviewTextInput((s, e) =>
+ e.Handled = !RegexFilters.Time.MonthAbbrev.IsMatch(_month_text.PeekText(e))
));
day.SetBinding(TickUpDown.TickCommandProperty, new Binding("tick_day") { Source = _controller });
day.TickUpParameter = 1;
day.TickDownParameter = -1;
- day_text.SetBinding(TextBox.TextProperty, new Binding("day_text") { Source = _controller, Delay = delay });
- _hooks.Add(day_text.SubscribePreviewTextInput((s, e) =>
- e.Handled = !RegexFilters.Time.DaysInMonth.IsMatch(day_text.PeekText(e))
+ _day_text.SetBinding(TextBox.TextProperty, new Binding("day_text") { Source = _controller });
+ _hooks.Add(_day_text.SubscribePreviewTextInput((s, e) =>
+ e.Handled = !RegexFilters.Time.DaysInMonth.IsMatch(_day_text.PeekText(e))
));
year.SetBinding(TickUpDown.TickCommandProperty, new Binding("tick_year") { Source = _controller });
year.TickUpParameter = 1;
year.TickDownParameter = -1;
- year_text.SetBinding(TextBox.TextProperty, new Binding("year_text") { Source = _controller, Delay = delay });
- _hooks.Add(year_text.SubscribePreviewTextInput((s, e) =>
- e.Handled = !RegexFilters.Time.Year.IsMatch(year_text.PeekText(e))
+ _year_text.SetBinding(TextBox.TextProperty, new Binding("year_text") { Source = _controller });
+ _hooks.Add(_year_text.SubscribePreviewTextInput((s, e) =>
+ e.Handled = !RegexFilters.Time.Year.IsMatch(_year_text.PeekText(e))
));
}
void _vm_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(DTPController.result)) {
_suspend_notify_vm = true;
- TimeTuple = _controller.result;
+ SetCurrentValue(TimeTupleProperty, _controller.result);
_suspend_notify_vm = false;
}
}
diff --git a/src/client/spark/view/Converters/AnonymousValueConverter.cs b/src/client/spark/view/Converters/AnonymousValueConverter.cs
index 10882f471..28b8ad002 100644
--- a/src/client/spark/view/Converters/AnonymousValueConverter.cs
+++ b/src/client/spark/view/Converters/AnonymousValueConverter.cs
@@ -37,8 +37,8 @@ namespace mbts.ui.converters {
private readonly Func _convert;
private readonly Func _convert_back;
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return _convert(ObjectHelper.try_convert(value)); }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return _convert_back(ObjectHelper.try_convert(value)); }
+ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return _convert(ConvertUtils.try_convert(value)); }
+ public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return _convert_back(ConvertUtils.try_convert(value)); }
}
public class AnonymousMultiValueConverter : IMultiValueConverter {
@@ -49,7 +49,7 @@ namespace mbts.ui.converters {
public TOut ErrorValue { get; set; }
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
- ObjectHelper.try_convert_args(values, out TIn1 a, out TIn2 b) ? _convert(a, b) : ErrorValue;
+ ConvertUtils.try_convert_args(values, out TIn1 a, out TIn2 b) ? _convert(a, b) : ErrorValue;
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
@@ -62,7 +62,7 @@ namespace mbts.ui.converters {
public TOut ErrorValue { get; set; }
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
- ObjectHelper.try_convert_args(values, out TIn1 a, out TIn2 b, out TIn3 c) ? _convert(a, b, c) : ErrorValue;
+ ConvertUtils.try_convert_args(values, out TIn1 a, out TIn2 b, out TIn3 c) ? _convert(a, b, c) : ErrorValue;
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
diff --git a/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs b/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs
index 112d4970e..486dd5b96 100644
--- a/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs
+++ b/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs
@@ -1,4 +1,4 @@
-using mbts.utils;
+using bts.utils;
using System;
using System.Globalization;
using System.Windows.Data;
@@ -19,7 +19,7 @@ namespace mbts.ui.converters
}
public class DynamicValueEquals : DynamicValueEquals {
- protected override bool ValuesEqual(object x, object y) { return ObjectHelper.try_convert(x, out T tx) && ObjectHelper.try_convert(y, out T ty) && ValuesEqual(tx, ty); }
+ protected override bool ValuesEqual(object x, object y) { return ConvertUtils.try_convert(x, out T tx) && ConvertUtils.try_convert(y, out T ty) && ValuesEqual(tx, ty); }
protected virtual bool ValuesEqual(T x, T y) { return CompareUtils.NullCheckEquals(x, y); }
}
}
\ No newline at end of file
diff --git a/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs b/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs
index 97fde92b6..483266ea2 100644
--- a/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs
+++ b/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs
@@ -12,7 +12,7 @@ namespace mbts.ui.converters
}
public class StaticValueEqualsConverter : StaticValueEqualsConverter {
- protected override bool ValueEquals(object value) { return ObjectHelper.try_convert(value, out T result) && ValueEquals(result); }
+ protected override bool ValueEquals(object value) { return ConvertUtils.try_convert(value, out T result) && ValueEquals(result); }
protected virtual bool ValueEquals(T value) { return base.ValueEquals(value); }
}
}
\ No newline at end of file
diff --git a/src/client/spark/view/Extensions/Command/AsyncDialogCommand.cs b/src/client/spark/view/Extensions/Command/AsyncDialogCommand.cs
index c20424db2..05d4100cd 100644
--- a/src/client/spark/view/Extensions/Command/AsyncDialogCommand.cs
+++ b/src/client/spark/view/Extensions/Command/AsyncDialogCommand.cs
@@ -32,7 +32,7 @@ namespace mbts.ui
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) {
- return !_is_executing && (_can_execute == null || _can_execute(ObjectHelper.try_convert(parameter)));
+ return !_is_executing && (_can_execute == null || _can_execute(ConvertUtils.try_convert(parameter)));
}
public void RaiseCanExecuteChanged() {
@@ -45,7 +45,7 @@ namespace mbts.ui
_is_executing = true;
RaiseCanExecuteChanged();
try {
- var w = await _factory(ObjectHelper.try_convert(parameter));
+ var w = await _factory(ConvertUtils.try_convert(parameter));
if (w != null) {
if (_off_x.HasValue && _off_y.HasValue)
w.move_to_mouse(_off_x.Value, _off_x.Value);
diff --git a/src/client/spark/view/Extensions/Command/DialogCommand.cs b/src/client/spark/view/Extensions/Command/DialogCommand.cs
index 27a5f78bf..e5a9e8611 100644
--- a/src/client/spark/view/Extensions/Command/DialogCommand.cs
+++ b/src/client/spark/view/Extensions/Command/DialogCommand.cs
@@ -28,12 +28,12 @@ namespace mbts.ui
private IDisposable _dialog;
public Predicate can_execute { get; set; }
- public bool CanExecute(object parameter) { return can_execute == null ? true : can_execute(ObjectHelper.try_convert(parameter)); }
+ public bool CanExecute(object parameter) { return can_execute == null ? true : can_execute(ConvertUtils.try_convert(parameter)); }
public event EventHandler CanExecuteChanged;
public void Execute(object parameter) {
Disposable.dispose(ref _dialog);
- Window w = _factory(ObjectHelper.try_convert(parameter));
+ Window w = _factory(ConvertUtils.try_convert(parameter));
if (w != null) {
if (_try_dispose_vm_on_close) {
w.Closed += (s, e) => {
diff --git a/src/client/spark/view/Extensions/Command/FileDialogCommand.cs b/src/client/spark/view/Extensions/Command/FileDialogCommand.cs
index 6e52b47cd..e6b4c911b 100644
--- a/src/client/spark/view/Extensions/Command/FileDialogCommand.cs
+++ b/src/client/spark/view/Extensions/Command/FileDialogCommand.cs
@@ -101,10 +101,10 @@ namespace mbts.ui {
public event EventHandler CanExecuteChanged;
- public bool CanExecute(object parameter) => _can_execute(ObjectHelper.try_convert(parameter));
+ public bool CanExecute(object parameter) => _can_execute(ConvertUtils.try_convert(parameter));
public void Execute(object parameter) {
_safe_close_dialog();
- TParam tparam = ObjectHelper.try_convert(parameter);
+ TParam tparam = ConvertUtils.try_convert(parameter);
_dialog = _dialog_factory(tparam);
if (_dialog.ShowDialog() == DialogResult.OK)
_commit(tparam, _dialog.FileName);
diff --git a/src/client/spark/view/Extensions/DisposeExtensions.cs b/src/client/spark/view/Extensions/DisposeExtensions.cs
index 105cfffee..a76572b31 100644
--- a/src/client/spark/view/Extensions/DisposeExtensions.cs
+++ b/src/client/spark/view/Extensions/DisposeExtensions.cs
@@ -63,5 +63,16 @@ namespace mbts.ui
});
}
}
+
+ public static IDisposable SubscribeDisposed(this IWillLetYouKnowWhenIDispose dispose_broadcaster, Action callback) =>
+ dispose_broadcaster.SubscribeDisposed(_ => { callback?.Invoke(); callback = null; });
+
+ public static IDisposable SubscribeDisposed(this IWillLetYouKnowWhenIDispose dispose_broadcaster, IDisposable dispose) =>
+ dispose_broadcaster.SubscribeDisposed(_ => Disposable.dispose(ref dispose));
+
+ public static IDisposable SubscribeDisposed(this IWillLetYouKnowWhenIDispose dispose_broadcaster, Action callback) {
+ dispose_broadcaster.OnDisposed += callback;
+ return Disposable.Create(() => dispose_broadcaster.OnDisposed -= callback);
+ }
}
}
diff --git a/src/client/spark/view/Extensions/WPFExtensions.cs b/src/client/spark/view/Extensions/WPFExtensions.cs
index 127405dc1..d9ed318d7 100644
--- a/src/client/spark/view/Extensions/WPFExtensions.cs
+++ b/src/client/spark/view/Extensions/WPFExtensions.cs
@@ -24,7 +24,7 @@ namespace mbts.ui {
public static T get_template_child(this Control control, string name) {
object obj = get_template_child(control, name);
- return ObjectHelper.try_convert(obj);
+ return ConvertUtils.try_convert(obj);
}
public static bool try_get_template_child(this Control control, string name, out object result) {
@@ -40,7 +40,7 @@ namespace mbts.ui {
public static bool try_get_template_child(this Control control, string name, out T result) {
if (try_get_template_child(control, name, out object obj))
- return ObjectHelper.try_convert(obj, out result);
+ return ConvertUtils.try_convert(obj, out result);
result = default;
return false;
}
diff --git a/src/client/spark/view/Shell/Login/LoginModel.cs b/src/client/spark/view/Shell/Login/LoginModel.cs
index 44e0240a5..1845850f0 100644
--- a/src/client/spark/view/Shell/Login/LoginModel.cs
+++ b/src/client/spark/view/Shell/Login/LoginModel.cs
@@ -25,24 +25,17 @@ namespace mbts.ui.shell
internal class LoginContainer
{
[ImportingConstructor]
- public LoginContainer(UserService user, [Import("settings")] PersistenceService persist, [Import("autologin", AllowDefault=true)]string auto_login) {
- if (string.IsNullOrEmpty(auto_login)) {
- var model = LoginModel.instance;
- model.provide_services(user, persist);
- // await_login pumps the dispatcher but doesn't allow control to return to MEF until the username and workspace are available
- model.await_login();
- var u = model.get_user();
- UserName = u.name;
- UserId = u.id;
- Workspace = model.get_workspace();
- model.Dispose();
- }
- else {
- UserName = auto_login;
- Environment.SetEnvironmentVariable("BTS_USER", UserName);
- Workspace = string.Empty;
- LoginModel.instance.Dispose();
- }
+ public LoginContainer(UserService user, [Import("settings")] PersistenceService persist) {
+ var model = LoginModel.instance;
+ model.provide_services(user, persist);
+ // await_login pumps the dispatcher but doesn't allow control to return to MEF until the username and workspace are available
+ model.await_login();
+ var u = model.get_user();
+ UserName = u.name;
+ UserId = u.id;
+ Token = u.token;
+ Workspace = model.get_workspace();
+ model.Dispose();
}
[Export("username")]
@@ -50,14 +43,22 @@ namespace mbts.ui.shell
[Export("userid")]
public uint UserId { get; private set; }
+ [Export]
+ public AuthToken Token { get; private set; }
[Export("workspace")]
public string Workspace { get; private set; }
}
public struct User {
- public string name;
- public UInt32 id;
+ public User(string name, uint id, AuthToken token) {
+ this.name = name;
+ this.id = id;
+ this.token = token;
+ }
+ public readonly string name;
+ public readonly UInt32 id;
+ public readonly AuthToken token;
}
public class LoginModel : IDisposable
@@ -117,7 +118,7 @@ namespace mbts.ui.shell
_enum_workspace = new PreloginWorkspaceEnumerator(persist);
var response = await _logon.get_users_async(new GetUsersRequest());
if (response.success) {
- Users = response.value.Users.Select(x => new User { name = x.Login, id = x.Id }).OrderBy(u => u.name).ToArray();
+ Users = response.value.Users.Select(x => new User(x.Login,x.Id, null)).OrderBy(u => u.name).ToArray();
}
else {
ErrorMessage = "Logon: " + response.error_message;
@@ -137,7 +138,7 @@ namespace mbts.ui.shell
if (response.success) {
if (response.value.IsValid) {
_workspace = workspace;
- set_authenticated_user(new User { name =username, id = response.value.UserId});
+ set_authenticated_user(new User(username, response.value.UserId, response.value.Token));
return (true, "");
}
else {
diff --git a/src/client/spark/view/Shell/ViewModels/ShellWindowVM.cs b/src/client/spark/view/Shell/ViewModels/ShellWindowVM.cs
index 62769397f..235e48268 100644
--- a/src/client/spark/view/Shell/ViewModels/ShellWindowVM.cs
+++ b/src/client/spark/view/Shell/ViewModels/ShellWindowVM.cs
@@ -65,15 +65,13 @@ namespace mbts.ui.shell
public string TitleOverride {
get => _title_override;
set {
- if (_title_override != value) {
- if (value == _model.Title) {
- _title_override = null;
- }
- else {
- _title_override = value;
- }
- RaisePropertyChanged(nameof(TitleOverride), nameof(Title), nameof(HasCustomTitle));
+ if (value == _model.Title) {
+ _title_override = null;
}
+ else {
+ _title_override = value;
+ }
+ RaisePropertyChanged(nameof(TitleOverride), nameof(Title), nameof(HasCustomTitle));
_edit_mode.set(false);
}
}
diff --git a/src/client/spark/view/Shell/Workspaces/WorkspaceViewModel.cs b/src/client/spark/view/Shell/Workspaces/WorkspaceViewModel.cs
index fc63e12c2..49bb41138 100644
--- a/src/client/spark/view/Shell/Workspaces/WorkspaceViewModel.cs
+++ b/src/client/spark/view/Shell/Workspaces/WorkspaceViewModel.cs
@@ -9,6 +9,8 @@ namespace mbts.ui.shell
{
public class WorkspaceViewModel : ViewModelBase
{
+ private const string INITIAL_VISUAL_STATE = "Normal";
+
WorkspacesModel _parent;
public WorkspaceViewModel(WorkspacesModel parent, string name, WorkspaceDefinition definition) {
_parent = parent;
@@ -22,8 +24,23 @@ namespace mbts.ui.shell
get { return Icons.Window; }
}
- private string _vstate = "Normal";
- public string VisualState { get { return _vstate; } set { _vstate = value; RaisePropertyChanged("VisualState"); } }
+ private string _vstate = INITIAL_VISUAL_STATE;
+ public string VisualState {
+ get {
+ // this unconventional getter acts as a reset after the VisualStateManager has played
+ // i.e. if we overwrite a workspace then save, then close the window, when we open the
+ // window back up, we'll see item animate b/c it has never been reset from the animate
+ // state. This is necessary b/c the lifetime of Workspaces is not tied to the lifetime
+ // of the View, rather it lives in the Model and is only instantiated on startup via MEF
+ var return_val = _vstate;
+ _vstate = INITIAL_VISUAL_STATE;
+ return return_val;
+ }
+ set {
+ _vstate = value;
+ RaisePropertyChanged("VisualState");
+ }
+ }
internal WorkspaceDefinition Definition { get; private set; }
diff --git a/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs b/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs
index 433292e33..80282e25e 100644
--- a/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs
+++ b/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs
@@ -45,13 +45,13 @@ namespace mbts.ui.shell
{
clear_error("SaveName");
}
- var save_candidate_already_exists = Workspaces.Any(x => x.Name == SaveName);
+ var save_candidate_already_exists = Workspaces.Any(x => x.Name.Replace(WorkspacesModel.SHARED_MONIKER, string.Empty) == SaveName && x.IsShared == IsPublicWorkspace);
// Save
_work_model.save_workspace(SaveName, ispublic: IsPublicWorkspace);
// if we just overwrote something, have the vm reflect it
if (save_candidate_already_exists)
- Workspaces.Where(x => x.Name == SaveName).ForEach(x => x.VisualState = "Overridden");
+ Workspaces.Where(x => x.Name.Replace(WorkspacesModel.SHARED_MONIKER, string.Empty) == SaveName && x.IsShared == IsPublicWorkspace).ForEach(x => x.VisualState = "Overridden");
});
}
}
diff --git a/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs b/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs
index 1c4c59126..867c34b18 100644
--- a/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs
+++ b/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs
@@ -26,6 +26,7 @@ namespace mbts.ui.shell
{
internal const string WORKSPACE_NAMESPACE = "workspace";
internal const string ACTIVE_WORKSPACE_PREFIX = "Where I left off on ";
+ public const string SHARED_MONIKER = " (shared)";
public static string ACTIVE_WORKSPACE_NAME { get { return ACTIVE_WORKSPACE_PREFIX + Environment.MachineName; } }
private ISettingsCollector _settings_collector;
@@ -178,7 +179,7 @@ namespace mbts.ui.shell
public void save_workspace(string name, bool persist=true, bool ispublic=false) {
WorkspaceDefinition workspace = get_workspace();
workspace.is_shared = ispublic;
- if (ispublic) { name += " (shared)"; }
+ if (ispublic) { name += SHARED_MONIKER; }
// Remove the old one if a workspace by this name exists already
var old = Workspaces.SingleOrDefault(w => w.Name == name && ispublic == w.IsShared);
diff --git a/src/client/spark/view/Spark/Core/SparkUtils.cs b/src/client/spark/view/Spark/Core/SparkUtils.cs
index 0aa748cfe..fb620cb3a 100644
--- a/src/client/spark/view/Spark/Core/SparkUtils.cs
+++ b/src/client/spark/view/Spark/Core/SparkUtils.cs
@@ -59,6 +59,12 @@ namespace mbts.spark {
public static SecurityImmutable? security(this SecurityMD? security_md) =>
security_md.HasValue ? new SecurityImmutable?(security_md.Value.security) : new SecurityImmutable?();
+ public static Venue exchange(this SecurityMD? security_md) =>
+ security_md.HasValue ? security_md.Value.security.Exchange : Venue.Unset;
+
+ public static string symbol(this SecurityMD? security_md) =>
+ security_md.HasValue ? security_md.Value.security.Symbol : "unknown";
+
public static async Task get_security_async(IBus bus, uint security_key) =>
await bus.subscribe(SparkTags.SecuritiesTag).Where(map => map.ContainsKey(security_key)).Select(map => map[security_key].security).FirstAsync();
diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs
index 903039173..180f1a3b1 100644
--- a/src/client/spark/view/Spark/Core/TickUtils.cs
+++ b/src/client/spark/view/Spark/Core/TickUtils.cs
@@ -140,7 +140,7 @@ namespace mbts.spark {
Comparer.Create(_compare_unit);
public static IComparer base_unit_comparer =>
- Comparer.Create(utils.CompareUtils.safe_comparison(compare_base_unit));
+ Comparer.Create(bts.utils.CompareUtils.safe_comparison(compare_base_unit));
public static int compare_base_unit(TickFactors a, TickFactors b) {
int comp = _compare_base(a.tick_base, b.tick_base);
diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs
index aceefbcf8..bd9f61f64 100644
--- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs
+++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs
@@ -853,11 +853,11 @@ namespace mbts.spark {
LadderSettings _settings => _owner._settings;
public void refresh() {
- bid_dirty = ObjectHelper.update_value_type(ref _bid, _settings.bid_break_line.show ? _owner._get_bid_market_break() : double.NaN);
- ask_dirty = ObjectHelper.update_value_type(ref _ask, _settings.ask_break_line.show ? _owner._get_ask_market_break() : double.NaN);
- mid_dirty = ObjectHelper.update_value_type(ref _mid, _settings.mid_break_line.show ? _owner._get_mid_market_break() : double.NaN);
- session_low_dirty = ObjectHelper.update_value_type(ref _session_low, (_settings.session_low_line.show || _settings.session_range_fill.show) ? _owner._get_session_low() : double.NaN);
- session_high_dirty = ObjectHelper.update_value_type(ref _session_high, (_settings.session_high_line.show || _settings.session_range_fill.show) ? _owner._get_session_high() : double.NaN);
+ bid_dirty = ConvertUtils.update_value_type(ref _bid, _settings.bid_break_line.show ? _owner._get_bid_market_break() : double.NaN);
+ ask_dirty = ConvertUtils.update_value_type(ref _ask, _settings.ask_break_line.show ? _owner._get_ask_market_break() : double.NaN);
+ mid_dirty = ConvertUtils.update_value_type(ref _mid, _settings.mid_break_line.show ? _owner._get_mid_market_break() : double.NaN);
+ session_low_dirty = ConvertUtils.update_value_type(ref _session_low, (_settings.session_low_line.show || _settings.session_range_fill.show) ? _owner._get_session_low() : double.NaN);
+ session_high_dirty = ConvertUtils.update_value_type(ref _session_high, (_settings.session_high_line.show || _settings.session_range_fill.show) ? _owner._get_session_high() : double.NaN);
if (session_low_dirty)
_low_index = null;
if (session_high_dirty)
@@ -871,7 +871,7 @@ namespace mbts.spark {
else new_origin = mid;
if (double.IsNaN(new_origin))
new_origin = _owner._get_bid_market_break();
- origin_dirty = ObjectHelper.update_value_type(ref _origin, new_origin);
+ origin_dirty = ConvertUtils.update_value_type(ref _origin, new_origin);
}
}
}
diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs
index 0f509ece0..c571fbd3b 100644
--- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs
+++ b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs
@@ -186,8 +186,6 @@ namespace mbts.spark {
public string weighted_average_sell_text => _weighted_average_sell.text;
public void raise_invalidated() => invalidated?.Invoke();
- ObservableCollection DIYGrid.IRowVM.row_animations { get; } = new ObservableCollection();
- IReadOnlyList DIYGrid.IRowVM.cell_stores => new DIYGrid.IGridCellStore[0];
//public IEnumerable sod_fills => _fills.Where(f => f.Timestamp.ToDateTime() >= _start_of_day);
//public IEnumerable pos_fills => _fills.Where(f => f.Timestamp.ToDateTime() < _start_of_day);
diff --git a/src/client/spark/view/Spark/Utilities/OrderDataHelper.cs b/src/client/spark/view/Spark/Utilities/OrderDataHelper.cs
index d837e076a..e9ef09d5b 100644
--- a/src/client/spark/view/Spark/Utilities/OrderDataHelper.cs
+++ b/src/client/spark/view/Spark/Utilities/OrderDataHelper.cs
@@ -37,6 +37,7 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Lean,
CustomOrderDefinition.CustomOneofCase.Join,
CustomOrderDefinition.CustomOneofCase.Cover,
+ CustomOrderDefinition.CustomOneofCase.Offset,
CustomOrderDefinition.CustomOneofCase.Top,
CustomOrderDefinition.CustomOneofCase.Trigger,
},
@@ -47,15 +48,18 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Iceberg,
CustomOrderDefinition.CustomOneofCase.TimeBox,
CustomOrderDefinition.CustomOneofCase.Trigger,
+ CustomOrderDefinition.CustomOneofCase.Offset,
};
public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = _standard_types.Union(_spreader_types).ToArray();
readonly AdminModel _admin_model;
+ readonly DynamicOrderHelper _dynamic_helper;
IDisposable _dispose;
[ImportingConstructor]
- public OrderFactory(AdminModel admin_model) {
+ public OrderFactory(AdminModel admin_model, DynamicOrderHelper dynamic_helper) {
_admin_model = admin_model;
+ _dynamic_helper = dynamic_helper;
}
public IObservable> subscribe_accounts() => _admin_model.on_accounts;
@@ -106,7 +110,7 @@ namespace mbts.spark.utilities {
if(ot != CustomOrderDefinition.CustomOneofCase.Dynamic)
defs.Add(new CustomOrderDefinitionImmutable(custom_order(ot)));
}
- DynamicOrderHelper.add_dynamic_order_defs(defs, ott => custom_order(ott));
+ _dynamic_helper.add_dynamic_order_defs(defs, ott => custom_order(ott));
return defs;
}
@@ -119,7 +123,7 @@ namespace mbts.spark.utilities {
// TODO: replace with better naming scheme (right now, the order type ref count 'n' is appended to the order-type name)
var order_type_ref_count = defs.ToDictionary(kv => kv.Key, kv => name_ref_seed);
var dynamic_defs = new List();
- DynamicOrderHelper.add_dynamic_order_defs(dynamic_defs, ot => custom_order(ot));
+ _dynamic_helper.add_dynamic_order_defs(dynamic_defs, ot => custom_order(ot));
foreach (var ddef in dynamic_defs) {
var header = new OrderTemplateHeader(new OrderTemplateKey(ddef.CustomCase, ddef.Dynamic.DynamicOrderType), ddef.Dynamic.DynamicOrderType );
// if (order_type_ref_count.TryGetValue(header, out int count)) {
@@ -212,19 +216,21 @@ namespace mbts.spark.utilities {
{
Child = custom_order(),
JoinThreshold = new QuantityMeasure(),
- Hedge = custom_order(),
};
public TopOrderDefinition top_order() => new TopOrderDefinition
{
Child = custom_order(),
TopThreshold = new QuantityMeasure(),
- Hedge = custom_order(),
};
public CoverOrderDefinition cover_order() => new CoverOrderDefinition
{
Child = custom_order(),
Hedge = custom_order(),
};
+ public OffsetOrderDefinition offset_order() => new OffsetOrderDefinition
+ {
+ Child = custom_order(),
+ };
public TriggerOrderDefinition trigger_order() => new TriggerOrderDefinition
{
@@ -234,8 +240,7 @@ namespace mbts.spark.utilities {
};
public DynamicOrderDefinition dynamic_order() => new DynamicOrderDefinition
- {
- Child = custom_order(),
+ {
};
@@ -251,11 +256,12 @@ namespace mbts.spark.utilities {
case CustomOrderDefinition.CustomOneofCase.StopLimit: rv.StopLimit = stop_limit_order(); break;
case CustomOrderDefinition.CustomOneofCase.Iceberg: rv.Iceberg = iceberg_order(); break;
case CustomOrderDefinition.CustomOneofCase.TimeBox: rv.TimeBox = time_box_order(); break;
- case CustomOrderDefinition.CustomOneofCase.Tick: rv.Tick = tick_order(); break;
+ case CustomOrderDefinition.CustomOneofCase.Tick: rv.Tick = tick_order(); break;
case CustomOrderDefinition.CustomOneofCase.Lean: rv.Lean = lean_order(); break;
case CustomOrderDefinition.CustomOneofCase.Join: rv.Join = join_order(); break;
case CustomOrderDefinition.CustomOneofCase.Top: rv.Top = top_order(); break;
case CustomOrderDefinition.CustomOneofCase.Cover: rv.Cover = cover_order(); break;
+ case CustomOrderDefinition.CustomOneofCase.Offset: rv.Offset = offset_order(); break;
case CustomOrderDefinition.CustomOneofCase.Trigger: rv.Trigger = trigger_order(); break;
case CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = spreader_order(); break;
case CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = dynamic_order(); break;
@@ -278,6 +284,7 @@ namespace mbts.spark.utilities {
case CustomOrderDefinition.CustomOneofCase.Join: return new OrderMetadata { KeyBinding = "J", Color = BTSColors.Orders.join_order };
case CustomOrderDefinition.CustomOneofCase.Top: return new OrderMetadata { KeyBinding = "D", Color = BTSColors.Orders.top_order };
case CustomOrderDefinition.CustomOneofCase.Cover: return new OrderMetadata { KeyBinding = "C", Color = BTSColors.Orders.cover_order };
+ case CustomOrderDefinition.CustomOneofCase.Offset: return new OrderMetadata { KeyBinding = "O", Color = BTSColors.Orders.tick_order };
case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order };
case CustomOrderDefinition.CustomOneofCase.Spreader: goto default;
case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order };
@@ -298,6 +305,7 @@ namespace mbts.spark.utilities {
case OrderState.CustomOneofCase.Join: return new OrderMetadata { KeyBinding = "J", Color = BTSColors.Orders.join_order };
case OrderState.CustomOneofCase.Top: return new OrderMetadata { KeyBinding = "D", Color = BTSColors.Orders.top_order };
case OrderState.CustomOneofCase.Cover: return new OrderMetadata { KeyBinding = "C", Color = BTSColors.Orders.cover_order };
+ case OrderState.CustomOneofCase.Offset: return new OrderMetadata { KeyBinding = "O", Color = BTSColors.Orders.tick_order };
case OrderState.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order };
case OrderState.CustomOneofCase.Spreader: goto default;
case OrderState.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.top_order };
@@ -336,6 +344,7 @@ namespace mbts.spark.utilities {
case nameof(JoinOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Join;
case nameof(TopOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Top;
case nameof(CoverOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Cover;
+ case nameof(OffsetOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Offset;
case nameof(TriggerOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Trigger;
case nameof(DynamicOrderDefinition): return CustomOrderDefinition.CustomOneofCase.Dynamic;
default: throw new ArgumentException($"Unable to match '{order_type_def?.Descriptor.Name}' to an order definition type");
diff --git a/src/client/spark/view/Utility/SortingCriteria.cs b/src/client/spark/view/Utility/SortingCriteria.cs
index 4b09ac9dc..6845f9470 100644
--- a/src/client/spark/view/Utility/SortingCriteria.cs
+++ b/src/client/spark/view/Utility/SortingCriteria.cs
@@ -21,5 +21,7 @@ namespace mbts.ui
public bool is_ascending;
public SortDescription to_sort_description() { return new SortDescription(col_name, is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending); }
+
+ public override string ToString() => $"{col_name}:{(is_ascending ? "Ascending" : "Descending")}";
}
}
\ No newline at end of file
diff --git a/src/client/spark/view/Utility/TextUtils.cs b/src/client/spark/view/Utility/TextUtils.cs
index b29b2cb87..2ec2cea09 100644
--- a/src/client/spark/view/Utility/TextUtils.cs
+++ b/src/client/spark/view/Utility/TextUtils.cs
@@ -144,6 +144,7 @@ namespace mbts.ui.utility.text {
StandardTimeOptionalSeconds = new Regex(@"^((\d?|0\d|1[0-2])|((\d|0\d|1[0-2])(:?|(:([0-5]?|[0-5]\d(( ?|( ([aApP]?|[aApP][mM])))(:?|(: ?)|(: [aApP]?[mM]?)|(:[0-5]?\d? ?[aApP]?[mM]?))|:([0-5]?|([0-5]\d( ?|( ([aApP]?|([aApP][mM]))))))))))))$"),
MilitaryTime = new Regex(@"^(([0-1]?[0-9])|(2?[0-3]?))(:?|:([0-5]?|[0-5][0-9]?))$"),
MilitaryTimeOptionalSeconds = new Regex(@"^((\d?|[0-1]\d|2[0-3])|((\d|[0-1]\d|2[0-3])(:?|(:([0-5]?|[0-5]\d(:?|:([0-5]?|[0-5]\d)))))))$"),
+ FlexibleTime = new Regex(@"^[0-9:aApPmM ]*$"),
DaysInMonth = new Regex(@"^([0-9]?|[0-2][0-9]|3[0-1])?$"),
MonthAbbrev = new Regex(@"^(?i)(a(ug?|pr?)?|d(e|ec)?|f(e?b)?|j(an?|u[nl]?)?|m(a[ry]?)?|(o(ct?)?)|s(ep?)?|n(ov?)?)?$"),
Year = new Regex(@"^\d{0,4}$"),
diff --git a/src/client/spark/view/Utility/WPFHelper.cs b/src/client/spark/view/Utility/WPFHelper.cs
index 275ac1ea2..eb350fc7f 100644
--- a/src/client/spark/view/Utility/WPFHelper.cs
+++ b/src/client/spark/view/Utility/WPFHelper.cs
@@ -259,13 +259,13 @@ namespace mbts.ui {
}
public static PropertyChangedCallback prop_changed_callback(PropertyChangedCallback callback) =>
- (d, e) => callback(ObjectHelper.try_convert(d), ObjectHelper.try_convert(e.OldValue), ObjectHelper.try_convert(e.NewValue));
+ (d, e) => callback(ConvertUtils.try_convert(d), ConvertUtils.try_convert(e.OldValue), ConvertUtils.try_convert(e.NewValue));
public static PropertyChangedCallback prop_changed_callback(Action callback) =>
- (d, e) => callback(ObjectHelper.try_convert(d), ObjectHelper.try_convert(e.NewValue));
+ (d, e) => callback(ConvertUtils.try_convert(d), ConvertUtils.try_convert(e.NewValue));
public static CoerceValueCallback coerce_value_callback(Func coerce_value) =>
- (d, obj) => coerce_value(ObjectHelper.try_convert(d), ObjectHelper.try_convert(obj));
+ (d, obj) => coerce_value(ConvertUtils.try_convert(d), ConvertUtils.try_convert(obj));
public static double control_base_width(Thickness border_thickness, Thickness padding) =>
border_thickness.Left + padding.Left + padding.Right + border_thickness.Right;
diff --git a/src/client/spark_sdk/samples/MarketDataClient.cs b/src/client/spark_api/md/MarketDataClient.cs
similarity index 77%
rename from src/client/spark_sdk/samples/MarketDataClient.cs
rename to src/client/spark_api/md/MarketDataClient.cs
index 19d1442bc..748ffdea8 100644
--- a/src/client/spark_sdk/samples/MarketDataClient.cs
+++ b/src/client/spark_api/md/MarketDataClient.cs
@@ -12,7 +12,7 @@ using bts.api;
using bts.api.core;
using bts.co2;
-namespace bts.sdk
+namespace bts.api.md
{
using security_key = System.UInt32;
public class MarketDataClient : IDisposable
@@ -30,17 +30,39 @@ namespace bts.sdk
MDRequest.Types.Flags.Implied |
MDRequest.Types.Flags.LastTrade);
- readonly ConcurrentDictionary _data = new ConcurrentDictionary();
+ readonly ConcurrentDictionary _data = new ConcurrentDictionary();
+ readonly ConcurrentDictionary _security_key_to_desc= new ConcurrentDictionary();
+ readonly ConcurrentDictionary _security_desc_to_key = new ConcurrentDictionary();
+ readonly Lazy _subscription;
+ readonly Venue _venue;
+
readonly static Lazy _md = new Lazy(() => locate(), true);
- readonly Lazy _subscription = new Lazy(() => load_request());
- public MarketDataClient()
+ readonly static ConcurrentDictionary _venue_cache = new ConcurrentDictionary();
+ static readonly List _all_products;
+ static MarketDataClient()
{
+ _all_products = _md.Value.request_products(new VoidMessage()).Products.ToList();
+ }
+ public static bool create_or_get(api.Venue exchange, out MarketDataClient md)
+ {
+ if (!_venue_cache.TryGetValue(exchange, out md))
+ {
+ _venue_cache[exchange] = md = new MarketDataClient(exchange);
+ return true;
+ }
+ return false;
+ }
+
+ public MarketDataClient(bts.api.Venue exchange = Venue.Unset)
+ {
+ _venue = exchange;
+ _subscription = new Lazy(() => load_request(exchange));
}
- static MDRequest load_request()
+ MDRequest load_request(bts.api.Venue exchange)
{
var req = new MDRequest();
- var prods = _md.Value.request_products(new VoidMessage()).Products;
+ var prods = _all_products.Where(x=>x.Exchange == exchange || exchange == bts.api.Venue.Unset);
foreach(var prod in prods)
req.Channels.Add(new SecurityChannel() { Exchange = prod.Exchange, Type = prod.Type, Symbol = prod.Symbol, Flags = 0 });
return req;
@@ -63,6 +85,16 @@ namespace bts.sdk
return null;
}
+ public bool lookup_security_desc(security_key key, out string security_desc)
+ {
+ return _security_key_to_desc.TryGetValue(key, out security_desc);
+ }
+
+ public bool lookup_security_key_from_desc(string security_desc, out security_key key)
+ {
+ return _security_desc_to_key.TryGetValue(security_desc, out key);
+ }
+
public Security find_security(Func filter)
{
return _data.Values.Select(x => x.data.Security).Where(xx => filter(xx)).FirstOrDefault();
@@ -203,6 +235,20 @@ namespace bts.sdk
///
public async Task start_pump(TimeSpan? interval = null)
{
+ var rep = await _md.Value.request_names_async(new VoidMessage());
+ int count = 0;
+ do
+ {
+ foreach (var s in rep.value.Securities)
+ {
+ foreach (var ss in s.Names)
+ {
+ _security_desc_to_key[ss.Value] = ss.Key;
+ _security_key_to_desc[ss.Key] = ss.Value;
+ }
+ }
+ }
+ while (!rep.success && count++ < 5);
while (true)
{
var reply = await _md.Value.requestmd_async(_subscription.Value);
@@ -248,6 +294,12 @@ namespace bts.sdk
}
}
+ public async void run_pump_async(TimeSpan? interval = null)
+ {
+ await this.start_pump(interval);
+ }
+
+
readonly CancellationTokenSource _cts = new CancellationTokenSource();
public void Dispose()
{
diff --git a/src/client/spark_api/utils/Log.cs b/src/client/spark_api/utils/Log.cs
index 83cb36b3d..d07b338ca 100644
--- a/src/client/spark_api/utils/Log.cs
+++ b/src/client/spark_api/utils/Log.cs
@@ -31,7 +31,8 @@ namespace bts {
Mercury,
Testing,
Latency,
- DataFlow
+ DataFlow,
+ Plugin
// Please keep this list in sync with logging.h/logging.cpp
}
readonly struct Logger {
diff --git a/src/client/spark_core/Co2/Co2NativeMethods.cs b/src/client/spark_core/Co2/Co2NativeMethods.cs
index 1d07490ef..1276d1ca9 100644
--- a/src/client/spark_core/Co2/Co2NativeMethods.cs
+++ b/src/client/spark_core/Co2/Co2NativeMethods.cs
@@ -80,6 +80,8 @@ namespace mbts.co2
internal unsafe static extern IntPtr stop_relay(IntPtr relay);
[DllImport("libspark")]
internal unsafe static extern IntPtr add_relay_symbol(IntPtr relay, UserSymbol symbol, bts.co2.MDRequest.Types.Flags flags);
+ [DllImport("libspark")]
+ internal unsafe static extern IntPtr set_relay_token(IntPtr relay, string user_name);
[DllImport("libspark")]
internal unsafe static extern void post_on_scan_security_thread(Action callback);
diff --git a/src/client/spark_core/Co2/Co2RelayControl.cs b/src/client/spark_core/Co2/Co2RelayControl.cs
index eb2835f2b..9adef0694 100644
--- a/src/client/spark_core/Co2/Co2RelayControl.cs
+++ b/src/client/spark_core/Co2/Co2RelayControl.cs
@@ -6,6 +6,7 @@ using System.Text;
using System.Threading.Tasks;
using bts.api;
using bts;
+using bts.api.user;
namespace mbts.co2
{
@@ -22,6 +23,10 @@ namespace mbts.co2
Log.assert(_relay != IntPtr.Zero);
}
+ public void set_token(AuthToken token) {
+ Co2NativeMethods.set_relay_token(_relay, token.Token);
+ }
+
public async Task preload_securities(MDRequest.Types.Flags flags=MDRequest.Types.Flags.Security) {
var securities = UserSymbol.get_all();
foreach (var future in securities.Where(s => s.type == SecurityType.Future)) {
diff --git a/src/client/spark_core/Co2/MDConsumerHandle.cs b/src/client/spark_core/Co2/MDConsumerHandle.cs
index a5454b6f2..3f5c6502e 100644
--- a/src/client/spark_core/Co2/MDConsumerHandle.cs
+++ b/src/client/spark_core/Co2/MDConsumerHandle.cs
@@ -149,7 +149,6 @@ namespace mbts.co2 {
public DateTime close_date { get { return _cold->close_date; } }
public double session_high { get { return _cold->session_high; } }
public double session_low { get { return _cold->session_low; } }
- public double open_interest { get { return _cold->open_interest; } }
// public double session_high_bid { get { return _cold->session_high_bid; } }
// public double session_low_offer { get { return _cold->session_low_offer; } }
public double fixing_price { get { return _cold->fixing_price; } }
@@ -245,7 +244,7 @@ namespace mbts.co2 {
}
}
- [StructLayout(LayoutKind.Sequential, Size = 384)]
+ [StructLayout(LayoutKind.Sequential, Size = 376)]
internal struct ColdEntry {
public int exchange_status;
// Last trade
@@ -268,7 +267,6 @@ namespace mbts.co2 {
//// Misc stats for current session
public double session_high;
public double session_low;
- public double open_interest;
public double session_high_bid;
public double session_low_offer;
public double fixing_price;
diff --git a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs
new file mode 100644
index 000000000..5f7576ad8
--- /dev/null
+++ b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs
@@ -0,0 +1,81 @@
+using System.Collections.ObjectModel;
+using System.Linq;
+
+namespace System.Collections.Generic {
+ public static class DictionaryExtensions {
+ public static void AddOrUpdate(this IDictionary dictionary, TKey key, Func add_value_factory, Action update_value) {
+ if (!dictionary.TryGetValue(key, out TValue value))
+ dictionary.Add(key, add_value_factory(key));
+ else update_value(key, value);
+ }
+
+ public static void AddOrUpdate(this IDictionary dictionary, TKey key, Func add_value_factory, Func update_value) {
+ if (!dictionary.TryGetValue(key, out TValue value))
+ dictionary.Add(key, add_value_factory(key));
+ dictionary[key] = update_value(key, value);
+ }
+
+ public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func add_value_factory) {
+ if (!dictionary.TryGetValue(key, out TValue value))
+ dictionary.Add(key, value = add_value_factory(key));
+ return value;
+ }
+
+ public static IReadOnlyDictionary Join(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target) =>
+ Join(dictionary, merge_target, (v1, v2) => (v1, v2));
+
+ public static IReadOnlyDictionary Join(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target, Func select) {
+ var iks = dictionary.Keys.Intersect(merge_target.Keys);
+ return new ReadOnlyDictionary(iks.ToDictionary(k => k, k => select(dictionary[k], merge_target[k])));
+ }
+
+ public static IReadOnlyDictionary LeftJoin(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target,
+ Func select, Func select_left_only) =>
+ dictionary.ToDictionary(kv => kv.Key, kv => {
+ if (merge_target.TryGetValue(kv.Key, out TValue2 v2))
+ return select(kv.Value, v2);
+ else
+ return select_left_only(kv.Value);
+ });
+
+ public static IReadOnlyDictionary SuperJoin(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target) {
+ var eks1 = dictionary.Keys.Except(merge_target.Keys);
+ var eks2 = merge_target.Keys.Except(dictionary.Keys);
+ var iks = dictionary.Keys.Intersect(merge_target.Keys);
+ return new ReadOnlyDictionary(eks1
+ .Select(k => (k, dictionary[k], default(TValue2)))
+ .Concat(eks2.Select(k => (k, default(TValue1), merge_target[k])))
+ .Concat(iks.Select(k => (k, dictionary[k], merge_target[k])))
+ .ToDictionary(vals => vals.k, vals => (vals.Item2, vals.Item3))
+ );
+ }
+
+ ///
+ /// Gets the value associated with the specified key, then removes the key if the lookup was successful.
+ ///
+ /// The type of keys in the dictionary.
+ /// The type of values in the dictionary.
+ /// A dictionary to try to get/remove a KeyValuePair from.
+ /// The key of the value to get/remove.
+ /// When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
+ /// true if the dictionary contains an element with the specified key; otherwise, false.
+ public static bool TryPopValue(this IDictionary dictionary, TKey key, out TValue result) {
+ if (dictionary.TryGetValue(key, out result)) {
+ dictionary.Remove(key);
+ return true;
+ } else return false;
+ }
+
+ ///
+ /// Gets the value associated with the specified key, then calls with the result if the lookup was successful. If returns true, the key is removed.
+ ///
+ /// The type of keys in the dictionary.
+ /// The type of values in the dictionary.
+ /// A dictionary to try to get/remove a KeyValuePair from.
+ /// The key of the value to get/remove.
+ /// When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
+ /// true if the dictionary contains an element with the specified key, AND returns true; otherwise, false.
+ public static bool TryPopValueIf(this IDictionary dictionary, TKey key, Func should_pop) =>
+ dictionary.TryGetValue(key, out TValue result) && should_pop(result) && dictionary.Remove(key);
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark_core/Collections/SortedList.cs b/src/client/spark_core/Collections/SortedList.cs
index dd31ef0ff..d6ddc3c2a 100644
--- a/src/client/spark_core/Collections/SortedList.cs
+++ b/src/client/spark_core/Collections/SortedList.cs
@@ -2,7 +2,6 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
namespace bts.collections {
public class SortedList : IEnumerable {
@@ -10,11 +9,18 @@ namespace bts.collections {
int _size = 0;
readonly IComparer _comparer;
+ ///
+ /// Note: comparer MUST be 100% deterministic for to work properly; item-equality is NOT checked.
+ ///
public SortedList(IComparer comparer) {
_comparer = comparer;
_values = new T[4];
_size = 0;
}
+
+ ///
+ /// Note: comparer MUST be 100% deterministic for to work properly; item-equality is NOT checked.
+ ///
public SortedList(IEnumerable items, IComparer comparer) {
_comparer = comparer;
var capacity = items.Count();
@@ -24,6 +30,8 @@ namespace bts.collections {
}
}
+ public int Count => _size;
+
bool Contains(T item) {
return BinarySearch(item) >= 0;
}
@@ -57,6 +65,16 @@ namespace bts.collections {
return false;
}
+ public void Clear() {
+ Array.Clear(_values, 0, _values.Length);
+ _size = 0;
+ }
+
+ public bool TryGetIndex(T item, out int result) {
+ result = BinarySearch(item);
+ return result > 0;
+ }
+
public T this [int index] {
get {
return _values[index];
diff --git a/src/client/spark_core/Collections/SortedTree.cs b/src/client/spark_core/Collections/SortedTree.cs
index d6db11772..884a2c3a1 100644
--- a/src/client/spark_core/Collections/SortedTree.cs
+++ b/src/client/spark_core/Collections/SortedTree.cs
@@ -1,100 +1,235 @@
-using System;
+using mbts.utils;
+using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
namespace bts.collections {
+ public interface INode {
+ T value { get; }
+ IEnumerable> inner { get; }
+ }
- public class SortedTree : IEnumerable {
+ public static class NodeExtensions {
+ public static IEnumerable inner_values(this INode node) {
+ foreach (var n in node.inner) {
+ yield return n.value;
+ foreach (var v in n.inner_values())
+ yield return v;
+ }
+ }
+ }
+
+ public class SortedTree : IEnumerable where TKey : IEquatable {
readonly IComparer _comparer;
readonly Func id;
readonly Func parent;
+ readonly TKey _root_id;
Dictionary _index = new Dictionary();
+ Dictionary> _nursery = new Dictionary>();
SortedList _tree;
+ ///
+ /// comparer MUST be 100% deterministic, else Removes won't work right (SortedList uses a simple BinarySearch to find/remove items, and does NOT check item-equality).
+ ///
+ public SortedTree(IComparer comparer, Func fnid, Func fnparent, IEnumerable items = null)
+ : this(comparer, fnid, fnparent, default, items) { }
- public SortedTree(IComparer comparer, Func fnid, Func fnparent, IEnumerable items=null) {
+ ///
+ /// comparer MUST be 100% deterministic, else Removes won't work right (SortedList uses a simple BinarySearch to find/remove items, and does NOT check item-equality).
+ ///
+ public SortedTree(IComparer comparer, Func fnid, Func fnparent, TKey root_id, IEnumerable items = null) {
_comparer = Comparer.Create((l, r) => comparer.Compare(l.value, r.value));
id = fnid;
parent = fnparent;
_tree = new SortedList(_comparer);
- if (items != null) {
- AddAll(items);
- }
+ _root_id = root_id;
+ Reset(items);
}
+ public IEnumerable> RootNodes => _tree;
+
// Insert (return: true) or overwrite (return false) a new value
// NOTE: you should use AddAll if you are adding multiple values
public bool Insert(T item) {
- var item_id = id(item);
- if (!_index.TryGetValue(item_id, out Node itemnode)) {
- // Item is new
- itemnode = new Node(item, _comparer);
- _index[item_id] = itemnode;
- if (_index.TryGetValue(parent(item), out Node pnode)) {
- pnode.children.Add(itemnode);
- }
+ var k = id(item);
+ if (_index.TryGetValue(k, out Node node)) {
+ _replace(node, item);
+ return false;
+ } else {
+ if (_nursery.TryPopValue(k, out SortedList children)) {
+ // remove orphans from _tree (orphan-nodes must reside in the main _tree until parents arrive)
+ foreach (var n in children)
+ _tree.Remove(n);
+ node = new Node(item, children);
+ } else node = new Node(item, _comparer);
+ var pk = parent(item);
+ if (pk.Equals(_root_id))
+ _tree.Add(node);
+ else if (_index.TryGetValue(pk, out Node pnode))
+ pnode.children.Add(node);
else {
- _tree.Add(itemnode);
+ if (!_nursery.TryGetValue(pk, out SortedList l))
+ _nursery.Add(pk, l = new SortedList(_comparer));
+ l.Add(node);
+ _tree.Add(node);
}
+ _index.Add(k, node);
return true;
}
- else {
- // Item exists
- if (!parent(itemnode.value).Equals(parent(item))) {
- // Item has a new parent
- // Remove it entirely and re-insert at a new tree position
- Remove(item);
- Insert(item);
- return false;
- }
- else {
- // Item has same parent. Just overwrite in place
- itemnode.value = item;
- return false;
- }
- }
- }
- public void Remove(T item) {
- var item_id = id(item);
- if (_index.TryGetValue(item_id, out Node itemnode)) {
- if (_index.TryGetValue(parent(item), out Node parentnode)) {
- parentnode.children.Remove(itemnode);
- }
- else {
- _tree.Remove(itemnode);
- }
- _index.Remove(item_id);
- }
}
+ public bool TryReplace(TKey k, Func replace) {
+ if (!_index.TryGetValue(k, out Node node)) {
+ return false;
+ } else {
+ var newval = replace(node.value);
+ Log.assert(id(newval).Equals(k));
+ _replace(node, newval);
+ return true;
+ }
+ }
+
+
+ public void Remove(T item) => Remove(id(item));
+
+ // this is NOT idempotent, and will throw an exception if the Key is not present.
+ // (if we decide to change it to be idempotent, we should return a bool to indicate whether or not the remove succeeded)
+ public void Remove(TKey k) {
+ // must be in the index, bc this is a remove
+ var node = _index[k];
+ _index.Remove(k);
+ var pk = parent(node.value);
+ if (pk.Equals(_root_id)) {
+ _tree.Remove(node);
+ } else if (_index.TryGetValue(pk, out Node pnode)) {
+ pnode.children.Remove(node);
+ } else {
+ _remove_from_nursery(pk, node);
+ }
+ if (node.children.Count > 0) {
+ // any children left behind are orphans now, add them to the main _tree and _nursery
+ _nursery.Add(k, node.children);
+ foreach (var n in node.children)
+ _tree.Add(n);
+ }
+ }
+
+ ///
+ /// comparer MUST be 100% deterministic, else Removes won't work right (SortedList uses a simple BinarySearch to find/remove items, and does NOT check item-equality).
+ ///
public SortedTree Resort(IComparer comparer) {
return new SortedTree(comparer, id, parent, this);
}
- // Note: This method does not handle replacements correctly.
- public void AddAll(IEnumerable items) {
+ public void Reset(IEnumerable items) {
+ Clear();
+ if (items == null) return;
// When adding multiple items we build the index first to avoid the children before parents problem
foreach (var item in items) {
- //_index[id(item)] = new Node(item, _comparer);
_index.Add(id(item), new Node(item, _comparer));
}
- // Assume all parents are in this collection
- // There's not really anything else we can do
foreach (var item in items) {
// We are sure it is in the index because we just added it
- var itemnode = _index[id(item)];
- if (_index.TryGetValue(parent(item), out Node pnode)) {
- pnode.children.Add(itemnode);
+ var node = _index[id(item)];
+ if (_nursery.TryPopValue(id(item), out SortedList nl)) {
+ // remove orphans from _tree (orphan-nodes must reside in the main _tree until parents arrive)
+ foreach (var n in nl)
+ _tree.Remove(n);
+ if (node.children.Count == 0) {
+ node.children = nl;
+ } else {
+ if (node.children.Count > nl.Count) {
+ // merge nl into node.children
+ foreach (var cn in nl)
+ node.children.Add(cn);
+ } else {
+ // merge node.children into nl
+ foreach (var cn in node.children)
+ nl.Add(cn);
+ node.children = nl;
+ }
+ }
}
- else {
- _tree.Add(itemnode);
+ TKey pk = parent(item);
+ if (pk.Equals(_root_id)) {
+ _tree.Add(node);
+ } else if (_index.TryGetValue(pk, out Node pnode)) {
+ pnode.children.Add(node);
+ } else {
+ if (!_nursery.TryGetValue(pk, out nl))
+ _nursery.Add(pk, nl = new SortedList(_comparer));
+ nl.Add(node);
+ _tree.Add(node);
}
}
}
+ public void Clear() {
+ foreach (Node n in _tree)
+ clear_node(n);
+ foreach (var nl in _nursery.Values) {
+ foreach (var n in nl)
+ clear_node(n);
+ nl.Clear();
+ }
+ _tree.Clear();
+ _index.Clear();
+ _nursery.Clear();
+
+ void clear_node(Node n) {
+ foreach (Node cn in n.children)
+ clear_node(cn);
+ n.children.Clear();
+ }
+ }
+
+ void _replace(Node node, T newval) {
+ TKey pk = parent(newval);
+ TKey old_pk = parent(node.value);
+ if (pk.Equals(old_pk)) {
+ SortedList node_list;
+ if (pk.Equals(_root_id))
+ node_list = _tree;
+ else if (_index.TryGetValue(pk, out Node pnode)) {
+ node_list = pnode.children;
+ } else if (!_nursery.TryGetValue(pk, out node_list)) {
+ throw new KeyNotFoundException($"Replace was called with a parent-key ({pk}) that was not found in _index or _nursery; item-key was ({id(newval)}).");
+ }
+ node_list.Remove(node);
+ node.value = newval;
+ node_list.Add(node);
+ } else {
+ if (old_pk.Equals(_root_id)) {
+ _tree.Remove(node);
+ } else {
+ if (_index.TryGetValue(old_pk, out Node pnode))
+ pnode.children.Remove(node);
+ else {
+ _remove_from_nursery(old_pk, node);
+ }
+ }
+ node.value = newval;
+ if (pk.Equals(_root_id)) {
+ _tree.Add(node);
+ } else if (_index.TryGetValue(pk, out Node pnode)) {
+ pnode.children.Add(node);
+ } else {
+ if (!_nursery.TryGetValue(pk, out SortedList nursery_list)) {
+ _nursery.Add(pk, nursery_list = new SortedList(_comparer));
+ }
+ nursery_list.Add(node);
+ _tree.Add(node);
+ }
+ }
+ }
+
+ void _remove_from_nursery(TKey pk, Node node) {
+ _nursery.TryPopValueIf(pk, nl => nl.Remove(node) && nl.Count == 0);
+ _tree.Remove(node);
+ }
+
IEnumerable iterate(SortedList nodes) {
foreach (var n in nodes) {
yield return n.value;
@@ -114,27 +249,50 @@ namespace bts.collections {
return null;
}
+ public INode GetRootNode(TKey key) =>
+ _index.TryGetValue(key, out Node node) ? GetRootNode(node) : null;
+
+ Node GetRootNode(Node node) =>
+ _index.TryGetValue(parent(node.value), out Node pnode) ? GetRootNode(pnode) : node;
public IEnumerable EnumerateGroup(T item) {
var pnode = parentmost(item);
- if (pnode != null) {
- yield return pnode.value;
- foreach (var child in iterate(pnode.children)) {
- yield return child;
- }
+ return pnode == null ? Enumerable.Empty() : EnumerateNode(pnode);
+ }
+
+ public IEnumerable EnumerateInnerValues(T item) =>
+ iterate(_index[id(item)].children);
+
+ public IEnumerable> EnumerateInnerNodes(T item) =>
+ _index[id(item)].children;
+
+ IEnumerable EnumerateNode(Node node) {
+ yield return node.value;
+ foreach (var child in iterate(node.children)) {
+ yield return child;
}
}
public IEnumerator GetEnumerator() {
- return iterate(_tree).GetEnumerator();
+ foreach (T item in iterate(_tree))
+ yield return item;
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
- class Node {
- public Node(T i, IComparer c) { value = i; children = new SortedList(c); }
+ class Node : INode {
+ public Node(T i, IComparer c)
+ : this(i, new SortedList(c)) { }
+
+ public Node(T i, SortedList children) {
+ value = i;
+ this.children = children;
+ }
+
public T value;
public SortedList children;
+ T INode.value => value;
+ IEnumerable> INode.inner => children;
}
}
}
diff --git a/src/client/spark_core/utils/AnonymousDisposable.cs b/src/client/spark_core/utils/AnonymousDisposable.cs
index 5948d6484..a4750ea9d 100644
--- a/src/client/spark_core/utils/AnonymousDisposable.cs
+++ b/src/client/spark_core/utils/AnonymousDisposable.cs
@@ -92,6 +92,13 @@ namespace mbts
item = null;
}
}
+
+ public static void replace(ref T current, T newval) where T : IDisposable {
+ if (current != null) {
+ current.Dispose();
+ }
+ current = newval;
+ }
}
// inspired by: https://blogs.msdn.microsoft.com/blambert/2009/07/24/a-simple-and-totally-thread-safe-implementation-of-idisposable/
diff --git a/src/client/spark/core/Utility/CompareUtils.cs b/src/client/spark_core/utils/CompareUtils.cs
similarity index 65%
rename from src/client/spark/core/Utility/CompareUtils.cs
rename to src/client/spark_core/utils/CompareUtils.cs
index 89ebe5f3e..2484c596d 100644
--- a/src/client/spark/core/Utility/CompareUtils.cs
+++ b/src/client/spark_core/utils/CompareUtils.cs
@@ -2,8 +2,14 @@
using System.Collections;
using System.Collections.Generic;
-namespace mbts.utils {
+namespace bts.utils {
public static class CompareUtils {
+ public static int safe_compare(this T a, T b, Func compare) =>
+ a == null ? (b == null ? 0 : -1) : (b == null ? 1 : compare(a, b));
+
+ public static int safe_compare(this T a, T b) where T : IComparable =>
+ a == null ? (b == null ? 0 : -1) : (b == null ? 1 : a.CompareTo(b));
+
#region Equality
public static bool NullCheckEquals(T x, T y) =>
NullCheckEquals(x, y, (_x, _y) => _x.Equals(_y));
@@ -29,13 +35,19 @@ namespace mbts.utils {
public static IComparer wrap(this IComparer inner_comparer, Func selector) =>
Comparer.Create((a, b) => inner_comparer.Compare(a == null ? default : selector(a), b == null ? default : selector(b)));
+ public static IComparer to_nullable(this IComparer comparer) where T : struct =>
+ Comparer.Create(nullable_comparison(comparer.Compare));
+
+ public static IComparer reverse(this IComparer comparer) =>
+ Comparer.Create((a, b) => comparer.Compare(b, a));
+
class NonGenericComparerWrapper : IComparer {
readonly IComparer _comparer;
public NonGenericComparerWrapper(IComparer comparer) => _comparer = comparer;
public int Compare(object x, object y) =>
- _comparer.Compare(ObjectHelper.try_convert(x), ObjectHelper.try_convert(y));
+ _comparer.Compare(ConvertUtils.try_convert(x), ConvertUtils.try_convert(y));
}
#endregion
}
diff --git a/src/client/spark/core/GlobalExtensions/ObjectHelper.cs b/src/client/spark_core/utils/ConvertUtils.cs
similarity index 79%
rename from src/client/spark/core/GlobalExtensions/ObjectHelper.cs
rename to src/client/spark_core/utils/ConvertUtils.cs
index 4fe0923a6..d8d9b259b 100644
--- a/src/client/spark/core/GlobalExtensions/ObjectHelper.cs
+++ b/src/client/spark_core/utils/ConvertUtils.cs
@@ -1,9 +1,5 @@
-using mbts.ui.utility;
-
-namespace System
-{
- public static class ObjectHelper
- {
+namespace System {
+ public static class ConvertUtils {
public static object try_convert(Type type, object obj) {
try_convert(type, obj, out object result);
return result;
@@ -20,7 +16,7 @@ namespace System
result = obj;
return true;
} else if (type.IsEnum && obj is string) {
- result = EnumHelper.try_parse(type, obj.ToString());
+ result = try_parse_enum(type, obj.ToString());
return true;
} else if (type.IsNullable()) {
return try_convert(type.GetGenericArguments()[0], obj, out result);
@@ -85,6 +81,17 @@ namespace System
return rv;
}
+ public static object try_parse_enum(Type enum_type, string value, bool ignore_case = true) {
+ if (!enum_type.IsEnum) throw new ArgumentException("Must an enum type.", nameof(enum_type));
+ Array vals = Enum.GetValues(enum_type);
+ var str_comp = ignore_case ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
+ foreach (object v in vals) {
+ if (string.Equals(v.ToString(), value, str_comp))
+ return v;
+ }
+ return Activator.CreateInstance(enum_type);
+ }
+
public static bool update_value_type(ref T field, T newval) where T : struct, IEquatable {
bool rv = field.Equals(newval);
field = newval;
diff --git a/src/client/spark/core/Exceptions/ExceptionAssert.cs b/src/client/spark_core/utils/Exceptions/ExceptionAssert.cs
similarity index 100%
rename from src/client/spark/core/Exceptions/ExceptionAssert.cs
rename to src/client/spark_core/utils/Exceptions/ExceptionAssert.cs
diff --git a/src/client/spark/core/Exceptions/ExceptionBuilder.cs b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs
similarity index 100%
rename from src/client/spark/core/Exceptions/ExceptionBuilder.cs
rename to src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs
diff --git a/src/client/spark_core/utils/GlobalExtensions.cs b/src/client/spark_core/utils/GlobalExtensions.cs
index b872b32ae..0f231a633 100644
--- a/src/client/spark_core/utils/GlobalExtensions.cs
+++ b/src/client/spark_core/utils/GlobalExtensions.cs
@@ -19,6 +19,9 @@ namespace mbts {
}
return sb.ToString();
}
+ public static bool iequals(this string str, string comparand) =>
+ string.Equals(str, comparand, StringComparison.CurrentCultureIgnoreCase);
+
public static T choose(this Random r, IEnumerable range) {
var index = r.Next(0, range.Count());
return range.Skip(index).First();
diff --git a/src/client/spark/core/GlobalExtensions/TypeExtensions.cs b/src/client/spark_core/utils/TypeExtensions.cs
similarity index 100%
rename from src/client/spark/core/GlobalExtensions/TypeExtensions.cs
rename to src/client/spark_core/utils/TypeExtensions.cs
diff --git a/src/client/spark_excel/ExcelAddin.cs b/src/client/spark_excel/ExcelAddin.cs
new file mode 100644
index 000000000..60e03aa99
--- /dev/null
+++ b/src/client/spark_excel/ExcelAddin.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Reflection;
+
+using System.IO;
+using System.Security.Policy;
+using System.Diagnostics;
+
+using ExcelDna.Integration;
+using ExcelDna.IntelliSense;
+using ExcelDna.Logging;
+
+namespace bts.excel
+{
+ public class TestMethod
+ {
+ [ExcelFunction]
+ static public string bts_excel_test_string(string x) { return "Hello " + x; }
+ [ExcelFunction]
+ static public object bts_excel_test_int(int x) { return x; }
+ [ExcelFunction]
+ static public object bts_excel_test_long(long x) { return x; }
+ }
+
+ [System.Runtime.InteropServices.ComVisible(true)]
+ public class ContextTeardown : ExcelComAddIn
+ {
+ private api.core.ServiceContext _context;
+ public ContextTeardown(api.core.ServiceContext context)
+ {
+ _context = context;
+ }
+ //This is called on application shutdown
+ public override void OnBeginShutdown(ref Array custom)
+ {
+ _context.Dispose();
+ _context = null;
+ }
+ }
+
+ [System.Runtime.InteropServices.ComVisible(true)]
+ public class ExcelAddin : IExcelAddIn
+ {
+ public void AutoClose()
+ {
+ //don't do anything here, it's only called when the addin is removed, not on shutdown
+ IntelliSenseServer.Uninstall();
+ }
+ public void AutoOpen() //This is called on EXCEL startup, when the addin is loaded
+ {
+ Trace.Listeners.Add(new LogDisplayTraceListener("bts"));
+ IntelliSenseServer.Install();
+ ExcelIntegration.RegisterUnhandledExceptionHandler(ex => ex.ToString());
+
+ load_assemblies();
+ ExcelComAddInHelper.LoadComAddIn(new ContextTeardown(APIDispatch.service_context.Value));
+ }
+
+ private void load_assemblies()
+ {
+ var config = System.Configuration.ConfigurationManager.AppSettings["load_assemblies"];
+ if (config != null)
+ {
+ var asses = config.Split(new char[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
+ foreach (var ass in asses)
+ Utilities.bts_load_assembly(ass);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark_excel/Properties/AssemblyInfo.cs b/src/client/spark_excel/Properties/AssemblyInfo.cs
new file mode 100644
index 000000000..95ebd4d2e
--- /dev/null
+++ b/src/client/spark_excel/Properties/AssemblyInfo.cs
@@ -0,0 +1,17 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+[assembly: InternalsVisibleTo("spark")]
+[assembly: InternalsVisibleTo("spark_core")]
+[assembly: InternalsVisibleTo("sparkcmd")]
+[assembly: InternalsVisibleTo("spark_test")]
+
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("b319f835-7390-47e5-8093-461ed0dfce63")]
diff --git a/src/client/spark_excel/Properties/ExcelDna.Build.props b/src/client/spark_excel/Properties/ExcelDna.Build.props
new file mode 100644
index 000000000..0f536a88f
--- /dev/null
+++ b/src/client/spark_excel/Properties/ExcelDna.Build.props
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+ false
+ true
+
+
+
+ 64
+
+
+
+
+
+ false
+
+
+ -packed
+
+
+
diff --git a/src/client/spark_excel/extensions/EnumParser.cs b/src/client/spark_excel/extensions/EnumParser.cs
new file mode 100644
index 000000000..63773890e
--- /dev/null
+++ b/src/client/spark_excel/extensions/EnumParser.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Linq;
+
+namespace bts.excel.extensions
+{
+ public static class EnumParser
+ {
+ public static T ToEnum(this string val, T default_val = default(T)) where T : struct, IConvertible, IComparable
+ {
+ val = val ?? string.Empty;
+ T eval;
+ if (!Enum.TryParse(val, true, out eval))
+ {
+ string[] names = Enum.GetNames(typeof(T));
+ val = names.FirstOrDefault(x => x.ToLower().Contains(val));
+ if(val != null)
+ Enum.TryParse(val, true, out eval);
+
+ if (eval.CompareTo(default(T)) == 0 && default_val.CompareTo(default(T)) != 0)
+ eval = default_val;
+ }
+ return eval;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/spark_excel/extensions/OrderService_Excel.cs b/src/client/spark_excel/extensions/OrderService_Excel.cs
new file mode 100644
index 000000000..399369e46
--- /dev/null
+++ b/src/client/spark_excel/extensions/OrderService_Excel.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Concurrent;
+using System.Linq;
+using ExcelDna.Integration;
+
+using bts.api.admin;
+using bts.excel;
+using bts.excel.extensions;
+using bts.excel.rtd;
+using Newtonsoft.Json;
+
+
+namespace bts.api.orderman
+{
+ public partial class OrderService_Excel
+ {
+ readonly static Lazy _users = new Lazy(() => locate(), true);
+ readonly static Lazy _admin = new Lazy(() => locate(), true);
+
+
+ [ExcelFunction(Category = "BTS", Description = "Cancel an Order by Order ID", IsMacroType = true)]
+ public static object spark_orderservice_cancel_order(long order_id)
+ {
+ var resp = _service.Value.cancel_order(new Cancel() { OrderKey = Convert.ToUInt32(order_id) });
+ return parse_response(resp);
+ }
+
+ [ExcelFunction(Category = "BTS", Description = "Update an Order by Order ID", IsMacroType = true)]
+ public static object spark_orderservice_update_order(long order_id, double price, long quantity)
+ {
+ var resp = _service.Value.update_order(new Update() { OrderKey = Convert.ToUInt32(order_id), Price = price, Quantity = Convert.ToUInt32(quantity) });
+ return parse_response(resp);
+ }
+
+ [ExcelFunction(Category = "BTS", Description = "Send an Order to Spark via security_key", IsMacroType = true)]
+ public static object spark_orderservice_send_order_key(
+ [ExcelArgument("Required. Only send the order if > last")] long local_order_id,
+ [ExcelArgument("Required. Security key")] long security_key,
+ [ExcelArgument("Required. Side BUY or SELL")] string side,
+ [ExcelArgument("Required. User")] string user,
+ [ExcelArgument("Required. Account")] string account,
+ [ExcelArgument("Required. Price")] double price,
+ [ExcelArgument("Required. Quantity")] long quantity,
+ [ExcelArgument("Required. OrderType (Limit, Stop, Stop_Limit, Iceberg) - Default Limit")] string order_type,
+ [ExcelArgument("OPTIONAL. Order Params JSON (\"stop_price\" : 51.88)")] string order_params = null,
+
+ [ExcelArgument("OPTIONAL. (DAY,GTC,IOC) - Default DAY")] string time_in_force = null,
+ [ExcelArgument("OPTIONAL. (YES,NO) - Default YES")] string manual_order_indicator = null,
+ [ExcelArgument("OPTIONAL. (1,2,3,4) - Default 1")] string cti_code = null,
+ [ExcelArgument("OPTIONAL. (CUSTOMER,FIRM) - Default FIRM")] string customer_or_firm = null)
+ {
+ if (local_order_id <= _local_order_id)
+ return "local_order_id must be greater than " + _local_order_id;
+ Create cr = new Create();
+ cr.NewOrder = new OrderDefinition()
+ {
+ SecurityKey = Convert.ToUInt32(security_key),
+ Side = EnumParser.ToEnum