Compare commits

..
Author SHA1 Message Date
John Colvin fbb4dd6e1f chore: Move 'Order' classes into Model/Trading dir 2022-07-08 23:42:23 -04:00
John Colvin f977b0fdd0 fix (ui): Validate width/height before updating DragRectAdorner 2022-07-08 23:42:22 -04:00
John Colvin a3968bd35b ui: Add theme picker ui and stock dark theme 2022-07-08 23:42:22 -04:00
John Colvin 2b94a29963 chore: Clean up ui settings classes
* Move most settings files into new dir 'Model/Settings'
* Conform code style to our current practices
2022-07-08 14:44:57 -04:00
John Colvin 4b8abc2005 fix: Add null-check
A null-ref exception surfaced when running client w/ low bandwidth
2022-07-08 13:11:50 -04:00
John Colvin 2627264eea ui: Speed up expand/collapse animation in settings dialogs 2022-07-08 13:11:50 -04:00
John Colvin 2c7186275f chore (refactor): Move synth mgmt settings classes into sep files 2022-07-08 10:27:45 -04:00
John Colvin a4d8cd9dfc fix: Gather individual win settings on dispatcher thread
In practice, window-states live on their respective dispatcher threads.
Window settings factories shouldn't be expected to be thread-safe.
2022-07-07 02:35:06 -04:00
John Colvin ed4be2f1dd fix (vs ui): Don't clip vs time sched ui 2022-07-07 02:14:02 -04:00
John Colvin cd6d504f06 ui (vs grid settings): Constrain window height 2022-07-07 00:35:56 -04:00
John Colvin e68d37f24d build (client cpp): Remove ZERO_CHECK.vcxproj from spark_client.sln
The new cmake generates ZERO_CHECK.proj instead, which doesn't need to be
included in the sln
2022-07-06 10:05:21 -04:00
taha afzal 43cba548f4 Adding some details to the logs to track order flow 2022-06-24 15:05:15 -04:00
taha afzal 772910ffe5 Fixing filled qty's fractional part not being filled on the server 2022-06-23 14:38:57 -05:00
John Colvin 767179caf7 chore (man fills): Format qty w/ sec metadata config 2022-06-23 14:38:57 -05:00
John Colvin ee4a9150b8 refactor (man fills): Rename 'size' members 'quantity' 2022-06-23 14:24:04 -05:00
John Colvin 58914fa703 chore: Replace remaining refs to uint 'filled' fn w/ double impl 2022-06-23 14:24:04 -05:00
John Colvin ba40e7044a fix (ladder, preemptive): Fix typo in _fmt_mkt_depth_item
Bugs (fixed):
   * The _fmt_mkt_depth_item fn potentially will return the result of the
     delegate.ToString(), instead of invoking the delegate and returning the
     result
2022-06-23 14:10:15 -05:00
John Colvin 010d0073fe chore: Set BTC qty display config defaults 2022-06-23 02:05:23 -05:00
John Colvin 40210ce42e chore: Remove unnecessary price_display config default 2022-06-23 01:35:22 -05:00
John Colvin 59cdafba21 fix: Don't cast manual fill qty to uint 2022-06-23 01:22:09 -05:00
John Colvin fe6226baa5 ui (reconcile rep): Match all undefined positions
Now, all positions without real non-zero quantities are considered matches
2022-06-23 01:19:27 -05:00
John Colvin 45987c7652 feat: Show fractional qty in orderbook Filled col 2022-06-22 16:04:24 -05:00
John Colvin a18ce97fb4 feat (ui): Support fractional qtys for order entry 2022-06-22 15:38:38 -05:00
John Colvin 13d5080bbc refactor: Shorten modify/revert cmd prop names
Also consolidate modify_price/qty fns into single modify_order fn
2022-06-22 15:38:38 -05:00
John Colvin 9f07a36d1d refactor: Move order-update-desc fn into OrderUtils for gen use 2022-06-22 15:38:38 -05:00
John Colvin bc2e7f428a chore: Add formal/consistent numeric exceptions/messages 2022-06-22 15:38:38 -05:00
John Colvin 53bfbdd349 fix: Sync 'has_value' prop for qty param
Bugs (fixed):
   * Can't tick qty up/down in the orderbook right panel (clicking the
   button has no discernible effect)
2022-06-22 15:38:38 -05:00
John Colvin 174eac9a59 refactor: Move OrderParamsVM into own file
OrderBookVM.cs was (and frankly still is) massive.  Too massive
2022-06-22 15:38:38 -05:00
John Colvin 3775b86d9e refactor: Rename 'size_' props 'quantity_' to be consistent 2022-06-22 15:38:38 -05:00
John Colvin 5e1c6d6209 fix build (windows): Don't include stdint-uintn.h on windows 2022-06-22 15:38:37 -05:00
taha afzal 0d0fb036ab EmMDListener now get_open_orders and logging the open orders 2022-06-22 15:38:37 -05:00
taha afzal f8668802ab Fixing oder updates on fractional quantity orders (just a few lines) 2022-06-22 15:38:37 -05:00
taha afzal c22a1382a1 Fractional qtys now work on the server (need some client side work) 2022-06-22 15:38:37 -05:00
Taha Afzal 941a0d91cc Enabled Combo report to show fractions (ITradeLow had size of type int) 2022-06-13 20:01:47 -04:00
153 changed files with 8722 additions and 7484 deletions

No files matched your search

-10
View File
@@ -12,8 +12,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sparkcmd", "src\client\spar
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_core", "src\client\spark_core\spark_core.csproj", "{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZERO_CHECK", "build\ZERO_CHECK.vcxproj", "{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_sdk", "src\client\spark_sdk\spark_sdk.csproj", "{6963C314-83C4-4667-B0D0-C2F7AE208C29}"
ProjectSection(ProjectDependencies) = postProject
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40} = {9FA60215-26AF-3EB7-AB89-D4F4B126EF40}
@@ -69,14 +67,6 @@ Global
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.Release|x64.Build.0 = Release|x64
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.Build.0 = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.ActiveCfg = Debug|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.Build.0 = Debug|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.ActiveCfg = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.Build.0 = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.ActiveCfg = Debug|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.Build.0 = Debug|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.MinSizeRel|x64.ActiveCfg = Release|x64
@@ -13,28 +13,21 @@ namespace mbts.spark {
bts.Log.Gen.info($"SingleVolSurfaceTimeSource cons vs_id:{vs_id}");
_vs_id = vs_id;
_bb = bb;
_bb.subscribe(SparkTags.VolSurfaceStandardServerTimeTag);
_bb.data_callback += _on_data;
_read_and_publish();
_bb.timer_callback += _on_timer;
}
private void _on_data(object tag, object data) {
if (tag.Equals(SparkTags.VolSurfaceStandardServerTimeTag)) {
_read_and_publish();
}
}
private void _read_and_publish() {
VolSurfaceStandardTime vs_time = _bb.read_state(SparkTags.VolSurfaceStandardServerTimeTag);
if (vs_time != null) {
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{vs_time.ToString()}");
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), vs_time);
private void _on_timer() {
if (DateTime.Now - _last_publish_time >= _publish_period) {
_last_publish_time = DateTime.Now;
VolSurfaceStandardTime time = VolSurfaceStandardTime.get_local_default();
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{time.ToString()}");
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), time);
}
}
#region IDisposable
public void Dispose() {
_bb.data_callback -= _on_data;
_bb.timer_callback -= _on_timer;
}
#endregion
}
@@ -96,10 +96,6 @@ namespace mbts.spark {
var vs_usage_sub = _analytics_service.subscribei_volsurface_usage()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(_on_vs_usage_update);
var vs_time_sub = _analytics_service.subscribei_volsurface_time()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(_on_vs_time);
_subs.Add(vs_time_sub);
_subs.Add(vs_sub);
_subs.Add(vs_usage_sub);
_subs.Add(new AnalyticsParametersManager(bus, _analytics_service));
@@ -167,17 +163,6 @@ namespace mbts.spark {
_init_vss(to_publish.Keys);
}
void _on_vs_time(bts.api.core.Update<VolSurfaceServerTimeImmutable, int> update) {
if (update.all.Count() != 1) {
return;
}
VolSurfaceStandardTime vs_time =
new VolSurfaceStandardTime(update.all.ElementAt(0).UtcTime.Seconds);
bts.Log.Gen.info(String.Format("VSBusManager._on_vs_time vs_time: {0}",
vs_time.ToString()));
_bb.post(SparkTags.VolSurfaceStandardServerTimeTag, vs_time);
}
private void _init_vss(IEnumerable<int> vs_ids) {
// we consider every vs in the db as "activated" which might prove to be expensive
// (will take care of it later)
@@ -17,13 +17,6 @@ namespace mbts.analytics {
this.server_time_utc = server_time_utc;
}
public VolSurfaceStandardTime(long seconds_from_epoch) {
timezone = TimeZoneInfo.Local;
server_time_utc =
DateTimeOffset.FromUnixTimeSeconds(seconds_from_epoch).DateTime;
server_time = server_time_utc.ToLocalTime();
}
public static VolSurfaceStandardTime get_local_default() {
DateTime local_rounded = VolSurfaceUtilityFunctions.round_time_mins(
DateTime.Now, VolSurfaceConstants.vol_time_sample_mins);
@@ -19,8 +19,9 @@ namespace mbts.analytics
/// with default inputs
public static VolSurfaceInput sync_input_expirations_to_master_list(VolSurfaceInput vs_input, IEnumerable<VolSurfaceExpiration> system_exp_list)
{
HashSet<VolSurfaceExpiration> vs_exp_map = new HashSet<VolSurfaceExpiration>(vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)),
sys_exp_map = new HashSet<VolSurfaceExpiration>(system_exp_list);
var vs_exp_map = vs_input.surface_parameters.curve_parameters_map
.empty_if_null().Select(t => t.Item1).ToHashSet();
var sys_exp_map = system_exp_list.ToHashSet();
sys_exp_map.difference(
vs_exp_map,
out HashSet<VolSurfaceExpiration> deleted_exps,
@@ -674,7 +674,7 @@ namespace mbts.analytics {
var vol_time = VolSurfaceCoreFunctions.compute_vol_time(
vs_input, vs_standard_time.server_time_utc);
var exp_inp_data = vs_nonvol_input.get_option_exp_input();
foreach (var (exp, curve_params) in vs_input.surface_parameters.curve_parameters_map) {
foreach (var (exp, curve_params) in vs_input.surface_parameters.curve_parameters_map.empty_if_null()) {
var time_shift = DoubleHelper.CoerceNaN(curve_params.core_parameters.time_shift);
_compute_option_bizt(
vs_input, exp, vol_time, time_shift, out var biz_yrs, out var biz_days_per_yr);
@@ -1,31 +1,31 @@
using bts.utils;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.spark {
[ProtoContract]
class GlobalAlertSettings : IEquatable<GlobalAlertSettings> {
[ProtoMember(1)]
TradeAlert[] _trade_alerts;
public GlobalAlertSettings() { }
public GlobalAlertSettings(IEnumerable<TradeAlert> trade_alerts) =>
_trade_alerts = trade_alerts.ToArray();
public IReadOnlyList<TradeAlert> trade_alerts => _trade_alerts ?? Array.Empty<TradeAlert>();
public bool Equals(GlobalAlertSettings other) =>
other != null &&
trade_alerts.SequenceEqual(other.trade_alerts);
public override bool Equals(object obj) =>
Equals(obj as GlobalAlertSettings);
public override int GetHashCode() =>
EqualityComparer.auto_phase(trade_alerts);
}
}
using bts.utils;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.spark {
[ProtoContract]
class GlobalAlertSettings : IEquatable<GlobalAlertSettings> {
[ProtoMember(1)]
TradeAlert[] _trade_alerts;
public GlobalAlertSettings() { }
public GlobalAlertSettings(IEnumerable<TradeAlert> trade_alerts) =>
_trade_alerts = trade_alerts.ToArray();
public IReadOnlyList<TradeAlert> trade_alerts => _trade_alerts ?? Array.Empty<TradeAlert>();
public bool Equals(GlobalAlertSettings other) =>
other != null &&
trade_alerts.SequenceEqual(other.trade_alerts);
public override bool Equals(object obj) =>
Equals(obj as GlobalAlertSettings);
public override int GetHashCode() =>
EqualityComparer.auto_phase(trade_alerts);
}
}
@@ -1,88 +1,88 @@
using bts;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.settings {
public interface ISavedWindowFactory {
Task<IShellWindow> restore(WindowState window);
}
[Export(typeof(ISavedWindowFactory))]
public class WindowFactory : ISavedWindowFactory {
IShellWindowMigrationRule[] _compat;
[ImportingConstructor]
public WindowFactory([ImportMany] IShellWindowMigrationRule[] migration) {
_compat = migration;
}
[Import]
public ObservableCollection<IShellModule> modules { get; set; }
public Task<IShellWindow> restore(WindowState window) {
Log.Ui.info("Loading window '{0}'".fmt(window.title));
bool changed;
int count = 0;
do {
count++;
changed = apply_compatability_migrations(ref window);
} while (count < 100 && changed);
if (count == 100) {
Log.Persist.error("Error: Window state migration still changing after 100 iterations. Please check IShellWindowMigrationRule logic.");
}
return restore(window.owner, window.app_data, window.position);
}
/// When we apply the migration changes to a window we stop as soon as one "matches" and updates the state
/// Since it's possible that we have multiple levels of migration we run this function until the data stops changing (or 100 iterations)
/// ex: If change the data format twice from A to B to C then we would write 2 IShellWindowMigration instances.
/// Starting in state A one of the _compat tests changes to state B. Now we need to re-run
/// the migrations because state B will match a different rule and be converted to state C.
private bool apply_compatability_migrations(ref WindowState window) {
foreach (var test in _compat) {
try {
if (test.apply(ref window)) {
return true;
}
} catch (Exception e) {
Log.Persist.error("Exception running compat rule {0}.\n{1}".fmt(test.GetType().Name, e.ToString()));
}
}
return false;
}
private async Task<IShellWindow> restore(string owner_name, byte[] state, WindowPosition windowPosition) {
IShellModule owner = modules.empty_if_null().SingleOrDefault(m => m.key() == owner_name);
if (owner == null) {
Log.Ui.warn("Could not locate module '{0}'".fmt(owner_name));
return null;
}
try {
Task<IShellWindow> task = owner.create(new MemoryStream(state));
if (task != null) {
IShellWindow window = await task;
if (window != null) {
window.set_start_position(windowPosition);
Log.Ui.info($"Restoring window {owner_name} - {window.diagnostic_name()}.");
}
return window;
}
} catch (Exception e) {
Log.Ui.error("Failure to re-create window for module {0}. Error: {1}".fmt(owner_name, e.Message));
}
return null;
}
}
}
using bts;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.settings {
public interface ISavedWindowFactory {
Task<IShellWindow> restore(WindowState window);
}
[Export(typeof(ISavedWindowFactory))]
public class WindowFactory : ISavedWindowFactory {
IShellWindowMigrationRule[] _compat;
[ImportingConstructor]
public WindowFactory([ImportMany] IShellWindowMigrationRule[] migration) {
_compat = migration;
}
[Import]
public ObservableCollection<IShellModule> modules { get; set; }
public Task<IShellWindow> restore(WindowState window) {
Log.Ui.info("Loading window '{0}'".fmt(window.title));
bool changed;
int count = 0;
do {
count++;
changed = apply_compatability_migrations(ref window);
} while (count < 100 && changed);
if (count == 100) {
Log.Persist.error("Error: Window state migration still changing after 100 iterations. Please check IShellWindowMigrationRule logic.");
}
return restore(window.owner, window.app_data, window.position);
}
/// When we apply the migration changes to a window we stop as soon as one "matches" and updates the state
/// Since it's possible that we have multiple levels of migration we run this function until the data stops changing (or 100 iterations)
/// ex: If change the data format twice from A to B to C then we would write 2 IShellWindowMigration instances.
/// Starting in state A one of the _compat tests changes to state B. Now we need to re-run
/// the migrations because state B will match a different rule and be converted to state C.
private bool apply_compatability_migrations(ref WindowState window) {
foreach (var test in _compat) {
try {
if (test.apply(ref window)) {
return true;
}
} catch (Exception e) {
Log.Persist.error("Exception running compat rule {0}.\n{1}".fmt(test.GetType().Name, e.ToString()));
}
}
return false;
}
private async Task<IShellWindow> restore(string owner_name, byte[] state, WindowPosition windowPosition) {
IShellModule owner = modules.empty_if_null().SingleOrDefault(m => m.key() == owner_name);
if (owner == null) {
Log.Ui.warn("Could not locate module '{0}'".fmt(owner_name));
return null;
}
try {
Task<IShellWindow> task = owner.create(new MemoryStream(state));
if (task != null) {
IShellWindow window = await task;
if (window != null) {
window.set_start_position(windowPosition);
Log.Ui.info($"Restoring window {owner_name} - {window.diagnostic_name()}.");
}
return window;
}
} catch (Exception e) {
Log.Ui.error("Failure to re-create window for module {0}. Error: {1}".fmt(owner_name, e.Message));
}
return null;
}
}
}
@@ -1,86 +1,113 @@
using bts;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.IO;
using System.Linq;
namespace mbts.ui.settings {
public interface ISettingsCollector {
// Get the save state for every open window
IEnumerable<WindowState> get_window_state();
WindowState get_window_state(IShellWindow window);
IEnumerable<ModuleState> get_module_state();
WindowPosition get_launcher_state();
}
[Export(typeof(ISettingsCollector))]
class SettingsCollector : ISettingsCollector {
WindowManager _wm;
ILauncher _launcher;
[ImportingConstructor]
public SettingsCollector(WindowManager wm, ILauncher launcher) {
_wm = wm;
_launcher = launcher;
}
[Import]
public ObservableCollection<IShellModule> modules { get; set; }
IWindowsInterop _interop => _wm;
public IEnumerable<WindowState> get_window_state() {
foreach (var window in _wm.list_windows()) {
// Check that the window is still open since we might be iterating asyncronously
if (_wm.contains(window)) {
var state = get_window_state(window);
if (state != null) {
yield return state;
}
}
}
}
public IEnumerable<ModuleState> get_module_state() {
//Note: I'm assuming that the list of modules is stable and I don't have to protect against it changing here
foreach (var module in modules.OfTypeSafe<IPersistShellModule>()) {
MemoryStream out_stream = new MemoryStream();
module.get_state(out_stream);
yield return new ModuleState() {
name = module.key(),
app_data = out_stream.ToArray(),
};
}
}
public WindowPosition get_launcher_state() {
return _launcher.get_position();
}
public WindowState get_window_state(IShellWindow window) {
try {
if (window == null || window.Owner == null) return null;
MemoryStream out_stream = new MemoryStream();
window.GetState(out_stream);
var pos = _interop.GetPosition(window);
var state = new WindowState() {
owner = window.Owner.key(),
app_data = out_stream.ToArray(),
position = pos,
title = string.IsNullOrEmpty(pos.custom_title) ? window.Title : pos.custom_title
};
return state;
} catch (Exception e) {
Log.Ui.error("Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
}
return null;
}
}
}
using bts;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace mbts.ui.settings {
public interface ISettingsCollector {
// Get the save state for every open window
Task<List<WindowState>> get_window_state();
Task<WindowState> get_window_state(IShellWindow window);
IEnumerable<ModuleState> get_module_state();
WindowPosition get_launcher_state();
}
[Export(typeof(ISettingsCollector))]
class SettingsCollector : ISettingsCollector {
WindowManager _wm;
ILauncher _launcher;
[ImportingConstructor]
public SettingsCollector(WindowManager wm, ILauncher launcher) {
_wm = wm;
_launcher = launcher;
}
[Import]
public ObservableCollection<IShellModule> modules { get; set; }
[Import]
public IShellThreadFactory thread_factory { get; set; }
IWindowsInterop _interop => _wm;
public async Task<List<WindowState>> get_window_state() {
var windows = _wm.list_windows();
var rv = new List<WindowState>(windows.Count);
foreach (var window in windows) {
// Check that the window is still open since we might be iterating asyncronously
if (_wm.contains(window)) {
var state = await get_window_state(window);
if (state != null) {
rv.Add(state);
}
}
}
return rv;
}
public IEnumerable<ModuleState> get_module_state() {
//Note: I'm assuming that the list of modules is stable and I don't have to protect against it changing here
foreach (var module in modules.OfTypeSafe<IPersistShellModule>()) {
MemoryStream out_stream = new MemoryStream();
module.get_state(out_stream);
yield return new ModuleState() {
name = module.key(),
app_data = out_stream.ToArray(),
};
}
}
public WindowPosition get_launcher_state() {
return _launcher.get_position();
}
public async Task<WindowState> get_window_state(IShellWindow window) {
try {
if (window == null || window.Owner == null) return null;
Dispatcher dispatcher = null;
if (window is ISlowWindow) {
var tf = thread_factory;
if (tf is not null) {
var thread_id = (window as ISharedWindow)?.thread_id;
dispatcher = tf.get_dispatcher(thread_id);
if (dispatcher is null) {
Log.Gen.error(
$"Unable to get window state for '{window.Title}.' " +
$"Didn't find dispatcher for thread {thread_id}.");
return null;
}
}
}
var pos = _interop.GetPosition(window);
var state = new WindowState() {
owner = window.Owner.key(),
app_data = dispatcher is null ?
(await dispatcher.InvokeAsync(serialize)) : serialize(),
position = pos,
title = string.IsNullOrEmpty(pos.custom_title) ? window.Title : pos.custom_title
};
return state;
byte[] serialize() {
using var ms = new MemoryStream();
window.GetState(ms);
return ms.ToArray();
}
} catch (Exception e) {
Log.Ui.error("Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
}
return null;
}
}
}
@@ -1,95 +1,95 @@
using bts.shell.pnl;
using bts.utils;
using mbts.ui.settings;
using System;
using System.Collections.Generic;
namespace bts.settings {
interface ISettingsMigrationRule<T> {
bool apply(T settings, out T new_settings);
}
// Migration rules of type ISettingsMigrationRule<T>, where 'T' is a common type, such as GridSettings,
// should be exposed through explicitly named interfaces that inherit ISettingsMigrationRule<T>.
// This avoids magic const names in the MEF import/export contracts, which would otherwise be needed to
// determine the various windows to which such rules apply.
interface IFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPNLSettingsMigrationRule : ISettingsMigrationRule<PNLSettings> { }
interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IReconcileReportMigrationRule : ISettingsMigrationRule<GridSettings> { }
static class SettingsMigrationHelper {
public static bool apply<T>(T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, out T new_settings) {
bool applied = false;
foreach (var r in migration_rules) {
if (r.apply(settings, out var migrated)) {
settings = migrated;
applied = true;
}
}
new_settings = applied ? settings : default;
return applied;
}
public static void apply_quiet<T>(ref T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules) {
if (apply(settings, migration_rules, out var new_settings))
settings = new_settings;
}
public static ISettingsMigrationRule<T> merge<T>(this IEnumerable<ISettingsMigrationRule<T>> rules) =>
new MergeWrapper<T>(rules);
public static ISettingsMigrationRule<TOuter> wrap<TInner, TOuter>(this ISettingsMigrationRule<TInner> rule, IImmutableProperty<TOuter, TInner> propi) =>
new SelectorWrapper<TInner, TOuter>(rule, propi.get, propi.set);
public static ISettingsMigrationRule<TOuter> wrap<TInner, TOuter>(this ISettingsMigrationRule<TInner> rule, Func<TOuter, TInner> get, Func<TOuter, TInner, TOuter> set) =>
new SelectorWrapper<TInner, TOuter>(rule, get, set);
class MergeWrapper<T> : ISettingsMigrationRule<T> {
readonly IEnumerable<ISettingsMigrationRule<T>> _rules;
public MergeWrapper(IEnumerable<ISettingsMigrationRule<T>> rules) =>
_rules = rules;
public bool apply(T settings, out T new_settings) {
bool applied = false;
foreach (var r in _rules) {
if (r.apply(settings, out var migrated)) {
settings = migrated;
applied = true;
}
}
new_settings = applied ? settings : default;
return applied;
}
}
class SelectorWrapper<TInner, TOuter> : ISettingsMigrationRule<TOuter> {
readonly ISettingsMigrationRule<TInner> _rule;
readonly Func<TOuter, TInner> _get;
readonly Func<TOuter, TInner, TOuter> _set;
public SelectorWrapper(ISettingsMigrationRule<TInner> rule, Func<TOuter, TInner> get, Func<TOuter, TInner, TOuter> set) {
_rule = rule;
_get = get;
_set = set;
}
public bool apply(TOuter settings, out TOuter new_settings) {
if (settings != null) {
var ival = _get(settings);
if (_rule.apply(ival, out var new_ival)) {
new_settings = _set(settings, new_ival);
return true;
}
}
new_settings = default;
return false;
}
}
}
}
using bts.shell.pnl;
using bts.utils;
using mbts.ui.settings;
using System;
using System.Collections.Generic;
namespace bts.settings {
interface ISettingsMigrationRule<T> {
bool apply(T settings, out T new_settings);
}
// Migration rules of type ISettingsMigrationRule<T>, where 'T' is a common type, such as GridSettings,
// should be exposed through explicitly named interfaces that inherit ISettingsMigrationRule<T>.
// This avoids magic const names in the MEF import/export contracts, which would otherwise be needed to
// determine the various windows to which such rules apply.
interface IFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPNLSettingsMigrationRule : ISettingsMigrationRule<PNLSettings> { }
interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IReconcileReportMigrationRule : ISettingsMigrationRule<GridSettings> { }
static class SettingsMigrationHelper {
public static bool apply<T>(T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, out T new_settings) {
bool applied = false;
foreach (var r in migration_rules) {
if (r.apply(settings, out var migrated)) {
settings = migrated;
applied = true;
}
}
new_settings = applied ? settings : default;
return applied;
}
public static void apply_quiet<T>(ref T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules) {
if (apply(settings, migration_rules, out var new_settings))
settings = new_settings;
}
public static ISettingsMigrationRule<T> merge<T>(this IEnumerable<ISettingsMigrationRule<T>> rules) =>
new MergeWrapper<T>(rules);
public static ISettingsMigrationRule<TOuter> wrap<TInner, TOuter>(this ISettingsMigrationRule<TInner> rule, IImmutableProperty<TOuter, TInner> propi) =>
new SelectorWrapper<TInner, TOuter>(rule, propi.get, propi.set);
public static ISettingsMigrationRule<TOuter> wrap<TInner, TOuter>(this ISettingsMigrationRule<TInner> rule, Func<TOuter, TInner> get, Func<TOuter, TInner, TOuter> set) =>
new SelectorWrapper<TInner, TOuter>(rule, get, set);
class MergeWrapper<T> : ISettingsMigrationRule<T> {
readonly IEnumerable<ISettingsMigrationRule<T>> _rules;
public MergeWrapper(IEnumerable<ISettingsMigrationRule<T>> rules) =>
_rules = rules;
public bool apply(T settings, out T new_settings) {
bool applied = false;
foreach (var r in _rules) {
if (r.apply(settings, out var migrated)) {
settings = migrated;
applied = true;
}
}
new_settings = applied ? settings : default;
return applied;
}
}
class SelectorWrapper<TInner, TOuter> : ISettingsMigrationRule<TOuter> {
readonly ISettingsMigrationRule<TInner> _rule;
readonly Func<TOuter, TInner> _get;
readonly Func<TOuter, TInner, TOuter> _set;
public SelectorWrapper(ISettingsMigrationRule<TInner> rule, Func<TOuter, TInner> get, Func<TOuter, TInner, TOuter> set) {
_rule = rule;
_get = get;
_set = set;
}
public bool apply(TOuter settings, out TOuter new_settings) {
if (settings != null) {
var ival = _get(settings);
if (_rule.apply(ival, out var new_ival)) {
new_settings = _set(settings, new_ival);
return true;
}
}
new_settings = default;
return false;
}
}
}
}
@@ -1,171 +1,153 @@
using mbts.spark;
using mbts.utils;
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
namespace mbts.persist {
interface IWindowSettingsManager<T> where T : class {
T instance_settings { get; set; }
T default_settings { get; }
event Action<T> instance_settings_changed;
IObservable<T> subscribe_default();
Task save_default_settings(T value);
IWindowSettingsManagerNonShared<T> as_non_shared();
}
/// <summary>
/// An implementation of IWindowSettingsManager that uses a clone of the actual default settings;
/// provides a convenient way to avoid problems that arise from sharing a single default settings object among multiple window instances.
/// </summary>
interface IWindowSettingsManagerNonShared<T> : IWindowSettingsManager<T>, IDisposable where T : class { }
class WindowSettingsManager<T> : IWindowSettingsManager<T> where T : class {
readonly UserSettingsHub _hub;
readonly Func<UserSettings, T> _get;
readonly Func<UserSettings, T, UserSettings> _set;
T _instance_settings;
public WindowSettingsManager(UserSettingsHub hub, T instance_settings, Func<UserSettings, T> get, Func<UserSettings, T, UserSettings> set) {
_hub = hub;
_instance_settings = instance_settings;
_get = get;
_set = set;
}
public T instance_settings {
get => _instance_settings;
set {
_instance_settings = value;
instance_settings_changed?.Invoke(value);
}
}
public T default_settings => _get(_hub.current);
public event Action<T> instance_settings_changed;
public async Task save_default_settings(T value) =>
await _hub.save_default(_set(_hub.current, value));
public IObservable<T> subscribe_default() =>
_hub.subscribe_default_settings().Select(_get).DistinctUntilChanged();
public IWindowSettingsManagerNonShared<T> as_non_shared() =>
new NonSharedWrapper(this);
class NonSharedWrapper : IWindowSettingsManagerNonShared<T> {
readonly IWindowSettingsManager<T> _wsm;
readonly BehaviorSubject<T> _default_subject;
IDisposable _dispose;
public NonSharedWrapper(IWindowSettingsManager<T> wsm) {
_wsm = wsm;
_default_subject = new BehaviorSubject<T>(_wsm.default_settings);
_dispose = wsm.subscribe_default().Subscribe(s =>
_default_subject.OnNext(default_settings = MiscUtils.clone_proto(s)));
}
public T instance_settings {
get => _wsm.instance_settings;
set => _wsm.instance_settings = value;
}
public T default_settings { get; private set; }
public event Action<T> instance_settings_changed {
add => _wsm.instance_settings_changed += value;
remove => _wsm.instance_settings_changed -= value;
}
public async Task save_default_settings(T value) =>
await _wsm.save_default_settings(value);
public IObservable<T> subscribe_default() =>
_default_subject.AsObservable();
public IWindowSettingsManagerNonShared<T> as_non_shared() =>
new NonSharedWrapper(_wsm);
public void Dispose() => Disposable.dispose(ref _dispose);
}
public class DisconnectedImpl : IWindowSettingsManager<T> {
readonly BehaviorSubject<T> _default_settings_subject;
T _instance_settings, _default_settings;
public DisconnectedImpl(T settings) : this(settings, settings) { }
public DisconnectedImpl(T instance_settings, T default_settings) {
_instance_settings = instance_settings;
_default_settings = default_settings;
_default_settings_subject = new BehaviorSubject<T>(default_settings);
}
public T instance_settings {
get => _instance_settings;
set {
if (!Equals(_instance_settings, value)) {
_instance_settings = value;
instance_settings_changed?.Invoke(value);
}
}
}
public T default_settings {
get => _default_settings;
set {
if (!Equals(_default_settings, _default_settings)) {
_default_settings = value;
_default_settings_subject.OnNext(value);
}
}
}
public event Action<T> instance_settings_changed;
public IWindowSettingsManagerNonShared<T> as_non_shared() => new NonSharedWrapper(this);
public Task save_default_settings(T value) {
default_settings = value;
return Task.CompletedTask;
}
public IObservable<T> subscribe_default() => _default_settings_subject;
}
}
static class WindowSettingsManagerExtensions {
/// <summary>
/// Returns an observable sequence of the settings object used by a particular window.
/// <para/>Note: 'Instance' settings take priority over 'default' settings. While the former is present, any changes to the latter will be ignored.
/// </summary>
public static IObservable<T> subscribe_current<T>(this IWindowSettingsManager<T> wsm) where T : class =>
Observable.CombineLatest(
Observable.FromEvent<Action<T>, T>(cb => wsm.instance_settings_changed += cb, cb => wsm.instance_settings_changed -= cb)
.StartWith(wsm.instance_settings),
wsm.subscribe_default(),
(i, d) => i ?? d
).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;
}
}
using mbts.spark;
using mbts.utils;
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
namespace mbts.persist {
interface IWindowSettingsManager<T> where T : class {
T instance_settings { get; set; }
T default_settings { get; }
event Action<T> instance_settings_changed;
IObservable<T> subscribe_default();
Task save_default_settings(T value);
IWindowSettingsManagerNonShared<T> as_non_shared();
}
/// <summary>
/// An implementation of IWindowSettingsManager that uses a clone of the actual default settings;
/// provides a convenient way to avoid problems that arise from sharing a single default settings object among multiple window instances.
/// </summary>
interface IWindowSettingsManagerNonShared<T> : IWindowSettingsManager<T>, IDisposable where T : class { }
class WindowSettingsManager<T> : IWindowSettingsManager<T> where T : class {
readonly UserSettingsHub _hub;
readonly Func<UserSettings, T> _get;
readonly Func<UserSettings, T, UserSettings> _set;
T _instance_settings;
public WindowSettingsManager(UserSettingsHub hub, T instance_settings, Func<UserSettings, T> get, Func<UserSettings, T, UserSettings> set) {
_hub = hub;
_instance_settings = instance_settings;
_get = get;
_set = set;
hub.request_clear_instance_settings += () => instance_settings = null;
}
public T instance_settings {
get => _instance_settings;
set {
_instance_settings = value;
instance_settings_changed?.Invoke(value);
}
}
public T default_settings => _get(_hub.current);
public event Action<T> instance_settings_changed;
public async Task save_default_settings(T value) =>
await _hub.save_default(_set(_hub.current, value));
public IObservable<T> subscribe_default() =>
_hub.subscribe_default_settings().Select(_get).DistinctUntilChanged();
public IWindowSettingsManagerNonShared<T> as_non_shared() =>
new NonSharedWrapper(this);
class NonSharedWrapper : IWindowSettingsManagerNonShared<T> {
readonly IWindowSettingsManager<T> _wsm;
readonly BehaviorSubject<T> _default_subject;
IDisposable _dispose;
public NonSharedWrapper(IWindowSettingsManager<T> wsm) {
_wsm = wsm;
_default_subject = new BehaviorSubject<T>(_wsm.default_settings);
_dispose = wsm.subscribe_default().Subscribe(s =>
_default_subject.OnNext(default_settings = MiscUtils.clone_proto(s)));
}
public T instance_settings {
get => _wsm.instance_settings;
set => _wsm.instance_settings = value;
}
public T default_settings { get; private set; }
public event Action<T> instance_settings_changed {
add => _wsm.instance_settings_changed += value;
remove => _wsm.instance_settings_changed -= value;
}
public async Task save_default_settings(T value) =>
await _wsm.save_default_settings(value);
public IObservable<T> subscribe_default() =>
_default_subject.AsObservable();
public IWindowSettingsManagerNonShared<T> as_non_shared() =>
new NonSharedWrapper(_wsm);
public void Dispose() => Disposable.dispose(ref _dispose);
}
public class DisconnectedImpl : IWindowSettingsManager<T> {
readonly BehaviorSubject<T> _default_settings_subject;
T _instance_settings, _default_settings;
public DisconnectedImpl(T settings) : this(settings, settings) { }
public DisconnectedImpl(T instance_settings, T default_settings) {
_instance_settings = instance_settings;
_default_settings = default_settings;
_default_settings_subject = new BehaviorSubject<T>(default_settings);
}
public T instance_settings {
get => _instance_settings;
set {
if (!Equals(_instance_settings, value)) {
_instance_settings = value;
instance_settings_changed?.Invoke(value);
}
}
}
public T default_settings {
get => _default_settings;
set {
if (!Equals(_default_settings, _default_settings)) {
_default_settings = value;
_default_settings_subject.OnNext(value);
}
}
}
public event Action<T> instance_settings_changed;
public IWindowSettingsManagerNonShared<T> as_non_shared() => new NonSharedWrapper(this);
public Task save_default_settings(T value) {
default_settings = value;
return Task.CompletedTask;
}
public IObservable<T> subscribe_default() => _default_settings_subject;
}
}
static class WindowSettingsManagerExtensions {
/// <summary>
/// Returns an observable sequence of the settings object used by a particular window.
/// <para/>Note: 'Instance' settings take priority over 'default' settings. While the former is present, any changes to the latter will be ignored.
/// </summary>
public static IObservable<T> subscribe_current<T>(this IWindowSettingsManager<T> wsm) where T : class =>
Observable.CombineLatest(
Observable.FromEvent<Action<T>, T>(cb => wsm.instance_settings_changed += cb, cb => wsm.instance_settings_changed -= cb)
.StartWith(wsm.instance_settings),
wsm.subscribe_default(),
(i, d) => i ?? d
).Where(v => v != null)
.DistinctUntilChanged();
public static T current_settings<T>(this IWindowSettingsManager<T> wsm) where T : class =>
wsm.instance_settings ?? wsm.default_settings;
}
}
@@ -0,0 +1,172 @@
#nullable enable
namespace mbts.persist {
using bts;
using bts.api.core;
using bts.api.persistence;
using bts.spark;
using Spark.Core.Protobuf;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
public class SettingsPersistenceModel : IPersist, IUserPersist {
readonly PersistenceService _persist;
readonly ErrorReporter _errors;
readonly string _user;
public SettingsPersistenceModel(
string user, PersistenceService persist, ErrorReporter errors) {
_user = user;
_persist = persist;
_errors = errors;
}
public Task set<T>(string ns, string key, T value) {
return _persist.store_async(new StoreRequest() {
Ns = _user_ns(ns),
Record = {
new Record() {
Key = key,
Value = ProtobufSerializationHelper.serialize_to_byte_string(value)
}
}
});
}
public Task clear(string ns, string key) {
return _persist.remove_async(new RemoveRequest() {
Ns = _user_ns(ns),
Key = { key }
});
}
public async Task<T?> get<T>(string ns, string key) {
var ret = await _persist.retrieve_async(new RetrieveRequest() {
Ns = _user_ns(ns),
Key = { key }
});
_check_error(ret, ns, key, out var empty);
if (empty) {
return default;
}
return ProtobufSerializationHelper.deserialize<T>(ret.value.Record.Single().Value);
}
public async Task<T[]> get_many<T>(string ns, string key) {
var ret = await _persist.retrieve_async(new RetrieveRequest() {
Ns = _user_ns(ns),
Key = { key }
});
_check_error(ret, ns, key, out bool empty);
if (empty) {
return Array.Empty<T>();
}
return ProtobufSerializationHelper.deserialize_many<T>(
ret.value.Record.Single().Value.ToByteArray());
}
public async Task<IEnumerable<PersistResult<T>>> query<T>(string ns, string pattern) {
var regex = new Regex(pattern);
var results = await _persist.retrieve_all_async(
new RetrieveAllRequest() {
Ns = _user_ns(ns)
});
_check_error(results, ns, string.Empty, out bool empty);
if (empty) {
return Enumerable.Empty<PersistResult<T>>();
}
return results.value.Record
.Where(r => regex.IsMatch(r.Key))
.Select(r => new PersistResult<T>() {
user = _user,
ns = ns,
key = r.Key,
value = ProtobufSerializationHelper.deserialize<T>(r.Value)
}).ToList();
}
public IDisposable subscribe<T>(
string ns, string pattern, Action<IEnumerable<PersistResult<T>>> callback) =>
subscribe<T>(ns, pattern).Subscribe(callback);
public IObservable<IEnumerable<PersistResult<T>>> subscribe<T>(string ns, string pattern) {
var ctx = SynchronizationContext.Current ??
throw new InvalidOperationException("Current SynchronizationContext is null");
var re = new Regex(pattern);
return _persist
.subscribe_ns(_user_ns(ns))
.Select(update =>
update.added
.Where(item => re.IsMatch(item.Key))
.Select(item => new PersistResult<T>() {
user = _user,
ns = ns,
key = item.Key,
value = ProtobufSerializationHelper.deserialize<T>(item.Value)
}))
.SubscribeOn(ctx);
}
public void Dispose() =>
GC.SuppressFinalize(this);
string _user_ns(string ns) =>
$"{_user}#{ns}";
void _check_error(Result<RetrieveResponse> result, string ns, string key, out bool empty) {
if (result.success) {
switch (result.value.Result) {
case RetrieveResponse.Types.Result.EmptyNs:
case RetrieveResponse.Types.Result.NoSuchNs:
case RetrieveResponse.Types.Result.NoSuchKey:
empty = true;
return;
case RetrieveResponse.Types.Result.EmptyKey:
case RetrieveResponse.Types.Result.DuplicateKey:
_errors?.report_error(
$"Invalid Key {result} '{key}'",
"Requested Invalid Settings Key",
MessageBoxImage.Information);
empty = true;
return;
default:
case RetrieveResponse.Types.Result.Ok:
empty = false;
return;
}
} else {
_errors?.report_error(
$"There was an error communicating with the settings server: {result.error_message}",
"Failed to retrieve settings from the server");
empty = true;
}
}
}
[Export(typeof(IPersist))]
public class UISettings : SettingsPersistenceModel {
[ImportingConstructor]
public UISettings([Import("settings")] PersistenceService persist, ErrorReporter err)
: base("all_users", persist, err) { }
}
[Export(typeof(IUserPersist))]
public class UserUISettings : SettingsPersistenceModel {
public UserUISettings(
uint user_id, [Import("settings")] PersistenceService persist, ErrorReporter err)
: base($"User {user_id}", persist, err) { }
[ImportingConstructor]
public UserUISettings(
Lazy<UserTuple> user, [Import("settings")] PersistenceService persist, ErrorReporter err)
: this(user.Value.id, persist, err) { }
}
}
@@ -0,0 +1,44 @@
#nullable enable
namespace mbts.spark {
using bts.utils;
using System;
interface ISettingsProfile<T> {
uint id { get; }
string? name { get; }
T? value { get; }
SecurityCriteria? security_criteria { get; }
}
readonly struct SettingsProfile<T> : IEquatable<SettingsProfile<T>> where T : class, IEquatable<T> {
public static readonly Func<SettingsProfile<T>, uint> key_fn = ns => ns.id;
public readonly uint id;
public readonly string? name;
public readonly T? value;
public readonly SecurityCriteria? security_criteria;
public SettingsProfile(uint id, string? name, T? value, SecurityCriteria? security_criteria = null) {
this.id = id;
this.name = name;
this.value = value;
this.security_criteria = security_criteria;
}
public SettingsProfile<T> with(uint? id = null, string? name = null, T? value = null, SecurityCriteria? security_criteria = null) =>
new(id ?? this.id, name ?? this.name, value ?? this.value, security_criteria ?? this.security_criteria);
public bool Equals(SettingsProfile<T> other) =>
id == other.id &&
name == other.name &&
value.safe_equals(other.value) &&
security_criteria.safe_equals(other.security_criteria);
public override bool Equals(object? obj) =>
obj is SettingsProfile<T> other && Equals(other);
public override int GetHashCode() =>
id.GetHashCode();
}
}
@@ -1,73 +1,73 @@
using mbts.persist;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.tests {
// Stub persistance store for shell unit tests
public class TestPersist : IPersist, IUserPersist {
public Dictionary<string, Dictionary<string, object>> Values = new Dictionary<string, Dictionary<string, object>>();
public Task set<T>(string ns, string key, T value) {
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
try {
Values[ns][key] = value;
source.TrySetResult(null);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task clear(string ns, string key) {
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
try {
Values[ns].Remove(key);
source.TrySetResult(null);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task<T> get<T>(string ns, string key) {
TaskCompletionSource<T> source = new TaskCompletionSource<T>();
try {
T result = (T)Values[ns][key];
source.TrySetResult(result);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task<T[]> get_many<T>(string ns, string key) {
var source = new TaskCompletionSource<T[]>();
try {
source.TrySetResult((T[])Values[ns][key]);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public async Task<IEnumerable<Tuple<T, DateTime>>> get_history<T>(string ns, string key) {
var res = await get<T>(ns, key);
return new Tuple<T, DateTime>[] { Tuple.Create(res, DateTime.Today) };
}
public Task<IEnumerable<PersistResult<T>>> query<T>(string ns, string pattern) {
throw new NotImplementedException();
}
public IDisposable subscribe<T>(string ns, string pattern, Action<IEnumerable<PersistResult<T>>> callback) {
throw new NotImplementedException();
}
public void Dispose() { }
}
}
using mbts.persist;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.tests {
// Stub persistance store for shell unit tests
public class TestPersist : IPersist, IUserPersist {
public Dictionary<string, Dictionary<string, object>> Values = new Dictionary<string, Dictionary<string, object>>();
public Task set<T>(string ns, string key, T value) {
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
try {
Values[ns][key] = value;
source.TrySetResult(null);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task clear(string ns, string key) {
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
try {
Values[ns].Remove(key);
source.TrySetResult(null);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task<T> get<T>(string ns, string key) {
TaskCompletionSource<T> source = new TaskCompletionSource<T>();
try {
T result = (T)Values[ns][key];
source.TrySetResult(result);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public Task<T[]> get_many<T>(string ns, string key) {
var source = new TaskCompletionSource<T[]>();
try {
source.TrySetResult((T[])Values[ns][key]);
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
public async Task<IEnumerable<Tuple<T, DateTime>>> get_history<T>(string ns, string key) {
var res = await get<T>(ns, key);
return new Tuple<T, DateTime>[] { Tuple.Create(res, DateTime.Today) };
}
public Task<IEnumerable<PersistResult<T>>> query<T>(string ns, string pattern) {
throw new NotImplementedException();
}
public IDisposable subscribe<T>(string ns, string pattern, Action<IEnumerable<PersistResult<T>>> callback) {
throw new NotImplementedException();
}
public void Dispose() { }
}
}
@@ -1,195 +1,242 @@
using bts.shell.pnl;
using Google.Protobuf.WellKnownTypes;
using mbts.ui.settings;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
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>
[ProtoContract]
class UserSettings {
public static UserSettings factory_defaults =>
new UserSettings {
_ladder = LadderSettings.Default,
_notification = NotificationSettings.Default,
_market_view_grid = bts.shell.market_view.MarketViewSettings.DefaultGridSettings,
_fills_grid = bts.shell.fills.FillsSettings.DefaultGridSettings,
_time_and_sales_grid = bts.shell.time_and_sales.TimeAndSalesSettings.DefaultGridSettings,
_synthetic_management_grid = bts.shell.SyntheticManagementWindowFactory.StartupData.DefaultGridSettings,
_reconcile_report_grid = Spark.Trading.ReconcileReportSettings.Default().grid,
_order_book_grid = bts.shell.orderbook.OrderBookStartupData.DefaultGrid
};
[ProtoMember(1)]
LadderSettings _ladder;
[ProtoMember(11)]
readonly LadderSettingsProfile[] _ladder_profiles;
/// When Profiles Are Deleted, ladders that were using that profile shall copy the profile's settings to a local profile.
/// Therefor:
/// Deleted profile ids must never be reused.
/// If they were reused, consider an unloaded workspace with ladders that were using the deleted profile.
/// If such a workspace was reloaded after a new profile was saved with the deleted one's id, the ladders using that deleted profile would suddenly be using the new profile.
/// To Prevent IDs From Being Recycled:
/// The last profile id is stored in the protobuf (<see cref="_last_ladder_profile_id"/>).
/// Anytime a profile is added, it shall use <see cref="next_ladder_profile_id"/>.
[ProtoMember(12)]
uint _last_ladder_profile_id;
// removing NotificationSettings these from proto-serialization, since they are disabled by default for now.
// This way, when they are enabled, there won't be any backwards compatability issues to worry about, as no clients will have persisted them yet.
NotificationSettings _notification;
[ProtoMember(5)]
GridSettings _market_view_grid;
[ProtoMember(6)]
GridSettings _time_and_sales_grid;
[ProtoMember(7)]
GridSettings _fills_grid;
[ProtoMember(8)]
GridSettings _synthetic_management_grid;
[ProtoMember(14)]
GridSettings _reconcile_report_grid;
[ProtoMember(9)]
bts.shell.orderbook.OrderBookGridSettings _order_book_grid;
[ProtoMember(10)]
PNLSettings _pnl;
[ProtoMember(13)]
GlobalAlertSettings _alerts;
public UserSettings() { }
public UserSettings(LadderSettingsProfile[] ladder_profiles) =>
_ladder_profiles = ladder_profiles;
public LadderSettings ladder => _ladder ?? (_ladder = LadderSettings.Default);
public IReadOnlyList<LadderSettingsProfile> ladder_profiles => _ladder_profiles ?? Array.Empty<LadderSettingsProfile>();
public uint next_ladder_profile_id => _last_ladder_profile_id + 1;
public NotificationSettings notification => _notification ?? (_notification = NotificationSettings.Default);
public GridSettings market_view_grid => _market_view_grid ?? (_market_view_grid = bts.shell.market_view.MarketViewSettings.DefaultGridSettings);
public GridSettings time_and_sales_grid => _time_and_sales_grid ?? (_time_and_sales_grid = GridSettings.Default.with(bts.shell.time_and_sales.TimeAndSalesSettings.DefaultColumns.all));
public GridSettings fills_grid => _fills_grid ?? (_fills_grid = bts.shell.fills.FillsSettings.DefaultGridSettings);
public GridSettings synthetic_management_grid => _synthetic_management_grid ?? (_synthetic_management_grid = bts.shell.SyntheticManagementWindowFactory.StartupData.DefaultGridSettings);
public GridSettings reconcile_report_grid => _reconcile_report_grid ??= Spark.Trading.ReconcileReportSettings.Default().grid;
public PNLSettings pnl => _pnl ?? (_pnl = PNLSettings.Default);
public bts.shell.orderbook.OrderBookGridSettings order_book_grid => _order_book_grid ?? (_order_book_grid = bts.shell.orderbook.OrderBookStartupData.Default.grid_settings_wrapper());
public GlobalAlertSettings alerts => _alerts ?? (_alerts = new GlobalAlertSettings());
public UserSettings with(LadderSettings ladder = null,
LadderSettingsProfile[] ladder_profiles = null,
NotificationSettings notification = null,
GridSettings provided_market_view_gridsettings = null,
GridSettings time_and_sales = null,
GridSettings provided_fills_gridsettings = null,
GridSettings provided_synthetic_management_gridsettings = null,
GridSettings reconcile_report_grid = null,
PNLSettings pnl = null,
bts.shell.orderbook.OrderBookGridSettings order_book_grid = null,
GlobalAlertSettings alerts = null) {
var us = new UserSettings(ladder_profiles ?? _ladder_profiles) {
_ladder = ladder ?? _ladder,
_notification = notification ?? _notification,
_market_view_grid = provided_market_view_gridsettings ?? _market_view_grid,
_time_and_sales_grid = time_and_sales ?? _time_and_sales_grid,
_fills_grid = provided_fills_gridsettings ?? _fills_grid,
_synthetic_management_grid = provided_synthetic_management_gridsettings ?? _synthetic_management_grid,
_reconcile_report_grid = reconcile_report_grid ?? _reconcile_report_grid,
_pnl = pnl ?? _pnl,
_order_book_grid = order_book_grid ?? _order_book_grid,
_alerts = alerts ?? _alerts
};
us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault());
return us;
}
public static class FileExtensions {
public const string
GRID = "grid",
LADDER = "ladder",
PNL = "pnl";
}
}
// - currently all notification-triggers are in GridSettings
// - the SoundNotificationSettings below are used to disable/enable SoundNotifications
// - the ToastNotificationSettings below are used to disable/enable ToastNotifications, and adjust the flash-duration (if enabled).
// - since this is a new feature, the ability to quickly enable/disable both types of notifications may save us the trouble of having to redeploy,
// in the unfortunate event that a bug slipped through the cracks, or the performance impact is more significant than expected.
// TODO: maybe globalize notification settings?
[ProtoContract]
class NotificationSettings {
[ProtoMember(1)]
readonly SoundNotificationSettings _sound_notification;
[ProtoMember(2)]
readonly ToastNotificationSettings _toast_notification;
public NotificationSettings() { }
public NotificationSettings(SoundNotificationSettings sound_notification, ToastNotificationSettings toast_notification) {
_sound_notification = sound_notification;
_toast_notification = toast_notification;
}
public static NotificationSettings Default => new NotificationSettings(SoundNotificationSettings.Default, ToastNotificationSettings.Default);
public SoundNotificationSettings sound_notification => _sound_notification;
public ToastNotificationSettings toast_notification => _toast_notification;
}
[ProtoContract]
class SoundNotificationSettings {
[ProtoMember(1)]
readonly bool _enabled;
public SoundNotificationSettings() { }
public SoundNotificationSettings(bool enabled) =>
_enabled = enabled;
public static SoundNotificationSettings Default => new SoundNotificationSettings(true);
public bool enabled => _enabled;
}
[ProtoContract]
class ToastNotificationSettings {
// though it is possible to infer such Modes from Duration values (null = Disabled, max = ManualClose, otherwise Flash)
// this Mode enum makes the behavior very clear, and less likely to be misinterpretted down the road.
// (without this enum, the meaning of "duration = null," and "duration = 0 seconds," is debatable)
public enum Mode {
Disabled,
ManualClose,
Flash
}
public static ToastNotificationSettings Default =>
new ToastNotificationSettings(Mode.Flash, new Duration { Seconds = 5 }, 320);
[ProtoMember(1)]
readonly Mode _mode;
[ProtoMember(2)]
readonly Duration _duration;
[ProtoMember(3)]
readonly double _max_height;
public ToastNotificationSettings() { }
public ToastNotificationSettings(Mode mode, Duration duration, double max_height) {
_mode = mode;
_duration = duration;
_max_height = max_height;
}
public Mode mode => _mode;
public TimeSpan? duration => _mode == Mode.Flash ? _duration?.ToTimeSpan() ?? TimeSpan.FromSeconds(5) : new TimeSpan?();
public double max_height => _max_height;
}
}
#nullable enable
namespace mbts.spark {
using bts.shell;
using bts.shell.fills;
using bts.shell.market_view;
using bts.shell.orderbook;
using bts.shell.pnl;
using bts.shell.time_and_sales;
using bts.utils;
using Google.Protobuf.WellKnownTypes;
using mbts.ui.settings;
using ProtoBuf;
using Spark.Trading;
using System;
using System.Collections.Generic;
using System.Linq;
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>
[ProtoContract]
class UserSettings {
public static UserSettings factory_defaults =>
new() {
_ladder = LadderSettings.Default,
_notification = NotificationSettings.Default,
_market_view_grid = MarketViewSettings.DefaultGridSettings,
_fills_grid = FillsSettings.DefaultGridSettings,
_time_and_sales_grid = TimeAndSalesSettings.DefaultGridSettings,
_synthetic_management = SyntheticManagementSettings.default_grid_settings,
_reconcile_report = ReconcileReportSettings.Default().grid,
_order_book = OrderBookStartupData.DefaultGrid
};
[ProtoMember(1)]
LadderSettings? _ladder;
[ProtoMember(11)]
LadderSettingsProfile[]? _ladder_profiles;
/// When Profiles Are Deleted, ladders that were using that profile shall copy the profile's settings to a local profile.
/// Therefor:
/// Deleted profile ids must never be reused.
/// If they were reused, consider an unloaded workspace with ladders that were using the deleted profile.
/// If such a workspace was reloaded after a new profile was saved with the deleted one's id, the ladders using that deleted profile would suddenly be using the new profile.
/// To Prevent IDs From Being Recycled:
/// The last profile id is stored in the protobuf (<see cref="_last_ladder_profile_id"/>).
/// Anytime a profile is added, it shall use <see cref="next_ladder_profile_id"/>.
[ProtoMember(12)]
uint _last_ladder_profile_id;
// removing NotificationSettings these from proto-serialization, since they are disabled by default for now.
// This way, when they are enabled, there won't be any backwards compatability issues to worry about, as no clients will have persisted them yet.
NotificationSettings? _notification;
[ProtoMember(5)]
GridSettings? _market_view_grid;
[ProtoMember(6)]
GridSettings? _time_and_sales_grid;
[ProtoMember(7)]
GridSettings? _fills_grid;
[ProtoMember(8)]
GridSettings? _synthetic_management;
[ProtoMember(14)]
GridSettings? _reconcile_report;
[ProtoMember(9)]
OrderBookGridSettings? _order_book;
[ProtoMember(10)]
PNLSettings? _pnl;
[ProtoMember(13)]
GlobalAlertSettings? _alerts;
/// Actual settings may deviate from those of the theme <see cref="_last_picked_theme"/>, as
/// the user is free to change specific properties after selecting a theme.
[ProtoMember(15)]
string? _last_picked_theme;
public UserSettings() { }
public LadderSettings ladder =>
_ladder ??= LadderSettings.Default;
public IReadOnlyList<LadderSettingsProfile> ladder_profiles =>
_ladder_profiles ?? Array.Empty<LadderSettingsProfile>();
public uint next_ladder_profile_id =>
_last_ladder_profile_id + 1;
public NotificationSettings notification =>
_notification ??= NotificationSettings.Default;
public GridSettings market_view_grid =>
_market_view_grid ??= MarketViewSettings.DefaultGridSettings;
public GridSettings time_and_sales_grid =>
_time_and_sales_grid ??= GridSettings.Default.with(
TimeAndSalesSettings.DefaultColumns.all);
public GridSettings fills_grid =>
_fills_grid ??= FillsSettings.DefaultGridSettings;
public GridSettings synthetic_management_grid =>
_synthetic_management ??=
SyntheticManagementSettings.default_grid_settings;
public GridSettings reconcile_report_grid =>
_reconcile_report ??= ReconcileReportSettings.Default().grid ??
throw new InvalidOperationException();
public PNLSettings pnl =>
_pnl ??= PNLSettings.Default;
public OrderBookGridSettings order_book_grid =>
_order_book ??= OrderBookStartupData.Default.grid_settings_wrapper();
public GlobalAlertSettings alerts =>
_alerts ??= new GlobalAlertSettings();
public string? last_picked_theme => _last_picked_theme;
public UserSettings with(
LadderSettings? ladder = null,
LadderSettingsProfile[]? ladder_profiles = null,
NotificationSettings? notification = null,
GridSettings? market_view = null,
GridSettings? time_and_sales = null,
GridSettings? fills = null,
GridSettings? synthetic_management = null,
GridSettings? reconcile_report = null,
PNLSettings? pnl = null,
OrderBookGridSettings? order_book_grid = null,
GlobalAlertSettings? alerts = null,
Optional<string?> last_picked_theme = default) {
var us = new UserSettings() {
_ladder_profiles = ladder_profiles ?? _ladder_profiles,
_ladder = ladder ?? _ladder,
_notification = notification ?? _notification,
_market_view_grid = market_view ?? _market_view_grid,
_time_and_sales_grid = time_and_sales ?? _time_and_sales_grid,
_fills_grid = fills ?? _fills_grid,
_synthetic_management = synthetic_management ?? _synthetic_management,
_reconcile_report = reconcile_report ?? _reconcile_report,
_pnl = pnl ?? _pnl,
_order_book = order_book_grid ?? _order_book,
_alerts = alerts ?? _alerts,
_last_picked_theme = last_picked_theme.or(_last_picked_theme)
};
us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault());
return us;
}
public static class FileExtensions {
public const string
GRID = "grid",
LADDER = "ladder",
PNL = "pnl";
}
}
// - currently all notification-triggers are in GridSettings
// - the SoundNotificationSettings below are used to disable/enable SoundNotifications
// - the ToastNotificationSettings below are used to disable/enable ToastNotifications, and adjust the flash-duration (if enabled).
// - since this is a new feature, the ability to quickly enable/disable both types of notifications may save us the trouble of having to redeploy,
// in the unfortunate event that a bug slipped through the cracks, or the performance impact is more significant than expected.
// TODO: maybe globalize notification settings?
[ProtoContract]
class NotificationSettings {
[ProtoMember(1)]
readonly SoundNotificationSettings? _sound_notification;
[ProtoMember(2)]
readonly ToastNotificationSettings? _toast_notification;
public NotificationSettings() { }
public NotificationSettings(SoundNotificationSettings sound_notification, ToastNotificationSettings toast_notification) {
_sound_notification = sound_notification;
_toast_notification = toast_notification;
}
public static NotificationSettings Default => new NotificationSettings(SoundNotificationSettings.Default, ToastNotificationSettings.Default);
public SoundNotificationSettings? sound_notification => _sound_notification;
public ToastNotificationSettings? toast_notification => _toast_notification;
}
[ProtoContract]
class SoundNotificationSettings {
[ProtoMember(1)]
readonly bool _enabled;
public SoundNotificationSettings() { }
public SoundNotificationSettings(bool enabled) =>
_enabled = enabled;
public static SoundNotificationSettings Default => new(true);
public bool enabled => _enabled;
}
[ProtoContract]
class ToastNotificationSettings {
// though it is possible to infer such Modes from Duration values (null = Disabled, max = ManualClose, otherwise Flash)
// this Mode enum makes the behavior very clear, and less likely to be misinterpretted down the road.
// (without this enum, the meaning of "duration = null," and "duration = 0 seconds," is debatable)
public enum Mode {
Disabled,
ManualClose,
Flash
}
public static ToastNotificationSettings Default =>
new(Mode.Flash, new Duration { Seconds = 5 }, 320);
[ProtoMember(1)]
readonly Mode _mode;
[ProtoMember(2)]
readonly Duration? _duration;
[ProtoMember(3)]
readonly double _max_height;
public ToastNotificationSettings() { }
public ToastNotificationSettings(Mode mode, Duration duration, double max_height) {
_mode = mode;
_duration = duration;
_max_height = max_height;
}
public Mode mode => _mode;
public TimeSpan duration =>
_mode switch {
Mode.Flash => _duration?.ToTimeSpan() ?? TimeSpan.FromSeconds(5),
_ => new()
};
public double max_height => _max_height;
}
}
@@ -1,177 +1,226 @@
using bts;
using bts.settings;
using bts.shell.pnl;
using bts.utils;
using mbts.spark;
using mbts.ui.settings;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
namespace mbts.persist {
/// <summary>
/// Represents the top level of the persisted settings hierarchy.
/// One UserSettings object, which contains the defaults for every SparkWindow, can be read/written on the server by UISettingsHub.
/// </summary>
[Export(typeof(UserSettingsHub))]
class UserSettingsHub {
// do NOT CHANGE these consts, they represent a file path on the server
const string NAME_SPACE = "settings", DEFAULT_KEY = "default";
static readonly IImmutableProperty<UserSettings, GridSettings>
_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)),
_mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)),
_synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)),
_reconcile_report_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.reconcile_report_grid, (us, gs) => us.with(reconcile_report_grid: gs));
static readonly IImmutableProperty<UserSettings, PNLSettings>
_pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl));
readonly object _default_settings_lock = new object();
readonly BehaviorSubject<UserSettings> _default_settings_subject = new BehaviorSubject<UserSettings>(UserSettings.factory_defaults);
readonly IEnumerable<IFillsGridSettingsMigrationRule> _fills_migration_rules;
readonly IEnumerable<IMarketViewGridSettingsMigrationRule> _mview_migration_rules;
readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules;
readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules;
readonly IEnumerable<IReconcileReportMigrationRule> _reconcile_report_migration_rules;
readonly IUserPersist _persist;
UserSettings _default_settings;
[ImportingConstructor]
public UserSettingsHub(
IUserPersist persist,
[ImportMany] IEnumerable<IFillsGridSettingsMigrationRule> fills_migration_rules,
[ImportMany] IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules,
[ImportMany] IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules,
[ImportMany] IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules,
[ImportMany] IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules,
[ImportMany] IEnumerable<IReconcileReportMigrationRule> reconcile_report_migration_rules) {
//
_persist = persist;
_fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>();
_mview_migration_rules = mview_migration_rules ?? Enumerable.Empty<IMarketViewGridSettingsMigrationRule>();
_pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>();
_synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>();
_reconcile_report_migration_rules = reconcile_report_migration_rules.empty_if_null();
init();
async void init() {
UserSettings s;
try {
s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
if (s != null) {
var wrapped_rules = new[] {
_fills_migration_rules.merge().wrap(_fills_propi),
_mview_migration_rules.merge().wrap(_mview_propi),
_pnl_migration_rules.merge().wrap(_pnl_propi),
_synth_migration_rules.merge().wrap(_synth_propi),
_reconcile_report_migration_rules.merge().wrap(_reconcile_report_propi)
};
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
// TODO: move ladder sanitization logic into ISettingsMigrationRule
s.ladder.sanitize();
// ensure valid named ladder set (w/ distinct, non-zero ids)
var ladder_profile_map = new Dictionary<uint, LadderSettingsProfile>();
var unidentified_lps = new List<LadderSettingsProfile>();
foreach (var lp in s.ladder_profiles) {
lp.value.sanitize();
if (lp.id == 0) {
unidentified_lps.Add(lp);
} else ladder_profile_map[lp.id] = lp;
}
uint id = s.next_ladder_profile_id;
foreach (var lp in unidentified_lps) {
ladder_profile_map[id] = lp.with(id);
id++;
}
var sorted_lps = ladder_profile_map.Values.ToArray();
Array.Sort(sorted_lps, Comparer<uint>.Default.wrap<uint, LadderSettingsProfile>(lp => lp.id));
if (!sorted_lps.SequenceEqual(s.ladder_profiles))
await _persist.set(NAME_SPACE, DEFAULT_KEY, s = s.with(ladder_profiles: sorted_lps));
}
} 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);
}
lock (_default_settings_lock) {
initialized = true;
if (s != null)
_default_settings_subject.OnNext(_default_settings = s);
}
}
}
// indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
public bool initialized { get; private set; }
internal UserSettings current {
get {
lock (_default_settings_lock)
return _default_settings ?? UserSettings.factory_defaults;
}
}
/// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
/// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
public IObservable<UserSettings> subscribe_default_settings() => _default_settings_subject.AsObservable();
public IWindowSettingsManager<GridSettings> create_fills_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_fills_migration_rules,
_fills_propi);
public IWindowSettingsManager<GridSettings> create_mview_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_mview_migration_rules,
_mview_propi);
public IWindowSettingsManager<PNLSettings> create_pnl_settings_manager(PNLSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_pnl_migration_rules,
_pnl_propi);
public IWindowSettingsManager<GridSettings> create_synth_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_synth_migration_rules,
_synth_propi);
public IWindowSettingsManager<GridSettings> create_reconcile_report_settings_manager(
GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_reconcile_report_migration_rules,
_reconcile_report_propi);
public async Task save_default(UserSettings value) {
// notify observers before persisting so the changes are reflected immediately in the ui
lock (_default_settings_lock) {
_default_settings_subject.OnNext(_default_settings = value);
}
await _persist_async();
}
IWindowSettingsManager<T> _create_settings_manager<T>(T instance_settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, IImmutableProperty<UserSettings, T> propi) where T : class {
if (instance_settings != null && migration_rules.merge().apply(instance_settings, out var new_settings))
instance_settings = new_settings;
return new WindowSettingsManager<T>(this, instance_settings, propi.get, propi.set);
}
async Task _persist_async() {
try {
await _persist.set(NAME_SPACE, DEFAULT_KEY, _default_settings);
} catch (Exception ex) {
Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}");
}
}
}
}
using bts;
using bts.settings;
using bts.shell.pnl;
using bts.utils;
using mbts.spark;
using mbts.ui.settings;
using Spark.Settings;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
namespace mbts.persist {
/// <summary>
/// Represents the top level of the persisted settings hierarchy.
/// One UserSettings object, which contains the defaults for every SparkWindow, can be read/written on the server by UISettingsHub.
/// </summary>
[Export(typeof(UserSettingsHub))]
class UserSettingsHub {
// do NOT CHANGE these consts, they represent a file path on the server
const string NAME_SPACE = "settings", DEFAULT_KEY = "default";
static readonly IImmutableProperty<UserSettings, GridSettings>
_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(fills: gs)),
_mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(market_view: gs)),
_synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(synthetic_management: gs)),
_reconcile_report_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.reconcile_report_grid, (us, gs) => us.with(reconcile_report: gs));
static readonly IImmutableProperty<UserSettings, PNLSettings>
_pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl));
readonly object _default_settings_lock = new object();
readonly BehaviorSubject<UserSettings> _default_settings_subject = new BehaviorSubject<UserSettings>(UserSettings.factory_defaults);
// A 'settings theme' is activated by updating the default settings object, and clearing all
// 'instance' settings so existing windows adopt the new theme (i.e., the new defaults).
readonly IEnumerable<IFillsGridSettingsMigrationRule> _fills_migration_rules;
readonly IEnumerable<IMarketViewGridSettingsMigrationRule> _mview_migration_rules;
readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules;
readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules;
readonly IEnumerable<IReconcileReportMigrationRule> _reconcile_report_migration_rules;
readonly IUserPersist _persist;
readonly Dictionary<string, UserSettingsTheme> _themes;
UserSettings _default_settings;
IDisposable _theme_op = null;
[ImportingConstructor]
public UserSettingsHub(
IUserPersist persist,
[ImportMany] IEnumerable<IFillsGridSettingsMigrationRule> fills_migration_rules,
[ImportMany] IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules,
[ImportMany] IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules,
[ImportMany] IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules,
[ImportMany] IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules,
[ImportMany] IEnumerable<IReconcileReportMigrationRule> reconcile_report_migration_rules,
[ImportMany] IEnumerable<UserSettingsTheme> themes) {
//
_persist = persist;
_fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>();
_mview_migration_rules = mview_migration_rules ?? Enumerable.Empty<IMarketViewGridSettingsMigrationRule>();
_pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>();
_synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>();
_reconcile_report_migration_rules = reconcile_report_migration_rules.empty_if_null();
_themes = themes.ToDictionaryCrushed(t => t.name);
init();
async void init() {
UserSettings s;
try {
s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
if (s != null) {
var wrapped_rules = new[] {
_fills_migration_rules.merge().wrap(_fills_propi),
_mview_migration_rules.merge().wrap(_mview_propi),
_pnl_migration_rules.merge().wrap(_pnl_propi),
_synth_migration_rules.merge().wrap(_synth_propi),
_reconcile_report_migration_rules.merge().wrap(_reconcile_report_propi)
};
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
// TODO: move ladder sanitization logic into ISettingsMigrationRule
s.ladder.sanitize();
// ensure valid named ladder set (w/ distinct, non-zero ids)
var ladder_profile_map = new Dictionary<uint, LadderSettingsProfile>();
var unidentified_lps = new List<LadderSettingsProfile>();
foreach (var lp in s.ladder_profiles) {
lp.value.sanitize();
if (lp.id == 0) {
unidentified_lps.Add(lp);
} else ladder_profile_map[lp.id] = lp;
}
uint id = s.next_ladder_profile_id;
foreach (var lp in unidentified_lps) {
ladder_profile_map[id] = lp.with(id);
id++;
}
var sorted_lps = ladder_profile_map.Values.ToArray();
Array.Sort(sorted_lps, Comparer<uint>.Default.wrap<uint, LadderSettingsProfile>(lp => lp.id));
if (!sorted_lps.SequenceEqual(s.ladder_profiles))
await _persist.set(NAME_SPACE, DEFAULT_KEY, s = s.with(ladder_profiles: sorted_lps));
}
} 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);
}
lock (_default_settings_lock) {
initialized = true;
if (s != null)
_default_settings_subject.OnNext(_default_settings = s);
}
}
}
public event Action request_clear_instance_settings {
add {
lock (_default_settings_lock) {
_request_clear_instance_settings += value;
}
}
remove {
lock (_default_settings_lock) {
_request_clear_instance_settings -= value;
}
}
}
event Action _request_clear_instance_settings;
// indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
public bool initialized { get; private set; }
public IEnumerable<UserSettingsTheme> themes =>
_themes.Values;
internal UserSettings current {
get {
lock (_default_settings_lock)
return _default_settings ?? UserSettings.factory_defaults;
}
}
/// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
/// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
public IObservable<UserSettings> subscribe_default_settings() => _default_settings_subject.AsObservable();
public IWindowSettingsManager<GridSettings> create_fills_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_fills_migration_rules,
_fills_propi);
public IWindowSettingsManager<GridSettings> create_mview_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_mview_migration_rules,
_mview_propi);
public IWindowSettingsManager<PNLSettings> create_pnl_settings_manager(PNLSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_pnl_migration_rules,
_pnl_propi);
public IWindowSettingsManager<GridSettings> create_synth_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_synth_migration_rules,
_synth_propi);
public IWindowSettingsManager<GridSettings> create_reconcile_report_settings_manager(
GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_reconcile_report_migration_rules,
_reconcile_report_propi);
public async Task save_default(UserSettings value, bool clear_instance_settings = false) {
// * Notify observers before persisting so the changes are reflected immediately in the ui.
// * If instance settings are to be cleared, don't clear them until the new defaults are
// ready. We want to avoid the case where windows w/ instance settings consume cpu
// loading the original defaults, just to load the new defaults immediately after that.
lock (_default_settings_lock) {
Disposable.dispose(ref _theme_op);
if (clear_instance_settings) {
clear_instance_async().ignore();
}
_default_settings_subject.OnNext(_default_settings = value);
}
await _persist_async();
async Task clear_instance_async() {
var cts = new CancellationTokenSource();
_theme_op = Disposable.Create(() => cts.Cancel());
var next = await _default_settings_subject.Skip(1).FirstOrDefaultAsync();
if (!cts.IsCancellationRequested) {
_request_clear_instance_settings?.Invoke();
}
}
}
IWindowSettingsManager<T> _create_settings_manager<T>(T instance_settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, IImmutableProperty<UserSettings, T> propi) where T : class {
if (instance_settings != null && migration_rules.merge().apply(instance_settings, out var new_settings))
instance_settings = new_settings;
var wsm = new WindowSettingsManager<T>(this, instance_settings, propi.get, propi.set);
lock (_default_settings_lock) {
request_clear_instance_settings += clear_instance_settings;
}
return wsm;
void clear_instance_settings() {
wsm.instance_settings = null;
}
}
async Task _persist_async() {
try {
await _persist.set(NAME_SPACE, DEFAULT_KEY, _default_settings);
} catch (Exception ex) {
Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}");
}
}
}
}
@@ -0,0 +1,36 @@
#nullable enable
namespace Spark.Settings {
using mbts.spark;
using System.Composition;
class UserSettingsTheme {
public UserSettingsTheme() {
name = string.Empty;
value = new();
}
public UserSettingsTheme(string name, UserSettings value) {
this.name = name;
this.value = value;
}
public string name { get; }
public UserSettings value { get; }
}
class ExportedThemes {
[Export]
public UserSettingsTheme light_theme =>
new("Light", UserSettings.factory_defaults);
[Export]
public UserSettingsTheme dark_theme =>
new("Dark", UserSettings.factory_defaults.with(
market_view: bts.shell.market_view.MarketViewSettings.dark_theme_grid_settings,
time_and_sales: bts.shell.time_and_sales.TimeAndSalesSettings.dark_theme_grid_settings,
fills: bts.shell.fills.FillsSettings.dark_theme_grid_settings,
synthetic_management: bts.shell.SyntheticManagementSettings.dark_theme_grid_settings,
ladder: LadderSettings.dark_theme));
}
}
@@ -1,77 +1,77 @@
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.shell {
public enum DockState {
FLOATING = 1,
TOP = 2,
BOTTOM = 3,
LEFT = 4,
RIGHT = 5,
}
[ProtoContract]
public class WindowPosition {
[ProtoMember(3)]
public int width;
[ProtoMember(4)]
public int height;
[ProtoMember(5)]
public int left;
[ProtoMember(6)]
public int top;
[ProtoMember(7)]
public bool is_maximized;
[ProtoMember(8)]
public string host_id;
[ProtoMember(9)]
public int tab_index;
[ProtoMember(100), DefaultValue(false)]
public bool horizontal = false;
[ProtoMember(101), DefaultValue(true)]
public bool show_text = true;
[ProtoMember(102), DefaultValue(true)]
public bool always_on_top = true;
//[ProtoMember(103)] //used
[ProtoMember(104)]
public string custom_title;
}
[ProtoContract]
public class WindowState {
[ProtoMember(1)]
public string owner;
[ProtoMember(2)]
public byte[] app_data;
//optional bool is_open = 3 [default = true];
//optional bool is_favorite = 4;
//optional string title = 5;
//optional string id = 6;
// optional bool is_loaded = 7 [default = false];
[ProtoMember(8)]
public WindowPosition position;
[ProtoMember(9)]
public string title; // for debugging
}
[ProtoContract]
public class ModuleState {
[ProtoMember(1)]
public string name;
[ProtoMember(2)]
public byte[] app_data;
}
}
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.shell {
public enum DockState {
FLOATING = 1,
TOP = 2,
BOTTOM = 3,
LEFT = 4,
RIGHT = 5,
}
[ProtoContract]
public class WindowPosition {
[ProtoMember(3)]
public int width;
[ProtoMember(4)]
public int height;
[ProtoMember(5)]
public int left;
[ProtoMember(6)]
public int top;
[ProtoMember(7)]
public bool is_maximized;
[ProtoMember(8)]
public string host_id;
[ProtoMember(9)]
public int tab_index;
[ProtoMember(100), DefaultValue(false)]
public bool horizontal = false;
[ProtoMember(101), DefaultValue(true)]
public bool show_text = true;
[ProtoMember(102), DefaultValue(true)]
public bool always_on_top = true;
//[ProtoMember(103)] //used
[ProtoMember(104)]
public string custom_title;
}
[ProtoContract]
public class WindowState {
[ProtoMember(1)]
public string owner;
[ProtoMember(2)]
public byte[] app_data;
//optional bool is_open = 3 [default = true];
//optional bool is_favorite = 4;
//optional string title = 5;
//optional string id = 6;
// optional bool is_loaded = 7 [default = false];
[ProtoMember(8)]
public WindowPosition position;
[ProtoMember(9)]
public string title; // for debugging
}
[ProtoContract]
public class ModuleState {
[ProtoMember(1)]
public string name;
[ProtoMember(2)]
public byte[] app_data;
}
}
@@ -1,25 +1,25 @@
using System;
namespace bts.api.orderman {
public readonly struct FillSecurity : IEquatable<FillSecurity> {
public FillSecurity(SecurityImmutable? sec, FillImmutable fill) {
this.sec = sec;
this.fill = fill;
}
public FillSecurity((SecurityImmutable? sec, FillImmutable fill) t) {
sec = t.sec;
fill = t.fill;
}
public static implicit operator FillSecurity(ValueTuple<SecurityImmutable?, FillImmutable> x) => new FillSecurity(x);
public SecurityImmutable? sec { get; }
public FillImmutable fill { get; }
public override bool Equals(object obj) => (obj is FillSecurity os) && Equals(os);
public bool Equals(FillSecurity other) => fill.FillKey == other.fill.FillKey && sec == other.sec;
public override int GetHashCode() => (sec, fill).GetHashCode();
public static bool operator ==(FillSecurity left, FillSecurity right) => left.Equals(right);
public static bool operator !=(FillSecurity left, FillSecurity right) => !left.Equals(right);
}
}
using System;
namespace bts.api.orderman {
public readonly struct FillSecurity : IEquatable<FillSecurity> {
public FillSecurity(SecurityImmutable? sec, FillImmutable fill) {
this.sec = sec;
this.fill = fill;
}
public FillSecurity((SecurityImmutable? sec, FillImmutable fill) t) {
sec = t.sec;
fill = t.fill;
}
public static implicit operator FillSecurity(ValueTuple<SecurityImmutable?, FillImmutable> x) => new FillSecurity(x);
public SecurityImmutable? sec { get; }
public FillImmutable fill { get; }
public override bool Equals(object obj) => (obj is FillSecurity os) && Equals(os);
public bool Equals(FillSecurity other) => fill.FillKey == other.fill.FillKey && sec == other.sec;
public override int GetHashCode() => (sec, fill).GetHashCode();
public static bool operator ==(FillSecurity left, FillSecurity right) => left.Equals(right);
public static bool operator !=(FillSecurity left, FillSecurity right) => !left.Equals(right);
}
}
@@ -1,101 +1,101 @@
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using System;
using static bts.api.orderman.Fill.Types;
namespace mbts.spark {
class FillTuple : IEquatable<FillTuple> {
public static readonly Func<FillTuple, string> key_fn = ft => ft.fill.FillKey;
public readonly FillImmutable fill;
public readonly SecurityImmutable? security;
OrderSecurityRootPair? _order_tuple;
public FillTuple(FillImmutable fill, SecurityImmutable? security, OrderSecurityRootPair? order_tuple) {
this.fill = fill;
this.security = security;
_order_tuple = order_tuple;
}
public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderSecurity? order_tuple)
: this(fill.val, fill.sec, order_tuple.HasValue ? OrderSecurityRootPair.from_order_security(order_tuple.Value) : (OrderSecurityRootPair?)null) { }
public AlgoData? algo =>
_order_tuple.HasValue ? _order_tuple.Value.order.algo : (AlgoData?)null;
public AlgoDefinitionMetadata? algo_meta =>
_order_tuple.HasValue ? _order_tuple.Value.order.meta : null;
public OrderRecordImmutable? order =>
_order_tuple.HasValue ? _order_tuple.Value.order.order : (OrderRecordImmutable?)null;
public AlgoData? root_algo =>
_order_tuple.HasValue ? _order_tuple.Value.root.algo : (AlgoData?)null;
public AlgoDefinitionMetadata? root_algo_meta =>
_order_tuple.HasValue ? _order_tuple.Value.root.meta : null;
public OrderSecurityAlgo? root_order_security => _order_tuple?.root;
public AccountTuple account_tuple => new(account_id, account);
public string account {
get {
var account_string = string.Empty;
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 uint account_id =>
fill.FillKind != FillKind.Sod && order.HasValue ?
order.Value.account_id() :
fill.InternalAccountId;
public TimeInForce time_in_force =>
order?.time_in_force() ?? TimeInForce.Undefined;
public bool Equals(FillTuple other) =>
other != null &&
_order_tuple.Equals(other._order_tuple) &&
security.HasValue == other.security.HasValue &&
fill.Equals(other.fill);
public override bool Equals(object obj) =>
Equals(obj as FillTuple);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
fill.FillKey.GetHashCode(),
order.HasValue ? order.Value.Key.GetHashCode() : 0,
security.HasValue ? security.Value.Id.GetHashCode() : 0);
}
static class FillTupleExtensions {
public static DateTime fill_time(this FillTuple fill_tuple) =>
fill_tuple.fill.Timestamp.to_local_time();
public static TimeInForce time_in_force(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.time_in_force() : TimeInForce.Undefined;
public static CustomOrderDefinition.CustomOneofCase order_type(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.order_type() : CustomOrderDefinition.CustomOneofCase.None;
public static Venue exchange(this FillTuple fill_tuple) =>
fill_tuple.security.HasValue ? fill_tuple.security.Value.Exchange : Venue.Unset;
public static uint order_key(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.Key : 0u;
public static string user(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.user() : string.Empty;
public static uint user_id(this FillTuple fill_tuple) =>
fill_tuple.order?.user_id() ?? 0;
}
}
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using System;
using static bts.api.orderman.Fill.Types;
namespace mbts.spark {
class FillTuple : IEquatable<FillTuple> {
public static readonly Func<FillTuple, string> key_fn = ft => ft.fill.FillKey;
public readonly FillImmutable fill;
public readonly SecurityImmutable? security;
OrderSecurityRootPair? _order_tuple;
public FillTuple(FillImmutable fill, SecurityImmutable? security, OrderSecurityRootPair? order_tuple) {
this.fill = fill;
this.security = security;
_order_tuple = order_tuple;
}
public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderSecurity? order_tuple)
: this(fill.val, fill.sec, order_tuple.HasValue ? OrderSecurityRootPair.from_order_security(order_tuple.Value) : (OrderSecurityRootPair?)null) { }
public AlgoData? algo =>
_order_tuple.HasValue ? _order_tuple.Value.order.algo : (AlgoData?)null;
public AlgoDefinitionMetadata? algo_meta =>
_order_tuple.HasValue ? _order_tuple.Value.order.meta : null;
public OrderRecordImmutable? order =>
_order_tuple.HasValue ? _order_tuple.Value.order.order : (OrderRecordImmutable?)null;
public AlgoData? root_algo =>
_order_tuple.HasValue ? _order_tuple.Value.root.algo : (AlgoData?)null;
public AlgoDefinitionMetadata? root_algo_meta =>
_order_tuple.HasValue ? _order_tuple.Value.root.meta : null;
public OrderSecurityAlgo? root_order_security => _order_tuple?.root;
public AccountTuple account_tuple => new(account_id, account);
public string account {
get {
var account_string = string.Empty;
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 uint account_id =>
fill.FillKind != FillKind.Sod && order.HasValue ?
order.Value.account_id() :
fill.InternalAccountId;
public TimeInForce time_in_force =>
order?.time_in_force() ?? TimeInForce.Undefined;
public bool Equals(FillTuple other) =>
other != null &&
_order_tuple.Equals(other._order_tuple) &&
security.HasValue == other.security.HasValue &&
fill.Equals(other.fill);
public override bool Equals(object obj) =>
Equals(obj as FillTuple);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
fill.FillKey.GetHashCode(),
order.HasValue ? order.Value.Key.GetHashCode() : 0,
security.HasValue ? security.Value.Id.GetHashCode() : 0);
}
static class FillTupleExtensions {
public static DateTime fill_time(this FillTuple fill_tuple) =>
fill_tuple.fill.Timestamp.to_local_time();
public static TimeInForce time_in_force(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.time_in_force() : TimeInForce.Undefined;
public static CustomOrderDefinition.CustomOneofCase order_type(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.order_type() : CustomOrderDefinition.CustomOneofCase.None;
public static Venue exchange(this FillTuple fill_tuple) =>
fill_tuple.security.HasValue ? fill_tuple.security.Value.Exchange : Venue.Unset;
public static uint order_key(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.Key : 0u;
public static string user(this FillTuple fill_tuple) =>
fill_tuple.order.HasValue ? fill_tuple.order.Value.user() : string.Empty;
public static uint user_id(this FillTuple fill_tuple) =>
fill_tuple.order?.user_id() ?? 0;
}
}
@@ -1,19 +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;
}
}
}
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;
}
}
}
@@ -1,225 +1,245 @@
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.shell;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui.controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using OrderPair = System.ValueTuple<bts.api.SecurityImmutable?, bts.api.orderman.OrderRecordImmutable>;
namespace bts.spark {
internal class Activity {
public SecurityImmutable? security;
public string message;
public ILogViewerCategory category;
}
class OrderActivitySummarizer : IDisposable {
readonly IBus _bus;
IReadOnlyDictionary<uint, SecurityMD> _security = new Dictionary<uint, SecurityMD>();
IDisposable _dispose;
static readonly IEqualityComparer<OrderRecordImmutable> _id_comparer =
bts.utils.EqualityComparer.Create<OrderRecordImmutable, uint>(a => a.Key);
public OrderActivitySummarizer(IBus bus, IObservable<TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint>> orders) {
_bus = bus;
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec => _security = sec),
orders.Subscribe(orders_updated)
);
}
public void Dispose() => Disposable.dispose(ref _dispose);
#region formatting
SecurityImmutable? try_get_security(uint security_key) {
if (_security.TryGetValue(security_key, out SecurityMD md)) {
return md.security;
}
return null;
}
public static string format_order_success(
uint key, double price, double size, Side side, ContractSpecificationImmutable? spec) =>
$"({key}) {side.ToString().ToLower()} {size} @ {spec.format(price)}";
string format_order_fail(
double price,
double size,
Side side,
ContractSpecificationImmutable? spec,
string error) =>
$"Failed to {side.ToString().ToLower()} {size} @ {spec.format(price)}. {error}";
string format_cancel_success(OrderRecordImmutable order, ContractSpecificationImmutable? spec) {
return $"({order.Key}) Canceled {order.short_description(spec)}, was working {order.working_quantity()}";
}
string format_cancel_error(OrderRecordImmutable order, ContractSpecificationImmutable? spec, string error) {
return $"({order.Key}) Failed to cancel {order.short_description(spec)}: {error}";
}
public static string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after) =>
_format_fill_summary(_header(after.Key), before, after);
public static string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after, SecurityImmutable? security) =>
_format_fill_summary(_header(after.Key, security), before, after);
public static string format_status_change(uint key, OrderStatus old_status, OrderStatus new_status) =>
_format_status_change(_header(key), key, old_status, new_status);
public static string format_status_change(uint key, OrderStatus old_status, OrderStatus new_status, SecurityImmutable? security) =>
_format_status_change(_header(key, security), key, old_status, new_status);
// since changes are naggled, transition changes aren't always detected (e.g. a new order changes before observers are notified of its existence), so old_status might be null.
public static string format_status_change(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) {
string header = _header(key, security);
return old_status.HasValue ?
_format_status_change(header, key, old_status.Value, new_status) :
_format_status_change(header, key, new_status);
}
public static string order_completion_debrief(OrderRecordImmutable order, SecurityImmutable? security) =>
_format_order_completion(_header(order.Key, security), order, security?.ContractSpec);
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) {
double old_price = old_order.State.Price, new_price = new_order.State.Price;
uint old_size = old_order.State.Quantity, new_size = new_order.State.Quantity;
uint old_attached_target_key = old_order.attached_target_order_key(), new_attached_target_key = new_order.attached_target_order_key();
return StringBuilderEx.join(prefix, change_descs());
//
string prefix() => $"({old_order.Key}) Changed";
IEnumerable<string> change_descs() {
if (old_price != new_price)
yield return $"price from {spec.format(old_price)} to {spec.format(new_price)}";
if (old_size != new_size)
yield return $"size from {old_size} to {new_size}, working {new_order.working_quantity()}";
if (old_attached_target_key != new_attached_target_key)
yield return $"attached target from {old_attached_target_key} to {new_attached_target_key}";
}
}
static string _header(uint key) => $"({key})";
static string _header(uint key, SecurityImmutable? security) => $"({key}) {security.display_name()}";
static string _format_fill_summary(string header, OrderRecordImmutable before, OrderRecordImmutable after) {
int fb = (int)before.State.FilledQuantity;
int fa = (int)after.State.FilledQuantity;
return $"{header} {after.Def.Side.past_tense()} {(fa - fb)} ({fa} total), still working {after.working_quantity()}";
}
static string _format_status_change(string header, uint key, OrderStatus new_status) =>
$"{header} Status changed to {new_status}";
static string _format_status_change(string header, uint key, OrderStatus old_status, OrderStatus new_status) =>
$"{header} Status changed from {old_status} to {new_status}";
public static string _format_order_completion(string header, OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
$"{header} Completed: {order.side().past_tense()} {order.filled()}, @ {spec.spec_or_default().format(order.avg_price())} (avg)";
#endregion
void orders_updated(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) {
foreach (var o in update.added) {
if (!string.IsNullOrEmpty(o.order.State.LastMsg) && o.order.State.Created.ToDateTime().Date == DateTime.Today) {
if (o.sec.HasValue) {
log_status(ActivityLogCategory.warn, o.sec.Value, o.order.State.LastMsg);
}
}
}
foreach (var order in update.changes) {
var neworder = order.New.order;
var oldorder = order.Old.order;
var security = order.New.sec ?? order.Old.sec;
//
// description
var mod_desc = modified_description(oldorder, neworder, security?.ContractSpec);
if (!string.IsNullOrEmpty(mod_desc)) {
log_status(ActivityLogCategory.modify, security, mod_desc);
}
//
// filled quantity
if (oldorder.State.FilledQuantity != neworder.State.FilledQuantity && !neworder.has_parent()) {
log_status(ActivityLogCategory.fill, security, format_fill_summary(oldorder, neworder));
}
//
// status
if (oldorder.State.Status != neworder.State.Status && !neworder.has_parent()) {
log_status(ActivityLogCategory.modify, security,
format_status_change(neworder.Key, oldorder.State.Status, neworder.State.Status));
}
// last msg
if (oldorder.State.LastMsg != neworder.State.LastMsg) {
if (security.HasValue) {
log_status(ActivityLogCategory.warn, security, neworder.State.LastMsg);
}
}
}
}
public void log_status(ILogViewerCategory category, SecurityImmutable? security, string msg) {
_bus.post(SparkTags.LogActivity, new Activity { security = security, message = msg, category = category });
}
internal void on_send_order(
OrderDefinitionImmutable order, double price, double size, uint? key, string error) {
var security = try_get_security(order.SecurityKey);
log_status(ActivityLogCategory.order, security, key.HasValue ?
format_order_success(key.Value, price, size, order.Side, security?.ContractSpec) :
format_order_fail(price, size, order.Side, security?.ContractSpec, error));
}
internal void on_cancel_order(OrderRecordImmutable order, bool success, string error) {
var security = try_get_security(order.Def.SecurityKey);
log_status(ActivityLogCategory.cancel, security, success ?
format_cancel_success(order, security?.ContractSpec) :
format_cancel_error(order, security?.ContractSpec, error));
}
internal void update_order(
OrderRecordImmutable order, double price, double size, bool algo_changed) =>
_log_order_update(order, price, size, algo_changed, "change from");
internal void update_order_failed(OrderRecordImmutable order, double price, double size, bool algo_changed) =>
_log_order_update(order, price, size, algo_changed, "failed to change from");
void _log_order_update(
OrderRecordImmutable order,
double price,
double size,
bool algo_changed,
string change_desc_prefix
) {
if (price == order.price() && size == order.working_quantity() && !algo_changed) {
// nothing actually changed
return;
}
const string algo_change_text = "change algo parameters";
var security = try_get_security(order.Def.SecurityKey);
var spec = security?.ContractSpec;
var desc_builder = new StringBuilderEx();
if (price != order.price() || size != order.working_quantity()) {
desc_builder.Add(order.State.Quantity.ToString(), "@", spec.format(order.State.Price), "to ", size.ToString(), "@", spec.format(price));
if (algo_changed)
desc_builder.Add("; ", algo_change_text);
} else if (algo_changed) {
desc_builder.Add(algo_change_text);
}
desc_builder.Insert(0, $"{change_desc_prefix} ");
desc_builder.Insert(0, $"({order.Key}) ");
log_status(ActivityLogCategory.modify, security, desc_builder.ToString());
}
}
}
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.shell;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui.controls;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using OrderPair = System.ValueTuple<bts.api.SecurityImmutable?, bts.api.orderman.OrderRecordImmutable>;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
namespace bts.spark {
internal class Activity {
public SecurityImmutable? security;
public string message;
public ILogViewerCategory category;
}
class OrderActivitySummarizer : IDisposable {
readonly IBus _bus;
IReadOnlyDictionary<uint, SecurityMD> _security = new Dictionary<uint, SecurityMD>();
IDisposable _dispose;
static readonly IEqualityComparer<OrderRecordImmutable> _id_comparer =
bts.utils.EqualityComparer.Create<OrderRecordImmutable, uint>(a => a.Key);
public OrderActivitySummarizer(IBus bus, IObservable<TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint>> orders) {
_bus = bus;
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec => _security = sec),
orders.Subscribe(orders_updated)
);
}
public void Dispose() => Disposable.dispose(ref _dispose);
#region formatting
SecurityImmutable? try_get_security(uint security_key) {
if (_security.TryGetValue(security_key, out SecurityMD md)) {
return md.security;
}
return null;
}
public static string format_order_success(
uint key, double price, double size, Side side, ContractSpecificationImmutable? spec) =>
$"({key}) {side.ToString().ToLower()} {size} @ {spec.format(price)}";
string format_order_fail(
double price,
double size,
Side side,
ContractSpecificationImmutable? spec,
string error) =>
$"Failed to {side.ToString().ToLower()} {size} @ {spec.format(price)}. {error}";
string format_cancel_success(OrderRecordImmutable order, ContractSpecificationImmutable? spec) {
return $"({order.Key}) Canceled {order.short_description(spec)}, was working {order.working_quantity()}";
}
string format_cancel_error(OrderRecordImmutable order, ContractSpecificationImmutable? spec, string error) {
return $"({order.Key}) Failed to cancel {order.short_description(spec)}: {error}";
}
public static string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after) =>
_format_fill_summary(_header(after.Key), before, after);
public static string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after, SecurityImmutable? security) =>
_format_fill_summary(_header(after.Key, security), before, after);
public static string format_status_change(uint key, OrderStatus old_status, OrderStatus new_status) =>
_format_status_change(_header(key), key, old_status, new_status);
public static string format_status_change(uint key, OrderStatus old_status, OrderStatus new_status, SecurityImmutable? security) =>
_format_status_change(_header(key, security), key, old_status, new_status);
// since changes are naggled, transition changes aren't always detected (e.g. a new order changes before observers are notified of its existence), so old_status might be null.
public static string format_status_change(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) {
string header = _header(key, security);
return old_status.HasValue ?
_format_status_change(header, key, old_status.Value, new_status) :
_format_status_change(header, key, new_status);
}
public static string order_completion_debrief(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) =>
_format_order_completion(
_header(order.Key, security), order, security?.ContractSpec, qty_display);
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) {
double old_price = old_order.State.Price, new_price = new_order.State.Price;
uint old_size = old_order.State.Quantity, new_size = new_order.State.Quantity;
uint old_attached_target_key = old_order.attached_target_order_key(), new_attached_target_key = new_order.attached_target_order_key();
return StringBuilderEx.join(prefix, change_descs());
//
string prefix() => $"({old_order.Key}) Changed";
IEnumerable<string> change_descs() {
if (old_price != new_price)
yield return $"price from {spec.format(old_price)} to {spec.format(new_price)}";
if (old_size != new_size)
yield return $"size from {old_size} to {new_size}, working {new_order.working_quantity()}";
if (old_attached_target_key != new_attached_target_key)
yield return $"attached target from {old_attached_target_key} to {new_attached_target_key}";
}
}
static string _header(uint key) => $"({key})";
static string _header(uint key, SecurityImmutable? security) => $"({key}) {security.display_name()}";
static string _format_fill_summary(string header, OrderRecordImmutable before, OrderRecordImmutable after) {
int fb = (int)before.State.FilledQuantity;
int fa = (int)after.State.FilledQuantity;
return $"{header} {after.Def.Side.past_tense()} {(fa - fb)} ({fa} total), still working {after.working_quantity()}";
}
static string _format_status_change(string header, uint key, OrderStatus new_status) =>
$"{header} Status changed to {new_status}";
static string _format_status_change(string header, uint key, OrderStatus old_status, OrderStatus new_status) =>
$"{header} Status changed from {old_status} to {new_status}";
static string _format_order_completion(
string header,
OrderRecordImmutable order,
ContractSpecificationImmutable? spec,
TickDisplaySettingsImmutable qty_display) {
var filled_qty_str = qty_display.format(order.filled_quantity());
return $"{header} Completed: {order.side().past_tense()} {filled_qty_str}, " +
$"@ {spec.spec_or_default().format(order.avg_price())} (avg)";
}
#endregion
void orders_updated(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) {
foreach (var o in update.added) {
if (!string.IsNullOrEmpty(o.order.State.LastMsg) && o.order.State.Created.ToDateTime().Date == DateTime.Today) {
if (o.sec.HasValue) {
log_status(ActivityLogCategory.warn, o.sec.Value, o.order.State.LastMsg);
}
}
}
foreach (var order in update.changes) {
var neworder = order.New.order;
var oldorder = order.Old.order;
var security = order.New.sec ?? order.Old.sec;
//
// description
var mod_desc = modified_description(oldorder, neworder, security?.ContractSpec);
if (!string.IsNullOrEmpty(mod_desc)) {
log_status(ActivityLogCategory.modify, security, mod_desc);
}
//
// filled quantity
if (oldorder.State.FilledQuantity != neworder.State.FilledQuantity && !neworder.has_parent()) {
log_status(ActivityLogCategory.fill, security, format_fill_summary(oldorder, neworder));
}
//
// status
if (oldorder.State.Status != neworder.State.Status && !neworder.has_parent()) {
log_status(ActivityLogCategory.modify, security,
format_status_change(neworder.Key, oldorder.State.Status, neworder.State.Status));
}
// last msg
if (oldorder.State.LastMsg != neworder.State.LastMsg) {
if (security.HasValue) {
log_status(ActivityLogCategory.warn, security, neworder.State.LastMsg);
}
}
}
}
public void log_status(ILogViewerCategory category, SecurityImmutable? security, string msg) {
_bus.post(SparkTags.LogActivity, new Activity { security = security, message = msg, category = category });
}
internal void on_send_order(
OrderDefinitionImmutable order, double price, double size, uint? key, string error) {
var security = try_get_security(order.SecurityKey);
log_status(ActivityLogCategory.order, security, key.HasValue ?
format_order_success(key.Value, price, size, order.Side, security?.ContractSpec) :
format_order_fail(price, size, order.Side, security?.ContractSpec, error));
}
internal void on_cancel_order(OrderRecordImmutable order, bool success, string error) {
var security = try_get_security(order.Def.SecurityKey);
log_status(ActivityLogCategory.cancel, security, success ?
format_cancel_success(order, security?.ContractSpec) :
format_cancel_error(order, security?.ContractSpec, error));
}
internal void update_order(
OrderRecordImmutable order, double price, double size, bool algo_changed) =>
_log_order_update(order, price, size, algo_changed, "change from");
internal void update_order_failed(OrderRecordImmutable order, double price, double size, bool algo_changed) =>
_log_order_update(order, price, size, algo_changed, "failed to change from");
void _log_order_update(
OrderRecordImmutable order,
double price,
double size,
bool algo_changed,
string change_desc_prefix
) {
if (price == order.price() && size == order.working_quantity() && !algo_changed) {
// nothing actually changed
return;
}
const string algo_change_text = "change algo parameters";
var security = try_get_security(order.Def.SecurityKey);
var change_descs = new List<string>(1);
TickDisplaySettingsImmutable? price_display =
security.HasValue && security.Value.HasContractSpec ?
security.Value.ContractSpec.tick_factors().to_api_tick_display_settingsi() : null;
var price_qty_change_desc = OrderUtils.update_description(
order, price, size, price_display);
if (!price_qty_change_desc.is_null_or_empty()) {
change_descs.Add(price_qty_change_desc);
}
if (algo_changed) {
change_descs.Add(algo_change_text);
}
var desc = $"({order.Key}) {change_desc_prefix} {"; ".join(change_descs)}";
log_status(ActivityLogCategory.modify, security, desc);
}
}
}
@@ -1,34 +1,34 @@
using bts.api;
using bts.spark;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace mbts.ui.spark {
internal static class OrderIconFactory {
static OrderIconFactory() {
_bid_pen.Freeze();
_ask_pen.Freeze();
}
private static readonly Pen _bid_pen = new Pen(BTSColors.MarketData.bid_brush, 4), _ask_pen = new Pen(BTSColors.MarketData.ask_brush, 4);
private static readonly ConcurrentDictionary<uint, Brush> _algo_palette = new ConcurrentDictionary<uint, Brush>();
public static ImageSource Create(OrderMetadata metadata, Side side) {
Brush brush = _algo_palette.GetOrAdd(metadata.Color, c => {
Brush b = new SolidColorBrush(c.rgb_color());
b.Freeze();
return b;
});
var group = new DrawingGroup();
group.Children.Add(new GeometryDrawing(brush, side == Side.Buy ? _bid_pen : _ask_pen, new RectangleGeometry(new Rect(0, 0, 40, 28), 3, 3)));
return new DrawingImage { Drawing = group };
}
}
}
using bts.api;
using bts.spark;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace mbts.ui.spark {
internal static class OrderIconFactory {
static OrderIconFactory() {
_bid_pen.Freeze();
_ask_pen.Freeze();
}
private static readonly Pen _bid_pen = new Pen(BTSColors.MarketData.bid_brush, 4), _ask_pen = new Pen(BTSColors.MarketData.ask_brush, 4);
private static readonly ConcurrentDictionary<uint, Brush> _algo_palette = new ConcurrentDictionary<uint, Brush>();
public static ImageSource Create(OrderMetadata metadata, Side side) {
Brush brush = _algo_palette.GetOrAdd(metadata.Color, c => {
Brush b = new SolidColorBrush(c.rgb_color());
b.Freeze();
return b;
});
var group = new DrawingGroup();
group.Children.Add(new GeometryDrawing(brush, side == Side.Buy ? _bid_pen : _ask_pen, new RectangleGeometry(new Rect(0, 0, 40, 28), 3, 3)));
return new DrawingImage { Drawing = group };
}
}
}
@@ -1,160 +1,160 @@
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
namespace mbts.spark {
/// <summary>
/// Monitors selected rows, and determines whether or not they are all active-orders, with common parameters.
/// </summary>
class OrderParamsAggregator {
readonly TimeSpan _throttle;
readonly CommonValueGroupMonitor<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable> _algo_def_mon =
new CommonValueGroupMonitor<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable>(
ask => ask,
OrderDataHelper.EqualsHelpers.custom_order_defi_structure_comparer,
OrderDataHelper.EqualsHelpers.custom_order_defi_comparer);
readonly CommonValueMonitor<SecurityImmutable?> _spreader_security_mon = new CommonValueMonitor<SecurityImmutable?>();
readonly CommonValueMonitor<SecurityImmutable?> _security_mon = new CommonValueMonitor<SecurityImmutable?>();
readonly CommonValueMonitor<double> _price_mon = new CommonValueMonitor<double>(double.NaN);
readonly CommonValueMonitor<double> _size_mon = new();
readonly CommonValueMonitor<AccountTuple> _account_mon = new CommonValueMonitor<AccountTuple>();
readonly CommonValueMonitor<bool> _all_active_mon = new CommonValueMonitor<bool>();
readonly CommonValueMonitorMultiplexor<OrderSecurityAlgo> _group_mon = new CommonValueMonitorMultiplexor<OrderSecurityAlgo>();
readonly DynamicOrderHelper _dyn_helper;
readonly Func<uint, OrderSecurityAlgo?> _lookup_order;
public OrderParamsAggregator(DynamicOrderHelper dyn_helper, TimeSpan throttle, Func<uint, OrderSecurityAlgo?> lookup_order) {
_dyn_helper = dyn_helper;
_throttle = throttle;
_lookup_order = lookup_order;
_group_mon.add_member_mon(_algo_def_mon, _build_algo_tree);
_group_mon.add_member_mon(_spreader_security_mon, _get_spreader_sec, s => s.HasValue);
_group_mon.add_member_mon(_security_mon, osam => osam.security, s => s.HasValue);
_group_mon.add_member_mon(_price_mon, osam => osam.order.price());
_group_mon.add_member_mon(_size_mon, osam => osam.order.quantity());
_group_mon.add_member_mon(_account_mon, osam => new AccountTuple(osam.order.account_id(), osam.order.account()));
_group_mon.add_member_mon(_all_active_mon, osam => osam.order.is_active());
}
public SecurityImmutable? security => _security_mon.common_value;
public SecurityImmutable? spreader_security => _spreader_security_mon.common_value;
public double price => _price_mon.try_get_common_value(out double p) ? p : double.NaN;
public double? size => _size_mon.common_value_nullable();
public AccountTuple? account => _account_mon.common_value_nullable();
public bool all_active => _all_active_mon.common_value;
/// <summary>
/// Notifies observers when the set of <see cref="CustomOrderDefinitionImmutable"/>s changes.
/// The algos in the set are the distinct group of algos for the selected <see cref="OrderSecurityAlgo"/>s.
/// </summary>
// Note: this might be better optimized by adding a 'begin_reset' method to CommonValueMonitor that records the current state,
// and accumulates subsequent changes into a batch change. If the 'begin_reset' method returned an IDisposable,
// the batch change object could be examined when Dispose is called,
// to avoid firing the common_values_changed event if the accumulated changes cancel each other out.
// However, such a change would be non-trivial, so this method will suffice for now.
// It should perform fine in practice, even with a large number of selected orders,
// because the input is throttled.
public IObservable<IEnumerable<CustomOrderDefinitionImmutable>> subscribe_algos() =>
Observable.Create<ImmutableHashSet<CustomOrderDefinitionImmutable>>(o => {
var last_algos = ImmutableHashSet.Create(OrderDataHelper.EqualsHelpers.custom_order_defi_comparer);
return _algo_def_mon
.SubscribeThrottled(_throttle, (ask, vals) => vals, Array.Empty<CustomOrderDefinitionImmutable>())
.Subscribe(algos => {
// only notify the observer if the algo set has actually changed.
if (algos.Count != last_algos.Count || !algos.All(last_algos.Contains))
o.OnNext(last_algos = ImmutableHashSet.CreateRange(OrderDataHelper.EqualsHelpers.custom_order_defi_comparer, algos));
});
});
public IObservable<SecurityImmutable?> subscribe_spreader_security() => _spreader_security_mon.SubscribeThrottled(_throttle);
public IObservable<SecurityImmutable?> subscribe_security() => _security_mon.SubscribeThrottled(_throttle);
public IObservable<double> subscribe_price() => _price_mon.SubscribeThrottled(_throttle);
public IObservable<double?> subscribe_size() => _size_mon.SubscribeThrottledNullable(_throttle);
public IObservable<AccountTuple?> subscribe_account() => _account_mon.SubscribeThrottledNullable(_throttle);
public IObservable<bool> subscribe_all_active() => _all_active_mon.SubscribeThrottled(_throttle);
public IObservable<Plurality> subscribe_security_plurality() => _security_mon.SubscribePluralityThrottled(_throttle);
public IDisposable defer_updates() =>
_group_mon.defer_updates();
public void Add(OrderSecurityAlgo order_tuple) =>
_group_mon.add(order_tuple);
public void Remove(OrderSecurityAlgo order_tuple) =>
_group_mon.remove(order_tuple);
public void Clear() =>
_group_mon.clear();
static SecurityImmutable? _get_spreader_sec(OrderSecurityAlgo osam) =>
OrderDataHelper.enumerate_algo_hierarchy(osam.order.Def.CustomDef.CloneToMutable())
.Any(algo => algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Spreader) ?
osam.security : null;
CustomOrderDefinitionImmutable _build_algo_tree(OrderSecurityAlgo root) =>
root.order.Def.AttachTargetOrderKey == 0 ?
root.order.Def.CustomDef :
new CustomOrderDefinitionImmutable(_add_attached_targets(root.order.Def.CustomDef.CloneToMutable(), root.order.Key, root.order.Def.AttachTargetOrderKey));
CustomOrderDefinition _add_attached_targets(CustomOrderDefinition mroot, uint root_id, uint attached_target) {
var lin = _lineage(root_id, attached_target);
if (lin != null && lin.Count > 0) {
var mparent = mroot;
var pcad = OrderDataHelper.get_primary_child_algo_data(mparent);
if (pcad.HasValue) {
do {
var mchild = lin.Pop().order.Def.CustomDef.CloneToMutable();
pcad.Value.assign_child(mparent, mchild);
mparent = mchild;
pcad = OrderDataHelper.get_primary_child_algo_data(mparent);
} while (lin.Count > 0 && pcad.HasValue);
}
}
return mroot;
}
Stack<OrderSecurityAlgo> _lineage(uint root, uint target) {
// check args/preconditions
if (root == 0) throw new ArgumentException("Cannot be zero.", nameof(root));
if (target == 0) throw new ArgumentException("Cannot be zero.", nameof(target));
if (target == root) return null;
var inner = _lookup_order(target);
if (!inner.HasValue)
return null;
// if 'target' has an attach target iteself (nested), push the nested lineage onto the stack first,
// then push the original target onto the stack, and try to hop up each algo-generation
// via parent-key lookups until we reach the root.
// **If the lineage is disjointed, and we never reach the root, return null**
var ival = inner.Value;
var lin_stack = ival.order.attached_target_order_key() != 0 ?
_lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack<OrderSecurityAlgo>() :
new Stack<OrderSecurityAlgo>();
lin_stack.Push(ival);
target = ival.order.ParentKey;
while (target != root) {
if (target == 0) {
// **disjointed lineage**
return null;
}
inner = _lookup_order(target);
if (!inner.HasValue) {
// **disjointed lineage**
return null;
}
ival = inner.Value;
lin_stack.Push(ival);
target = ival.order.ParentKey;
}
return lin_stack;
}
}
}
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.spark.utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
namespace mbts.spark {
/// <summary>
/// Monitors selected rows, and determines whether or not they are all active-orders, with common parameters.
/// </summary>
class OrderParamsAggregator {
readonly TimeSpan _throttle;
readonly CommonValueGroupMonitor<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable> _algo_def_mon =
new CommonValueGroupMonitor<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable>(
ask => ask,
OrderDataHelper.EqualsHelpers.custom_order_defi_structure_comparer,
OrderDataHelper.EqualsHelpers.custom_order_defi_comparer);
readonly CommonValueMonitor<SecurityImmutable?> _spreader_security_mon = new CommonValueMonitor<SecurityImmutable?>();
readonly CommonValueMonitor<SecurityImmutable?> _security_mon = new CommonValueMonitor<SecurityImmutable?>();
readonly CommonValueMonitor<double> _price_mon = new CommonValueMonitor<double>(double.NaN);
readonly CommonValueMonitor<double> _size_mon = new();
readonly CommonValueMonitor<AccountTuple> _account_mon = new CommonValueMonitor<AccountTuple>();
readonly CommonValueMonitor<bool> _all_active_mon = new CommonValueMonitor<bool>();
readonly CommonValueMonitorMultiplexor<OrderSecurityAlgo> _group_mon = new CommonValueMonitorMultiplexor<OrderSecurityAlgo>();
readonly DynamicOrderHelper _dyn_helper;
readonly Func<uint, OrderSecurityAlgo?> _lookup_order;
public OrderParamsAggregator(DynamicOrderHelper dyn_helper, TimeSpan throttle, Func<uint, OrderSecurityAlgo?> lookup_order) {
_dyn_helper = dyn_helper;
_throttle = throttle;
_lookup_order = lookup_order;
_group_mon.add_member_mon(_algo_def_mon, _build_algo_tree);
_group_mon.add_member_mon(_spreader_security_mon, _get_spreader_sec, s => s.HasValue);
_group_mon.add_member_mon(_security_mon, osam => osam.security, s => s.HasValue);
_group_mon.add_member_mon(_price_mon, osam => osam.order.price());
_group_mon.add_member_mon(_size_mon, osam => osam.order.quantity());
_group_mon.add_member_mon(_account_mon, osam => new AccountTuple(osam.order.account_id(), osam.order.account()));
_group_mon.add_member_mon(_all_active_mon, osam => osam.order.is_active());
}
public SecurityImmutable? security => _security_mon.common_value;
public SecurityImmutable? spreader_security => _spreader_security_mon.common_value;
public double price => _price_mon.try_get_common_value(out double p) ? p : double.NaN;
public double? size => _size_mon.common_value_nullable();
public AccountTuple? account => _account_mon.common_value_nullable();
public bool all_active => _all_active_mon.common_value;
/// <summary>
/// Notifies observers when the set of <see cref="CustomOrderDefinitionImmutable"/>s changes.
/// The algos in the set are the distinct group of algos for the selected <see cref="OrderSecurityAlgo"/>s.
/// </summary>
// Note: this might be better optimized by adding a 'begin_reset' method to CommonValueMonitor that records the current state,
// and accumulates subsequent changes into a batch change. If the 'begin_reset' method returned an IDisposable,
// the batch change object could be examined when Dispose is called,
// to avoid firing the common_values_changed event if the accumulated changes cancel each other out.
// However, such a change would be non-trivial, so this method will suffice for now.
// It should perform fine in practice, even with a large number of selected orders,
// because the input is throttled.
public IObservable<IEnumerable<CustomOrderDefinitionImmutable>> subscribe_algos() =>
Observable.Create<ImmutableHashSet<CustomOrderDefinitionImmutable>>(o => {
var last_algos = ImmutableHashSet.Create(OrderDataHelper.EqualsHelpers.custom_order_defi_comparer);
return _algo_def_mon
.SubscribeThrottled(_throttle, (ask, vals) => vals, Array.Empty<CustomOrderDefinitionImmutable>())
.Subscribe(algos => {
// only notify the observer if the algo set has actually changed.
if (algos.Count != last_algos.Count || !algos.All(last_algos.Contains))
o.OnNext(last_algos = ImmutableHashSet.CreateRange(OrderDataHelper.EqualsHelpers.custom_order_defi_comparer, algos));
});
});
public IObservable<SecurityImmutable?> subscribe_spreader_security() => _spreader_security_mon.SubscribeThrottled(_throttle);
public IObservable<SecurityImmutable?> subscribe_security() => _security_mon.SubscribeThrottled(_throttle);
public IObservable<double> subscribe_price() => _price_mon.SubscribeThrottled(_throttle);
public IObservable<double?> subscribe_size() => _size_mon.SubscribeThrottledNullable(_throttle);
public IObservable<AccountTuple?> subscribe_account() => _account_mon.SubscribeThrottledNullable(_throttle);
public IObservable<bool> subscribe_all_active() => _all_active_mon.SubscribeThrottled(_throttle);
public IObservable<Plurality> subscribe_security_plurality() => _security_mon.SubscribePluralityThrottled(_throttle);
public IDisposable defer_updates() =>
_group_mon.defer_updates();
public void Add(OrderSecurityAlgo order_tuple) =>
_group_mon.add(order_tuple);
public void Remove(OrderSecurityAlgo order_tuple) =>
_group_mon.remove(order_tuple);
public void Clear() =>
_group_mon.clear();
static SecurityImmutable? _get_spreader_sec(OrderSecurityAlgo osam) =>
OrderDataHelper.enumerate_algo_hierarchy(osam.order.Def.CustomDef.CloneToMutable())
.Any(algo => algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Spreader) ?
osam.security : null;
CustomOrderDefinitionImmutable _build_algo_tree(OrderSecurityAlgo root) =>
root.order.Def.AttachTargetOrderKey == 0 ?
root.order.Def.CustomDef :
new CustomOrderDefinitionImmutable(_add_attached_targets(root.order.Def.CustomDef.CloneToMutable(), root.order.Key, root.order.Def.AttachTargetOrderKey));
CustomOrderDefinition _add_attached_targets(CustomOrderDefinition mroot, uint root_id, uint attached_target) {
var lin = _lineage(root_id, attached_target);
if (lin != null && lin.Count > 0) {
var mparent = mroot;
var pcad = OrderDataHelper.get_primary_child_algo_data(mparent);
if (pcad.HasValue) {
do {
var mchild = lin.Pop().order.Def.CustomDef.CloneToMutable();
pcad.Value.assign_child(mparent, mchild);
mparent = mchild;
pcad = OrderDataHelper.get_primary_child_algo_data(mparent);
} while (lin.Count > 0 && pcad.HasValue);
}
}
return mroot;
}
Stack<OrderSecurityAlgo> _lineage(uint root, uint target) {
// check args/preconditions
if (root == 0) throw new ArgumentException("Cannot be zero.", nameof(root));
if (target == 0) throw new ArgumentException("Cannot be zero.", nameof(target));
if (target == root) return null;
var inner = _lookup_order(target);
if (!inner.HasValue)
return null;
// if 'target' has an attach target iteself (nested), push the nested lineage onto the stack first,
// then push the original target onto the stack, and try to hop up each algo-generation
// via parent-key lookups until we reach the root.
// **If the lineage is disjointed, and we never reach the root, return null**
var ival = inner.Value;
var lin_stack = ival.order.attached_target_order_key() != 0 ?
_lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack<OrderSecurityAlgo>() :
new Stack<OrderSecurityAlgo>();
lin_stack.Push(ival);
target = ival.order.ParentKey;
while (target != root) {
if (target == 0) {
// **disjointed lineage**
return null;
}
inner = _lookup_order(target);
if (!inner.HasValue) {
// **disjointed lineage**
return null;
}
ival = inner.Value;
lin_stack.Push(ival);
target = ival.order.ParentKey;
}
return lin_stack;
}
}
}
@@ -1,157 +1,157 @@
using bts.utils;
using mbts.spark;
using System;
namespace bts.api.orderman {
readonly struct OrderSecurity : IEquatable<OrderSecurity> {
public OrderSecurity((SecurityImmutable? sec, OrderRecordImmutable order) t) {
security = t.sec;
order = t.order;
piq = null;
algo = null;
meta = null;
}
public OrderSecurity(SecurityImmutable? sec, OrderRecordImmutable order, uint? piq) {
this.security = sec;
this.order = order;
this.piq = piq;
algo = null;
meta = null;
}
public OrderSecurity(SecurityImmutable? sec, OrderRecordImmutable order, uint? piq, AlgoData? algo, AlgoDefinitionMetadata? meta) {
this.security = sec;
this.order = order;
this.piq = piq;
this.algo = algo;
this.meta = meta;
}
public static implicit operator OrderSecurity(ValueTuple<SecurityImmutable?, OrderRecordImmutable> x) => new OrderSecurity(x);
public SecurityImmutable? security { get; }
public OrderRecordImmutable order { get; }
public uint? piq { get; }
public AlgoData? algo { get; }
public AlgoDefinitionMetadata? meta { get; }
public bool Equals(OrderSecurity other) =>
order == other.order &&
security == other.security &&
piq == other.piq &&
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,
piq?.GetHashCode() ?? 0,
algo?.GetHashCode() ?? 0,
meta?.GetHashCode() ?? 0);
public static bool operator ==(OrderSecurity left, OrderSecurity right) => left.Equals(right);
public static bool operator !=(OrderSecurity left, OrderSecurity right) => !left.Equals(right);
}
// This is a core data type on the front end, so data validation is strict, as bad values may yield weird/difficult to track bugs.
// Descriptive factory methods are favored over public constructors, as they are less likely to be misused.
readonly struct OrderSecurityAlgo : IEquatable<OrderSecurityAlgo> {
public readonly OrderRecordImmutable order;
public readonly SecurityImmutable? security;
public readonly AlgoData algo;
public readonly AlgoDefinitionMetadata? meta;
public readonly uint? piq;
OrderSecurityAlgo(OrderRecordImmutable order, SecurityImmutable? security, AlgoData algo, AlgoDefinitionMetadata? meta, uint? piq) {
this.order = order;
this.security = security;
this.algo = algo;
this.meta = meta;
this.piq = piq;
}
public static OrderSecurityAlgo from_order_security(OrderSecurity os) =>
new OrderSecurityAlgo(
os.order,
os.security,
os.algo ?? AlgoData.from_custom_def(os.order.Def.CustomDef),
os.meta,
os.piq);
public bool Equals(OrderSecurityAlgo other) =>
order == other.order &&
piq == other.piq &&
security == other.security &&
algo == other.algo;
public override bool Equals(object obj) =>
obj is OrderSecurityAlgo other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.auto_phase(
order.Key.GetHashCode(),
piq?.GetHashCode() ?? 0,
security.HasValue ? security.Value.Id.GetHashCode() : 0,
algo.GetHashCode());
public static bool operator ==(OrderSecurityAlgo a, OrderSecurityAlgo b) => a.Equals(b);
public static bool operator !=(OrderSecurityAlgo a, OrderSecurityAlgo b) => !a.Equals(b);
}
// This is a core data type on the front end, so data validation is strict, as bad values may yield weird/difficult to track bugs.
// Descriptive factory methods are favored over public constructors, as they are less likely to be misused.
readonly struct OrderSecurityRootPair : IEquatable<OrderSecurityRootPair> {
public readonly OrderSecurityAlgo order;
readonly OrderSecurityAlgo? _root;
OrderSecurityRootPair(OrderSecurityAlgo order) {
this.order = order;
_root = null;
}
OrderSecurityRootPair(OrderSecurityAlgo order, OrderSecurityAlgo? root) {
this.order = order;
_root = root;
}
public OrderSecurityAlgo root => _root ?? order;
public static OrderSecurityRootPair from_order_security(OrderSecurity order) =>
new OrderSecurityRootPair(OrderSecurityAlgo.from_order_security(order));
public static OrderSecurityRootPair from_order_security(OrderSecurity order, OrderSecurity root) =>
new OrderSecurityRootPair(
OrderSecurityAlgo.from_order_security(order),
OrderSecurityAlgo.from_order_security(root));
public bool Equals(OrderSecurityRootPair other) =>
order == other.order &&
_root == other._root;
public override bool Equals(object obj) =>
obj is OrderSecurityRootPair other && Equals(other);
public override int GetHashCode() =>
_root.HasValue ?
(order.GetHashCode() % (1 << 15)) | (_root.Value.GetHashCode() % (1 << 15) << 16) :
order.GetHashCode() % (1 << 15);
public static bool operator ==(OrderSecurityRootPair a, OrderSecurityRootPair b) => a.Equals(b);
public static bool operator !=(OrderSecurityRootPair a, OrderSecurityRootPair b) => !a.Equals(b);
}
static class OrderSecurityHelper {
public static readonly Func<OrderSecurity, uint>
key_fn = o => o.order.Key,
parent_key_fn = o => o.order.ParentKey;
public static readonly Func<OrderSecurityRootPair, uint>
root_pair_key_fn = o => o.order.order.Key,
root_pair_parent_key_fn = o => o.order.order.ParentKey;
}
}
using bts.utils;
using mbts.spark;
using System;
namespace bts.api.orderman {
readonly struct OrderSecurity : IEquatable<OrderSecurity> {
public OrderSecurity((SecurityImmutable? sec, OrderRecordImmutable order) t) {
security = t.sec;
order = t.order;
piq = null;
algo = null;
meta = null;
}
public OrderSecurity(SecurityImmutable? sec, OrderRecordImmutable order, uint? piq) {
this.security = sec;
this.order = order;
this.piq = piq;
algo = null;
meta = null;
}
public OrderSecurity(SecurityImmutable? sec, OrderRecordImmutable order, uint? piq, AlgoData? algo, AlgoDefinitionMetadata? meta) {
this.security = sec;
this.order = order;
this.piq = piq;
this.algo = algo;
this.meta = meta;
}
public static implicit operator OrderSecurity(ValueTuple<SecurityImmutable?, OrderRecordImmutable> x) => new OrderSecurity(x);
public SecurityImmutable? security { get; }
public OrderRecordImmutable order { get; }
public uint? piq { get; }
public AlgoData? algo { get; }
public AlgoDefinitionMetadata? meta { get; }
public bool Equals(OrderSecurity other) =>
order == other.order &&
security == other.security &&
piq == other.piq &&
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,
piq?.GetHashCode() ?? 0,
algo?.GetHashCode() ?? 0,
meta?.GetHashCode() ?? 0);
public static bool operator ==(OrderSecurity left, OrderSecurity right) => left.Equals(right);
public static bool operator !=(OrderSecurity left, OrderSecurity right) => !left.Equals(right);
}
// This is a core data type on the front end, so data validation is strict, as bad values may yield weird/difficult to track bugs.
// Descriptive factory methods are favored over public constructors, as they are less likely to be misused.
readonly struct OrderSecurityAlgo : IEquatable<OrderSecurityAlgo> {
public readonly OrderRecordImmutable order;
public readonly SecurityImmutable? security;
public readonly AlgoData algo;
public readonly AlgoDefinitionMetadata? meta;
public readonly uint? piq;
OrderSecurityAlgo(OrderRecordImmutable order, SecurityImmutable? security, AlgoData algo, AlgoDefinitionMetadata? meta, uint? piq) {
this.order = order;
this.security = security;
this.algo = algo;
this.meta = meta;
this.piq = piq;
}
public static OrderSecurityAlgo from_order_security(OrderSecurity os) =>
new OrderSecurityAlgo(
os.order,
os.security,
os.algo ?? AlgoData.from_custom_def(os.order.Def.CustomDef),
os.meta,
os.piq);
public bool Equals(OrderSecurityAlgo other) =>
order == other.order &&
piq == other.piq &&
security == other.security &&
algo == other.algo;
public override bool Equals(object obj) =>
obj is OrderSecurityAlgo other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.auto_phase(
order.Key.GetHashCode(),
piq?.GetHashCode() ?? 0,
security.HasValue ? security.Value.Id.GetHashCode() : 0,
algo.GetHashCode());
public static bool operator ==(OrderSecurityAlgo a, OrderSecurityAlgo b) => a.Equals(b);
public static bool operator !=(OrderSecurityAlgo a, OrderSecurityAlgo b) => !a.Equals(b);
}
// This is a core data type on the front end, so data validation is strict, as bad values may yield weird/difficult to track bugs.
// Descriptive factory methods are favored over public constructors, as they are less likely to be misused.
readonly struct OrderSecurityRootPair : IEquatable<OrderSecurityRootPair> {
public readonly OrderSecurityAlgo order;
readonly OrderSecurityAlgo? _root;
OrderSecurityRootPair(OrderSecurityAlgo order) {
this.order = order;
_root = null;
}
OrderSecurityRootPair(OrderSecurityAlgo order, OrderSecurityAlgo? root) {
this.order = order;
_root = root;
}
public OrderSecurityAlgo root => _root ?? order;
public static OrderSecurityRootPair from_order_security(OrderSecurity order) =>
new OrderSecurityRootPair(OrderSecurityAlgo.from_order_security(order));
public static OrderSecurityRootPair from_order_security(OrderSecurity order, OrderSecurity root) =>
new OrderSecurityRootPair(
OrderSecurityAlgo.from_order_security(order),
OrderSecurityAlgo.from_order_security(root));
public bool Equals(OrderSecurityRootPair other) =>
order == other.order &&
_root == other._root;
public override bool Equals(object obj) =>
obj is OrderSecurityRootPair other && Equals(other);
public override int GetHashCode() =>
_root.HasValue ?
(order.GetHashCode() % (1 << 15)) | (_root.Value.GetHashCode() % (1 << 15) << 16) :
order.GetHashCode() % (1 << 15);
public static bool operator ==(OrderSecurityRootPair a, OrderSecurityRootPair b) => a.Equals(b);
public static bool operator !=(OrderSecurityRootPair a, OrderSecurityRootPair b) => !a.Equals(b);
}
static class OrderSecurityHelper {
public static readonly Func<OrderSecurity, uint>
key_fn = o => o.order.Key,
parent_key_fn = o => o.order.ParentKey;
public static readonly Func<OrderSecurityRootPair, uint>
root_pair_key_fn = o => o.order.order.Key,
root_pair_parent_key_fn = o => o.order.order.ParentKey;
}
}
@@ -1,422 +1,483 @@
using bts;
using bts.api;
using bts.api.orderman;
using bts.co2;
using bts.spark;
using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Media;
using static mbts.ui.utilities.DisplayNameHelper;
namespace mbts.spark {
static class OrderUtils {
public static readonly Func<OrderRecordImmutable, uint> RecordKeySelector = o => o.Key;
public static uint filled(this OrderRecordImmutable order) =>
order.HasState ? order.State.FilledQuantity : 0u;
public static double fill_ratio(this OrderRecordImmutable order) =>
order.HasState ? order.State.FilledQuantity / (double)order.State.Quantity : double.NaN;
public static double quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.Quantity : 0;
public static int working_quantity(this OrderRecordImmutable order) =>
order.HasState ? (int)order.State.Quantity - (int)order.State.FilledQuantity : 0;
public static double price(this OrderRecordImmutable order) =>
order.HasState ? order.State.Price : double.NaN;
public static double ui_price(this OrderRecordImmutable order) {
if (order.HasState) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Stop && !order.stop_or_stop_limit_has_been_triggered()) {
return order.stop_price();
}
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.StopLimit && !order.stop_or_stop_limit_has_been_triggered()) {
return order.stop_limit_price();
}
return order.State.Price;
}
return double.NaN;
}
public static double stop_price(this OrderRecordImmutable order) =>
order.HasState && order.State.HasStop && order.State.Stop.HasNativeState ? order.State.Stop.NativeState.StopPx : double.NaN;
public static double stop_limit_price(this OrderRecordImmutable order) =>
order.HasState && order.State.HasStopLimit && order.State.StopLimit.HasNativeState ? order.State.StopLimit.NativeState.StopPx : double.NaN;
public static double avg_price(this OrderRecordImmutable order) =>
order.HasState ? order.State.AvgPrice : double.NaN;
public static double last_price(this OrderRecordImmutable order) =>
order.HasState ? order.State.LastPrice : double.NaN;
public static string last_msg(this OrderRecordImmutable order) =>
order.HasState ? order.State.LastMsg : string.Empty;
public static IReadOnlyDictionary<string, DynamicOrderParam> dynamic_custom_state(this OrderRecordImmutable order) =>
order.HasState && order.State.HasDynamic ?
(order.State.Dynamic.CustomState ?? DictionaryHelper.empty<string, DynamicOrderParam>()) :
DictionaryHelper.empty<string, DynamicOrderParam>();
public static DateTime created(this OrderRecordImmutable order) =>
order.HasState && order.State.HasCreated ? order.State.Created.ToDateTime().ToLocalTime() : DateTime.MinValue;
public static DateTime last_change(this OrderRecordImmutable order) =>
order.HasState && order.State.HasLastChange ? order.State.LastChange.ToDateTime().ToLocalTime() : DateTime.MinValue;
public static OrderStatus status(this OrderRecordImmutable order) =>
order.HasState ? order.State.Status : OrderStatus.Error;
public static uint security_key(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.SecurityKey : 0u;
public static Side side(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.Side : Side.Undefined;
public static string user(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.User : string.Empty;
public static uint user_id(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.UserId : 0;
public static UserTuple user_tuple(this OrderRecordImmutable order) =>
new(order.user_id(), order.user());
public static string account(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.Account : string.Empty;
public static uint account_id(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.AccountId : 0;
public static CustomOrderDefinition.CustomOneofCase order_type(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef ? order.Def.CustomDef.CustomCase : CustomOrderDefinition.CustomOneofCase.None;
/// <summary>
/// Unwraps all <see cref="CompositeOrderDefinition"/>s (if any) to return the underlying order type.
/// </summary>
/// <param name="order">The order who's underlying algo will be returned.</param>
/// <returns>The first non-composite algo definition in the specified <see cref="CustomOrderDefinition"/>.</returns>
public static CustomOrderDefinition.CustomOneofCase actual_order_type(this OrderRecordImmutable order) {
if (!order.HasDef || !order.Def.HasCustomDef)
return CustomOrderDefinition.CustomOneofCase.None;
var cdef = order.Def.CustomDef;
while (cdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
if (!cdef.Composite.HasDefinition)
return CustomOrderDefinition.CustomOneofCase.None;
cdef = cdef.Composite.Definition;
}
return cdef.CustomCase;
}
public static string dynamic_order_type_display_name(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.HasDynamic ? order.Def.CustomDef.Dynamic.DynamicOrderType : string.Empty;
public static uint algo_template_key(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite ?
order.Def.CustomDef.Composite.AlgoTemplateKey : 0u;
/// <summary>
/// If the definitions is a <see cref="CompositeOrderDefinition"/>, returns the underlying algo, otherwise returns <paramref name="custom_def"/> iteself.
/// </summary>
/// <param name="custom_def">The definition to for which the underlying algo will be returned.</param>
/// <returns>The first non-composite algo definition in the specified <see cref="CustomOrderDefinition"/>.</returns>
public static CustomOrderDefinitionImmutable actual(this CustomOrderDefinitionImmutable custom_def) {
while (custom_def.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
custom_def = custom_def.Composite.Definition;
return custom_def;
}
public static OrderSubType sub_type(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.SubType : OrderSubType.None;
public static TimeInForce time_in_force(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.TimeInForce : TimeInForce.Undefined;
public static uint attached_target_order_key(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.AttachTargetOrderKey : 0;
public static bool is_exchange_order(this OrderRecordImmutable order) {
if (order.HasDef && order.Def.HasCustomDef) {
switch (order.Def.CustomDef.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Limit:
case CustomOrderDefinition.CustomOneofCase.Market:
case CustomOrderDefinition.CustomOneofCase.Stop:
case CustomOrderDefinition.CustomOneofCase.StopLimit:
case CustomOrderDefinition.CustomOneofCase.GlbxIceberg: return true;
}
}
return false;
}
public static bool can_attach(this OrderRecordImmutable order) =>
order.working_quantity() > 0;
public static bool can_be_attached_to(this OrderRecordImmutable order) {
if (order.HasDef && order.Def.HasCustomDef) {
// TODO: implement with real logic (this is impl is a placeholder for development purposes)
switch (order.Def.CustomDef.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Iceberg:
case CustomOrderDefinition.CustomOneofCase.Dynamic:
return true;
}
}
return false;
}
public static bool can_detach(this OrderRecordImmutable order) =>
order.attached_target_order_key() == 0 && order.has_parent();
public static string display_name(this OrderSecurity order_tuple) =>
display_name(order_tuple.order, order_tuple.algo);
public static string display_name(OrderRecordImmutable order, AlgoData? algo, SecurityImmutable? security = null) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader && security.HasValue)
return security.Value.ToString();
if (algo.HasValue) {
return algo.Value.name;
} else if (order.HasDef && order.Def.HasCustomDef) {
return order.Def.CustomDef.HasDynamic ?
order.Def.CustomDef.Dynamic.DynamicOrderType :
order.Def.CustomDef.CustomCase.display_name();
}
return "Undefined";
}
public static string full_description(this OrderRecordImmutable order, SecurityImmutable security) {
StringBuilder sb = new StringBuilder();
string sec_key_text;
if (order.HasDef) {
sec_key_text = $"Security: {order.Def.SecurityKey}";
if (order.HasState) {
sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}");
sb.AppendLine($"Filled: {filled(order)} / {order.State.Quantity}");
} else {
sb.AppendLine($"{order.Def.Side}: (price-unknown)");
sb.AppendLine("Filled: (quantity-unknown)");
}
sb.AppendLine($"TIF: {order.Def.TimeInForce}");
sb.AppendLine($"Type: {display_name(order.Def.CustomDef.CustomCase)}");
} else {
sec_key_text = "Security: (id-unknown)";
sb.AppendLine($"(side-unknown): (price-unknown)");
sb.AppendLine("Filled: (quantity-unknown)");
}
sb.AppendLine($"Order: {order.Key}");
if (order.has_parent()) {
sb.AppendLine(sec_key_text);
sb.Append($"Parent Key: {order.ParentKey}");
} else
sb.Append(sec_key_text);
return sb.ToString();
}
public static string short_description(this OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{spec.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
public static string short_description(
SecurityImmutable security, Side side, double price, double quantity) =>
new StringBuilderEx(
security.ToString(), " ",
side.ToString(), " ",
price_quantity_description(price, quantity, security.spec_or_default())
).ToString();
public static string short_description(this OrderRecordImmutable order, SecurityImmutable? security) {
var spec = security.spec_or_default();
return new StringBuilderEx(
security.display_name(), " ",
order.side().ToString(), " ",
price_quantity_description(order.price(), order.quantity(), spec), " (",
filled_status_description(order, spec), ")"
).ToString();
}
public static string price_quantity_description(
double price, double quantity, ContractSpecificationImmutable spec) =>
new StringBuilderEx(quantity.ToString(), " @ ", spec.format(price) ?? price.ToString("#0.00##")).ToString();
public static string filled_status_description(
this OrderRecordImmutable order,
ContractSpecificationImmutable spec,
double display_qty_divisor = 1
) {
var sb = new StringBuilderEx(
"filled ", ((double)order.filled()).safe_divide(display_qty_divisor).ToString());
if (order.filled() > 0)
sb.Add(" @ ", spec.format(order.avg_price()));
sb.Add(", ", camel_to_title_case(order.status().ToString(), TextCapitalizationFormat.NoCaps));
return sb.ToString();
}
public static bool has_parent(this OrderRecordImmutable order) =>
order.ParentKey != 0;
public static bool is_active(this OrderRecordImmutable order) =>
order.HasState && order.State.Status == OrderStatus.Working;
public static bool is_non_terminal(this OrderRecordImmutable order) {
if (!order.HasState)
return false;
switch (order.State.Status) {
case OrderStatus.PendingWorking: return true;
case OrderStatus.Working: return true;
case OrderStatus.Inactive: return true;
case OrderStatus.Disconnected: return true;
default: return false;
}
}
public static bool stop_or_stop_limit_has_been_triggered(this OrderRecordImmutable order) {
if (order.HasState && (order.order_type() == CustomOrderDefinition.CustomOneofCase.Stop || order.order_type() == CustomOrderDefinition.CustomOneofCase.StopLimit)) {
var native_state = order.State.native_order_state();
if (native_state.HasValue) {
if (order.State.HasStop || order.State.HasStopLimit) {
return native_state.Value.NativeType == NativeOrderType.Limit;
}
} else {
return false;
}
}
return false;
}
public static string type_id(this CustomOrderDefinition.CustomOneofCase order_type) =>
order_type.ToString().ToUpper();
public static string display_name(this OrderSecurityAlgo order_sec_algo) =>
display_name(order_sec_algo.order, order_sec_algo.algo, order_sec_algo.security);
public static string display_name(this CustomOrderDefinitionImmutable algo) =>
algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic ? algo.Dynamic.DynamicOrderType : algo.CustomCase.display_name();
public static string display_name(this CustomOrderDefinition.CustomOneofCase order_type) =>
camel_to_title_case(Regex.Replace(order_type.ToString(), "Order", string.Empty, RegexOptions.IgnoreCase));
public static bool is_bts_algo_type(this CustomOrderDefinition.CustomOneofCase algo_type) {
switch (algo_type) {
case CustomOrderDefinition.CustomOneofCase.Iceberg:
case CustomOrderDefinition.CustomOneofCase.Lean:
case CustomOrderDefinition.CustomOneofCase.Join:
case CustomOrderDefinition.CustomOneofCase.Cover:
case CustomOrderDefinition.CustomOneofCase.Top:
case CustomOrderDefinition.CustomOneofCase.Spreader: return true;
}
return false;
}
public static Brush badge_fill(AlgoDefinitionMetadata? algo_meta, OrderMetadata order_meta) =>
new SolidColorBrush(badge_color(algo_meta, order_meta));
public static Color badge_color(AlgoDefinitionMetadata? algo_meta, OrderMetadata order_meta) =>
algo_meta?.badge_color ?? order_meta.Color.rgb_color();
public static string order_collection_summary(
double best_price, double best_price_volume, double total_volume) =>
order_collection_summary(
best_price,
best_price_volume,
total_volume,
SecurityDataHelper.Defaults.ContractSpecificationImmutable);
public static string order_collection_summary(
double best_price,
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec
) {
if (total_volume == 0)
return string.Empty;
return total_volume == best_price_volume ?
$"{best_price_volume} @ {spec.format(best_price)}" :
$"{best_price_volume} ({total_volume}) @ {spec.format(best_price)}";
}
public static string order_collection_summary(
double best_price,
double avg_price,
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec) {
if (total_volume == 0)
return string.Empty;
return total_volume == best_price_volume ?
$"{best_price_volume} @ {spec.format(best_price)}" :
$"{best_price_volume} @ {spec.format(best_price)} ({total_volume} @ {spec.format(avg_price)})";
}
public static string past_tense(this Side side) {
switch (side) {
case Side.Buy: return "Bought";
case Side.Sell: return "Sold";
default: return side.ToString();
}
}
public static string abbreviate(this Side side) {
switch (side) {
case Side.Buy: return "B";
case Side.Sell: return "S";
case Side.Undefined:
default: return "E";
}
}
public static string abbreviate_structure(CustomOrderDefinitionImmutable def) {
var builder = new StringBuilder();
impl(builder, def.CloneToMutable());
return builder.ToString();
// local methods
void impl(StringBuilder sb, CustomOrderDefinition mdef) {
sb.Append(abbreviate(mdef.CustomCase));
foreach (var cad in OrderDataHelper.get_child_algo_data(def.CloneToMutable())) {
var child = cad.get_child(mdef);
sb.Append(".[");
impl(sb, child);
sb.Append("]");
}
}
}
static readonly Dictionary<CustomOrderDefinition.CustomOneofCase, string> _abbreviated_exchange_types =
get_word_tree_abbreviations(OrderDataHelper.all_order_types.Select(t => t.ToString().ToUpper()))
.ToDictionary(kv => EnumHelper.parse<CustomOrderDefinition.CustomOneofCase>(kv.Key), kv => kv.Value);
public static string abbreviate(this CustomOrderDefinition.CustomOneofCase type) =>
_abbreviated_exchange_types.TryGetValue(type, out string result) ? result : type.ToString();
public static string order_sub_type_display_name(OrderSubType sub_type, bool use_long_name) {
switch (sub_type) {
case OrderSubType.HedgingLeg:
return use_long_name ? "Hedging (H)" : "H";
case OrderSubType.QuotingLeg:
return use_long_name ? "Quoting (Q)" : "Q";
case OrderSubType.None:
return use_long_name ? "None" : string.Empty;
default:
return string.Empty;
}
}
public static AggressorSide to_aggressor(this Side side) {
switch (side) {
case Side.Buy: return AggressorSide.Buy;
case Side.Sell: return AggressorSide.Sell;
default: return AggressorSide.None;
}
}
}
}
using bts;
using bts.api;
using bts.api.orderman;
using bts.co2;
using bts.spark;
using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Media;
using static mbts.ui.utilities.DisplayNameHelper;
namespace mbts.spark {
static class OrderUtils {
public static readonly Func<OrderRecordImmutable, uint> RecordKeySelector = o => o.Key;
#region OrderStateImmutable extension methods
public static double quantity(this OrderStateImmutable state) =>
Convert.ToDouble(state.Quantity) +
(state.HasFractionalQuantity ? state.FractionalQuantity.Fraction : 0.0);
public static double filled_quantity(this OrderStateImmutable state) =>
Convert.ToDouble(state.FilledQuantity) +
(state.HasFractionalFilledQuantity ? state.FractionalFilledQuantity.Fraction : 0.0);
public static double working_quantity(this OrderStateImmutable state) =>
state.quantity() - state.filled_quantity();
public static double fill_ratio(this OrderStateImmutable state) =>
state.filled_quantity() / state.quantity();
#endregion
public static double filled_quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.filled_quantity() : 0.0;
public static double fill_ratio(this OrderRecordImmutable order) =>
order.HasState ? order.State.FilledQuantity / (double)order.State.Quantity : double.NaN;
public static double quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.quantity() : 0;
public static double working_quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.working_quantity() : 0;
public static double price(this OrderRecordImmutable order) =>
order.HasState ? order.State.Price : double.NaN;
public static double ui_price(this OrderRecordImmutable order) {
if (order.HasState) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Stop && !order.stop_or_stop_limit_has_been_triggered()) {
return order.stop_price();
}
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.StopLimit && !order.stop_or_stop_limit_has_been_triggered()) {
return order.stop_limit_price();
}
return order.State.Price;
}
return double.NaN;
}
public static double stop_price(this OrderRecordImmutable order) =>
order.HasState && order.State.HasStop && order.State.Stop.HasNativeState ? order.State.Stop.NativeState.StopPx : double.NaN;
public static double stop_limit_price(this OrderRecordImmutable order) =>
order.HasState && order.State.HasStopLimit && order.State.StopLimit.HasNativeState ? order.State.StopLimit.NativeState.StopPx : double.NaN;
public static double avg_price(this OrderRecordImmutable order) =>
order.HasState ? order.State.AvgPrice : double.NaN;
public static double last_price(this OrderRecordImmutable order) =>
order.HasState ? order.State.LastPrice : double.NaN;
public static string last_msg(this OrderRecordImmutable order) =>
order.HasState ? order.State.LastMsg : string.Empty;
public static IReadOnlyDictionary<string, DynamicOrderParam> dynamic_custom_state(this OrderRecordImmutable order) =>
order.HasState && order.State.HasDynamic ?
(order.State.Dynamic.CustomState ?? DictionaryHelper.empty<string, DynamicOrderParam>()) :
DictionaryHelper.empty<string, DynamicOrderParam>();
public static DateTime created(this OrderRecordImmutable order) =>
order.HasState && order.State.HasCreated ? order.State.Created.ToDateTime().ToLocalTime() : DateTime.MinValue;
public static DateTime last_change(this OrderRecordImmutable order) =>
order.HasState && order.State.HasLastChange ? order.State.LastChange.ToDateTime().ToLocalTime() : DateTime.MinValue;
public static OrderStatus status(this OrderRecordImmutable order) =>
order.HasState ? order.State.Status : OrderStatus.Error;
public static uint security_key(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.SecurityKey : 0u;
public static Side side(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.Side : Side.Undefined;
public static string user(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.User : string.Empty;
public static uint user_id(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.UserId : 0;
public static UserTuple user_tuple(this OrderRecordImmutable order) =>
new(order.user_id(), order.user());
public static string account(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.Account : string.Empty;
public static uint account_id(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.AccountId : 0;
public static CustomOrderDefinition.CustomOneofCase order_type(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef ? order.Def.CustomDef.CustomCase : CustomOrderDefinition.CustomOneofCase.None;
/// <summary>
/// Unwraps all <see cref="CompositeOrderDefinition"/>s (if any) to return the underlying order type.
/// </summary>
/// <param name="order">The order who's underlying algo will be returned.</param>
/// <returns>The first non-composite algo definition in the specified <see cref="CustomOrderDefinition"/>.</returns>
public static CustomOrderDefinition.CustomOneofCase actual_order_type(this OrderRecordImmutable order) {
if (!order.HasDef || !order.Def.HasCustomDef)
return CustomOrderDefinition.CustomOneofCase.None;
var cdef = order.Def.CustomDef;
while (cdef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
if (!cdef.Composite.HasDefinition)
return CustomOrderDefinition.CustomOneofCase.None;
cdef = cdef.Composite.Definition;
}
return cdef.CustomCase;
}
public static string dynamic_order_type_display_name(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.HasDynamic ? order.Def.CustomDef.Dynamic.DynamicOrderType : string.Empty;
public static uint algo_template_key(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite ?
order.Def.CustomDef.Composite.AlgoTemplateKey : 0u;
/// <summary>
/// If the definitions is a <see cref="CompositeOrderDefinition"/>, returns the underlying algo, otherwise returns <paramref name="custom_def"/> iteself.
/// </summary>
/// <param name="custom_def">The definition to for which the underlying algo will be returned.</param>
/// <returns>The first non-composite algo definition in the specified <see cref="CustomOrderDefinition"/>.</returns>
public static CustomOrderDefinitionImmutable actual(this CustomOrderDefinitionImmutable custom_def) {
while (custom_def.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
custom_def = custom_def.Composite.Definition;
return custom_def;
}
public static OrderSubType sub_type(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.SubType : OrderSubType.None;
public static TimeInForce time_in_force(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.TimeInForce : TimeInForce.Undefined;
public static uint attached_target_order_key(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.AttachTargetOrderKey : 0;
public static bool is_exchange_order(this OrderRecordImmutable order) {
if (order.HasDef && order.Def.HasCustomDef) {
switch (order.Def.CustomDef.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Limit:
case CustomOrderDefinition.CustomOneofCase.Market:
case CustomOrderDefinition.CustomOneofCase.Stop:
case CustomOrderDefinition.CustomOneofCase.StopLimit:
case CustomOrderDefinition.CustomOneofCase.GlbxIceberg: return true;
}
}
return false;
}
public static bool can_attach(this OrderRecordImmutable order) =>
order.working_quantity() > 0;
public static bool can_be_attached_to(this OrderRecordImmutable order) {
if (order.HasDef && order.Def.HasCustomDef) {
// TODO: implement with real logic (this is impl is a placeholder for development purposes)
switch (order.Def.CustomDef.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Iceberg:
case CustomOrderDefinition.CustomOneofCase.Dynamic:
return true;
}
}
return false;
}
public static bool can_detach(this OrderRecordImmutable order) =>
order.attached_target_order_key() == 0 && order.has_parent();
public static string display_name(this OrderSecurity order_tuple) =>
display_name(order_tuple.order, order_tuple.algo);
public static string display_name(OrderRecordImmutable order, AlgoData? algo, SecurityImmutable? security = null) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader && security.HasValue)
return security.Value.ToString();
if (algo.HasValue) {
return algo.Value.name;
} else if (order.HasDef && order.Def.HasCustomDef) {
return order.Def.CustomDef.HasDynamic ?
order.Def.CustomDef.Dynamic.DynamicOrderType :
order.Def.CustomDef.CustomCase.display_name();
}
return "Undefined";
}
public static string full_description(
this OrderRecordImmutable order,
SecurityImmutable security,
bts.api.domain.TickDisplaySettingsImmutable? qty_display = null) {
StringBuilder sb = new StringBuilder();
string sec_key_text;
if (order.HasDef) {
sec_key_text = $"Security: {order.Def.SecurityKey}";
if (order.HasState) {
qty_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var qty_str = qty_display.Value.format(order.quantity());
var filled_qty_str = qty_display.Value.format(order.filled_quantity());
sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}");
sb.AppendLine($"Filled: {filled_qty_str} / {qty_str}");
} else {
sb.AppendLine($"{order.Def.Side}: (price-unknown)");
sb.AppendLine("Filled: (quantity-unknown)");
}
sb.AppendLine($"TIF: {order.Def.TimeInForce}");
sb.AppendLine($"Type: {display_name(order.Def.CustomDef.CustomCase)}");
} else {
sec_key_text = "Security: (id-unknown)";
sb.AppendLine($"(side-unknown): (price-unknown)");
sb.AppendLine("Filled: (quantity-unknown)");
}
sb.AppendLine($"Order: {order.Key}");
if (order.has_parent()) {
sb.AppendLine(sec_key_text);
sb.Append($"Parent Key: {order.ParentKey}");
} else
sb.Append(sec_key_text);
return sb.ToString();
}
public static string short_description(this OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{spec.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
public static string short_description(
SecurityImmutable security, Side side, double price, double quantity) =>
new StringBuilderEx(
security.ToString(), " ",
side.ToString(), " ",
price_quantity_description(price, quantity, security.spec_or_default())
).ToString();
public static string short_description(this OrderRecordImmutable order, SecurityImmutable? security) {
var spec = security.spec_or_default();
return new StringBuilderEx(
security.display_name(), " ",
order.side().ToString(), " ",
price_quantity_description(order.price(), order.quantity(), spec), " (",
filled_status_description(order, spec), ")"
).ToString();
}
public static string price_quantity_description(
double price, double quantity, ContractSpecificationImmutable spec) =>
price_quantity_description(
price, quantity, spec.tick_factors().to_api_tick_display_settingsi());
public static string price_quantity_description(
double price,
double quantity,
bts.api.domain.TickDisplaySettingsImmutable? price_display = null,
bts.api.domain.TickDisplaySettingsImmutable? quantity_display = null) {
price_display ??= SecurityDataHelper.Defaults.price_display_settingsi;
quantity_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
return $"{quantity_display.Value.format(quantity)} @ {price_display.Value.format(price)}";
}
public static string filled_status_description(
this OrderRecordImmutable order,
ContractSpecificationImmutable spec,
bts.api.domain.TickDisplaySettingsImmutable? qty_display = null
) {
qty_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var sb = new StringBuilderEx(
"filled ", qty_display.Value.format(order.filled_quantity()));
if (order.filled_quantity() > 0)
sb.Add(" @ ", spec.format(order.avg_price()));
sb.Add(", ", camel_to_title_case(order.status().ToString(), TextCapitalizationFormat.NoCaps));
return sb.ToString();
}
public static string update_description(
OrderRecordImmutable order,
double? new_price = null,
double? new_quantity = null,
bts.api.domain.TickDisplaySettingsImmutable? price_display = null,
bts.api.domain.TickDisplaySettingsImmutable? quantity_display = null
) {
var price = new_price ?? order.price();
var quantity = new_quantity ?? order.working_quantity();
if (price == order.price() && quantity == order.working_quantity()) {
// nothing actually changed
return null;
}
price_display ??= SecurityDataHelper.Defaults.price_display_settingsi;
quantity_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var from_desc = price_quantity_description(
order.quantity(), order.price(), price_display, quantity_display);
var to_desc = price_quantity_description(
quantity, price, price_display, quantity_display);
return $"{from_desc} to {to_desc}";
}
public static bool has_parent(this OrderRecordImmutable order) =>
order.ParentKey != 0;
public static bool is_active(this OrderRecordImmutable order) =>
order.HasState && order.State.Status == OrderStatus.Working;
public static bool is_non_terminal(this OrderRecordImmutable order) {
if (!order.HasState)
return false;
switch (order.State.Status) {
case OrderStatus.PendingWorking: return true;
case OrderStatus.Working: return true;
case OrderStatus.Inactive: return true;
case OrderStatus.Disconnected: return true;
default: return false;
}
}
public static bool stop_or_stop_limit_has_been_triggered(this OrderRecordImmutable order) {
if (order.HasState && (order.order_type() == CustomOrderDefinition.CustomOneofCase.Stop || order.order_type() == CustomOrderDefinition.CustomOneofCase.StopLimit)) {
var native_state = order.State.native_order_state();
if (native_state.HasValue) {
if (order.State.HasStop || order.State.HasStopLimit) {
return native_state.Value.NativeType == NativeOrderType.Limit;
}
} else {
return false;
}
}
return false;
}
public static string type_id(this CustomOrderDefinition.CustomOneofCase order_type) =>
order_type.ToString().ToUpper();
public static string display_name(this OrderSecurityAlgo order_sec_algo) =>
display_name(order_sec_algo.order, order_sec_algo.algo, order_sec_algo.security);
public static string display_name(this CustomOrderDefinitionImmutable algo) =>
algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic ? algo.Dynamic.DynamicOrderType : algo.CustomCase.display_name();
public static string display_name(this CustomOrderDefinition.CustomOneofCase order_type) =>
camel_to_title_case(Regex.Replace(order_type.ToString(), "Order", string.Empty, RegexOptions.IgnoreCase));
public static bool is_bts_algo_type(this CustomOrderDefinition.CustomOneofCase algo_type) {
switch (algo_type) {
case CustomOrderDefinition.CustomOneofCase.Iceberg:
case CustomOrderDefinition.CustomOneofCase.Lean:
case CustomOrderDefinition.CustomOneofCase.Join:
case CustomOrderDefinition.CustomOneofCase.Cover:
case CustomOrderDefinition.CustomOneofCase.Top:
case CustomOrderDefinition.CustomOneofCase.Spreader: return true;
}
return false;
}
public static Brush badge_fill(AlgoDefinitionMetadata? algo_meta, OrderMetadata order_meta) =>
new SolidColorBrush(badge_color(algo_meta, order_meta));
public static Color badge_color(AlgoDefinitionMetadata? algo_meta, OrderMetadata order_meta) =>
algo_meta?.badge_color ?? order_meta.Color.rgb_color();
public static string order_collection_summary(
double best_price, double best_price_volume, double total_volume) =>
order_collection_summary(
best_price,
best_price_volume,
total_volume,
SecurityDataHelper.Defaults.ContractSpecificationImmutable);
public static string order_collection_summary(
double best_price,
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec
) {
if (total_volume == 0)
return string.Empty;
return total_volume == best_price_volume ?
$"{best_price_volume} @ {spec.format(best_price)}" :
$"{best_price_volume} ({total_volume}) @ {spec.format(best_price)}";
}
public static string order_collection_summary(
double best_price,
double avg_price,
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec) {
if (total_volume == 0)
return string.Empty;
return total_volume == best_price_volume ?
$"{best_price_volume} @ {spec.format(best_price)}" :
$"{best_price_volume} @ {spec.format(best_price)} ({total_volume} @ {spec.format(avg_price)})";
}
public static string past_tense(this Side side) {
switch (side) {
case Side.Buy: return "Bought";
case Side.Sell: return "Sold";
default: return side.ToString();
}
}
public static string abbreviate(this Side side) {
switch (side) {
case Side.Buy: return "B";
case Side.Sell: return "S";
case Side.Undefined:
default: return "E";
}
}
public static string abbreviate_structure(CustomOrderDefinitionImmutable def) {
var builder = new StringBuilder();
impl(builder, def.CloneToMutable());
return builder.ToString();
// local methods
void impl(StringBuilder sb, CustomOrderDefinition mdef) {
sb.Append(abbreviate(mdef.CustomCase));
foreach (var cad in OrderDataHelper.get_child_algo_data(def.CloneToMutable())) {
var child = cad.get_child(mdef);
sb.Append(".[");
impl(sb, child);
sb.Append("]");
}
}
}
static readonly Dictionary<CustomOrderDefinition.CustomOneofCase, string> _abbreviated_exchange_types =
get_word_tree_abbreviations(OrderDataHelper.all_order_types.Select(t => t.ToString().ToUpper()))
.ToDictionary(kv => EnumHelper.parse<CustomOrderDefinition.CustomOneofCase>(kv.Key), kv => kv.Value);
public static string abbreviate(this CustomOrderDefinition.CustomOneofCase type) =>
_abbreviated_exchange_types.TryGetValue(type, out string result) ? result : type.ToString();
public static string order_sub_type_display_name(OrderSubType sub_type, bool use_long_name) {
switch (sub_type) {
case OrderSubType.HedgingLeg:
return use_long_name ? "Hedging (H)" : "H";
case OrderSubType.QuotingLeg:
return use_long_name ? "Quoting (Q)" : "Q";
case OrderSubType.None:
return use_long_name ? "None" : string.Empty;
default:
return string.Empty;
}
}
public static AggressorSide to_aggressor(this Side side) {
switch (side) {
case Side.Buy: return AggressorSide.Buy;
case Side.Sell: return AggressorSide.Sell;
default: return AggressorSide.None;
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -25,6 +25,7 @@
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Margin="12,12,10,12"
MaxHeight="400"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Grid.IsSharedSizeScope="True"
ItemsSource="{Binding columns}"
@@ -76,7 +76,7 @@
<!--SPACING-->
<ColumnDefinition Width="8" />
<!--TIME PICKER-->
<ColumnDefinition Width="80" />
<ColumnDefinition Width="Auto" />
<!--PAD RIGHT-->
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
@@ -91,7 +91,6 @@
x:Name="time_picker"
Grid.Column="3"
Background="White"
Width="80"
TimeTuple="{Binding new_actual_time}"
KeyDown="time_picker_KeyDown">
<Validation.ErrorTemplate>
@@ -134,7 +134,14 @@
// don't initialize more than once
if (_time_editor_popup != null) return;
var adorner_layer = AdornerLayer.GetAdornerLayer(adorned_grid);
_time_editor_popup = new PopupAdorner(adorned_grid, vol_time_popup_button, _get_time_editor_control(), HorizontalPosition.Left, VerticalPosition.Top, 0.5 * ((ToggleButton)sender).ActualWidth, 0d) { IsHitTestVisible = true };
_time_editor_popup = new PopupAdorner(
adorned_grid,
vol_time_popup_button,
_get_time_editor_control(),
HorizontalPosition.Left,
VerticalPosition.Top,
44,
0d) { IsHitTestVisible = true };
_time_editor_popup.SetBinding(PopupAdorner.DataContextProperty, "globals");
_time_editor_popup.SetBinding(PopupAdorner.IsOpenProperty, new Binding("vol_time_popup_open") { Mode = BindingMode.TwoWay });
_time_editor_popup.Opened += _time_editor_popup_Opened;
@@ -2,11 +2,12 @@
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
namespace mbts.ui.shell {
public interface IBookmarks {
void save_bookmark(IShellWindow window);
Task save_bookmark(IShellWindow window);
void save_bookmark(WindowState window);
void remove(WindowState window);
void clear();
@@ -22,15 +23,16 @@ namespace mbts.ui.shell {
public BookmarksModel(ISettingsCollector settings) {
_settings_collector = settings;
}
public void save_bookmark(IShellWindow window) {
var state = _settings_collector.get_window_state(window);
public async Task save_bookmark(IShellWindow window) {
var state = await _settings_collector.get_window_state(window);
if (state != null) {
_bookmarks[state.title] = state;
}
}
public void save_bookmark(WindowState window) {
public void save_bookmark(WindowState window) =>
_bookmarks[window.title] = window;
}
public void clear() {
_bookmarks.Clear();
@@ -8,6 +8,8 @@
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@@ -24,9 +26,11 @@
MDConsumer consumer,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model) =>
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) =>
_window_factories = new() {
new MarketViewWindowFactory(this, bus, settings_hub, orders_model, position_model),
new MarketViewWindowFactory(
this, bus, settings_hub, orders_model, position_model, sec_meta_store),
new OptionsViewWindowFactory(this, bus),
new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub, orders_model.security_auxiliary_model),
};
@@ -24,12 +24,14 @@
using System.Reactive.Linq;
using System.Windows.Input;
using TickFactors = bts.api.domain.TickFactorsImmutable;
partial class MarketViewVM {
public class Row : DisposableViewModelBase, ISecurityMDRow, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly AnimationManager _animation = new();
readonly MyOrderSummarizer _order_summarizer = new();
readonly MyOrderSummarizer _order_summarizer;
readonly DeferrableActionWrapper _raise_invalidated;
readonly Property<double> _bid_price;
@@ -79,6 +81,9 @@
_bus = bus;
security_md = smd;
_orders_model = orders_model;
_order_summarizer = new(
smd.quantity_display.HasTickFactors ?
smd.quantity_display.TickFactors : new(new() { TickBase = 1, TickUnit = 1}));
_raise_invalidated = new(() => invalidated?.Invoke());
_day_position = new CellProperty<double>(this, nameof(day_position), fmt_display_qty_double);
@@ -444,11 +449,16 @@
OrderDataHelper.CompareUtils.ask_price_comparer,
OrderDataHelper.CompareUtils.order_record_id_eq_comparer);
int _best_bid_working_qty;
int _best_ask_working_qty;
int _position;
int _working_bid_qty;
int _working_ask_qty;
readonly TickFactors _tick_factors;
double _best_bid_working_qty;
double _best_ask_working_qty;
double _position;
double _working_bid_qty;
double _working_ask_qty;
public MyOrderSummarizer(TickFactors tick_factors) =>
_tick_factors = tick_factors;
// bid
public double best_working_bid => _bids.Count > 0 ? _bids.at_index(0).Key : double.NaN;
@@ -456,22 +466,22 @@
public double working_bid_qty => _working_bid_qty;
// ask
public double best_working_ask => _asks.Count > 0 ? _asks.at_index(0).Key : double.NaN;
public int best_working_ask_qty => _best_ask_working_qty;
public double best_working_ask_qty => _best_ask_working_qty;
public double working_ask_qty => _working_ask_qty;
// pos
public int position => _position;
public double position => _position;
public void add_order(OrderRecordImmutable o) {
switch (o.side()) {
case Side.Buy:
_position += (int)o.filled();
_position += o.filled_quantity();
if (o.is_active()) {
_working_bid_qty += o.working_quantity();
_bids.add(o.price(), o);
}
break;
case Side.Sell:
_position -= (int)o.filled();
_position -= o.filled_quantity();
if (o.is_active()) {
_working_ask_qty += o.working_quantity();
_asks.add(o.price(), o);
@@ -485,14 +495,14 @@
public void remove_order(OrderRecordImmutable o) {
switch (o.side()) {
case Side.Buy:
_position -= (int)o.filled();
_position -= o.filled_quantity();
if (o.is_active()) {
_working_bid_qty -= o.working_quantity();
_bids.remove(o.price(), o);
}
break;
case Side.Sell:
_position += (int)o.filled();
_position += o.filled_quantity();
if (o.is_active()) {
_working_ask_qty -= o.working_quantity();
_asks.remove(o.price(), o);
@@ -504,6 +514,7 @@
}
void _refresh() {
_position = _tick_factors.round(_position);
_best_bid_working_qty = _bids.Count > 0 ? _bids.at_index(0).Sum(o => o.working_quantity()) : 0;
_best_ask_working_qty = _asks.Count > 0 ? _asks.at_index(0).Sum(o => o.working_quantity()) : 0;
}
@@ -38,6 +38,26 @@ namespace bts.shell.market_view {
public static GridSettings DefaultGridSettings =>
GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria, enable_background_color: true);
public static GridSettings dark_theme_grid_settings =>
DefaultGridSettings.with(
selection_highlight: BTSDarkColors.selection_highlight.argb_color(),
background: BTSDarkColors.background.argb_color(),
font_color: BTSDarkColors.foreground.argb_color(),
columns: DefaultColumns.all.Select(c => {
Color? fg = c.strong_id<Columns>() switch {
Columns.Ask or Columns.AskDirectQty or Columns.AskMergedQty or Columns.AskImpliedQty or Columns.WorkingAsks => BTSDarkColors.ask_foreground,
Columns.Bid or Columns.BidDirectQty or Columns.BidMergedQty or Columns.BidImpliedQty or Columns.WorkingBids => BTSDarkColors.bid_foreground,
_ => null,
};
Color? bg = c.strong_id<Columns>() switch {
Columns.Ask or Columns.Bid => BTSDarkColors.dark_background,
_ => null
};
return c.with(
background_color_override: new(bg),
font_color_override: new(fg));
}));
public static fills.FillsSettings DefaultAuxiliaryFills {
get {
var grid = fills.FillsSettings.MiniGridSettings;
@@ -18,6 +18,7 @@ namespace mbts.spark {
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
@@ -56,6 +57,7 @@ namespace mbts.spark {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly UserSettingsHub _settings_hub;
readonly ObservableCollection<Row> _rows = new();
readonly IList<SecurityMD> _wrapped_rows;
@@ -81,12 +83,14 @@ namespace mbts.spark {
IBus bus,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
UserSettingsHub settings_hub,
IObservable<TableUpdate<SecurityMD, uint>> security_mds_source,
bool use_mouse_state_transitions = false) {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_settings_hub = settings_hub;
security_filter = new RegexFilterVM<Row>(r => r.security.ToString(), nameof(Row.security));
// rows
@@ -636,8 +640,8 @@ namespace mbts.spark {
state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_cols);
var settings_man = new WindowSettingsManager<bts.shell.orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, _position_model, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, orders_source, settings_man, true);
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, orders_source, settings_man, true);
foreach (var c in OrderBookVM.OrderBookColumnCollection.editable_columns) {
obvm.columns.Insert(0, c);
}
@@ -16,6 +16,8 @@ using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -29,6 +31,7 @@ namespace mbts.spark {
const string _window_type = "MarketView", _window_type_display_name = "Market View";
readonly OrdersModel _orders_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IPositionModel _position_model;
readonly AllowOnce _init_guard = new AllowOnce("MarketView");
readonly UserSettingsHub _settings_hub;
@@ -51,11 +54,13 @@ namespace mbts.spark {
IBus bus,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
MarketViewSettings state,
UserSettingsHub settings_hub)
: base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) {
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_state = state;
_settings_hub = settings_hub;
_settings_manager = settings_hub.create_mview_settings_manager(state.grid);
@@ -131,6 +136,7 @@ namespace mbts.spark {
_bus,
_orders_model,
_position_model,
_sec_meta_store,
_settings_hub,
security_md_map_src
.BufferLatest(TimeSpan.FromSeconds(1))
@@ -9,6 +9,8 @@ using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
using Spark.Core.Data;
using System;
using System.Composition;
using System.Linq;
@@ -23,18 +25,20 @@ namespace bts.shell {
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly UserSettingsHub _settings_hub;
readonly ISecurityMetadataStore _sec_meta_store;
public MarketViewWindowFactory(
MarketShellModule module,
IBus bus,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model) : base(module, "MarketView") {
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) : base(module, "MarketView") {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_settings_hub = settings_hub;
_sec_meta_store = sec_meta_store;
_dispose = bus.subscribe(SparkTags.ShowMarketViewTag).OnDispatcher().Subscribe(_show);
}
@@ -48,7 +52,7 @@ namespace bts.shell {
IShellWindow _create(MarketViewSettings state) =>
new MarketViewWindow(
this, _bus, _orders_model, _position_model, state, _settings_hub);
this, _bus, _orders_model, _position_model, _sec_meta_store, state, _settings_hub);
// migration rules
[Export(typeof(IMarketViewGridSettingsMigrationRule))]
@@ -41,6 +41,12 @@ namespace bts.shell.time_and_sales {
public static GridSettings DefaultGridSettings =>
GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria);
public static GridSettings dark_theme_grid_settings =>
DefaultGridSettings.with(
selection_highlight: BTSDarkColors.selection_highlight.argb_color(),
background: BTSDarkColors.background.argb_color(),
font_color: BTSDarkColors.foreground.argb_color());
[ProtoMember(1)]
public SecurityCriteria? security_criteria { get; }
@@ -8,12 +8,17 @@ using mbts.spark;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.spark;
using mbts.ui.utility;
using Spark.Settings;
using Spark.View;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace bts.ui {
@@ -30,7 +35,9 @@ namespace bts.ui {
ws_model = ws;
var actions_list = new List<SparkCommand>(2) {
SparkCommands.ShowGlobalAlerts,
SparkCommands.ShowWorkspaces
SparkCommands.ShowWorkspaces,
new SparkCommandCommand(
"Choose Theme", Icons.ViewSettings, new DialogCommand(mk_theme_picker_dialog, -60, -40))
};
if (Configuration.get<bts.config.toggles.ToastNotifications>().enabled) {
actions_list.Add(SparkCommands.ShowSettings);
@@ -46,6 +53,21 @@ namespace bts.ui {
}));
_bus = bus;
Window mk_theme_picker_dialog() {
var model = new ThemePickerModel(settings_hub);
var vm = new ThemePickerVM(model);
var view = new ThemePickerView() { };
var win = new Window() {
DataContext = vm,
Content = view,
Title = "Choose Theme",
SizeToContent = SizeToContent.WidthAndHeight,
Style = Application.Current.FindResource("BTSDialog") as Style
};
vm.RequestClose += (s, e) => WindowUtilities.force_close(win);
return win;
}
}
public ImageSource icon => Icons.Admin;
@@ -0,0 +1,38 @@
#nullable enable
namespace Spark.Settings {
using bts;
using mbts.persist;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
class ThemePickerModel {
readonly UserSettingsHub _settings_hub;
public ThemePickerModel(UserSettingsHub settings_hub) =>
_settings_hub = settings_hub;
public IObservable<UserSettingsTheme?> selected_theme =>
_settings_hub.subscribe_default_settings()
.Select(us => _settings_hub.themes.FirstOrDefault(t => t.name == us.last_picked_theme))
.DistinctUntilChanged();
public IEnumerable<UserSettingsTheme> themes =>
_settings_hub.themes;
public async Task<bool> set_theme(UserSettingsTheme theme) {
try {
Log.Gen.info($"Applying settings theme '{theme.name}'");
await _settings_hub.save_default(theme.value, true);
return true;
} catch (Exception ex) {
Log.Gen.error($"Error applying theme '{theme.name}': {ex}");
}
return false;
}
}
}
@@ -0,0 +1,52 @@
#nullable enable
namespace Spark.Settings {
using bts;
using bts.collections;
using mbts;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
class ThemePickerVM : DisposableViewModelBase, IRequestViewClose {
readonly ThemePickerModel _model;
readonly Property<UserSettingsTheme?> _selected_theme;
public ThemePickerVM(ThemePickerModel model) {
_model = model;
themes.AddRange(model.themes);
_selected_theme = backing(nameof(selected_theme), model.selected_theme.OnDispatcher());
commit_cmd = observant_cmd(
commit, t => t is not null, _selected_theme.observe_current(true).OnDispatcher());
cancel_cmd = new Command(close);
async Task commit(UserSettingsTheme? theme) {
if (theme is null) {
Log.Ui.warn($"Unable to apply theme: {nameof(theme)} arg is null");
return;
}
await _model.set_theme(theme);
close();
}
void close() =>
RequestClose?.Invoke(this, EventArgs.Empty);
}
public event EventHandler? RequestClose;
public ObservableCollection<UserSettingsTheme> themes { get; } = new();
public UserSettingsTheme? selected_theme {
get => _selected_theme.Value;
set => _selected_theme.set(value);
}
public ICommand commit_cmd { get; }
public ICommand cancel_cmd { get; }
}
}
@@ -0,0 +1,45 @@
<UserControl
x:Class="Spark.View.ThemePickerView"
x:ClassModifier="internal"
x:Name="me"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:analytics="clr-namespace:mbts.analytics"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:view="clr-namespace:Spark.View">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/CursorsEx.xaml"/>
<ResourceDictionary Source="/view/Resources/DataTemplates.xaml"/>
<ResourceDictionary Source="/view/Controls/ExpandedContentSelector.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ComboBox
Margin="12"
ItemsSource="{Binding themes}"
SelectedItem="{Binding selected_theme}"
DisplayMemberPath="name" />
<c:DialogSkirtOKCancel
Grid.Row="1"
Grid.ColumnSpan="2"
VerticalAlignment="Bottom"
CloseOnOK="False"
CloseOnCancel="False"
OKCommand="{Binding commit_cmd}"
OKCommandParameter="{Binding selected_theme}"
CancelCommand="{Binding cancel_cmd}" />
</Grid>
</UserControl>
@@ -0,0 +1,9 @@
#nullable enable
namespace Spark.View {
using System.Windows.Controls;
partial class ThemePickerView : UserControl {
public ThemePickerView() =>
InitializeComponent();
}
}
@@ -0,0 +1,24 @@
namespace bts.shell {
using mbts.spark.filters;
using mbts.ui;
using ProtoBuf;
[ProtoContract]
class SyntheticManagementFilterSettings {
[ProtoMember(1)]
public string description;
[ProtoMember(2)]
public TimeFilterTuple create_time;
[ProtoMember(3)]
public string name;
[ProtoMember(4)]
public IntMinMaxState n_legs;
[ProtoMember(5)]
public UIntMinMaxState n_working_orders;
[ProtoMember(6)]
public string security_key;
[ProtoMember(7)]
public uint[] user;
}
}
@@ -0,0 +1,111 @@
namespace bts.shell {
using mbts.ui;
using mbts.ui.settings;
using ProtoBuf;
using System.Collections.Generic;
using Columns = mbts.ui.spark.SyntheticManagementView.Columns;
using ColHeaders = mbts.ui.controls.DIYGrid.DefaultColumnHeaders;
using ColWidths = mbts.ui.controls.DIYGrid.DefaultColumnWidths;
[ProtoContract]
class SyntheticManagementSettings {
public const int Version = 1;
[ProtoMember(1)]
public readonly List<SortingCriteria> sorting_criteria;
[ProtoMember(2)]
public readonly SyntheticManagementFilterSettings filters;
[ProtoMember(3)]
public readonly GridSettings grid;
[ProtoMember(4)]
public readonly SparkMenuDisplaySettings menu_display;
public SyntheticManagementSettings()
: this(new List<SortingCriteria>(), null, null) { }
public SyntheticManagementSettings(
List<SortingCriteria> sorting_criteria,
SyntheticManagementFilterSettings filters,
GridSettings grid = default)
: this(sorting_criteria, filters, grid, SparkMenuDisplaySettings.Default) { }
public SyntheticManagementSettings(
List<SortingCriteria> sorting_criteria,
SyntheticManagementFilterSettings filters,
GridSettings grid,
SparkMenuDisplaySettings menu_display) {
this.sorting_criteria = sorting_criteria;
this.filters = filters;
this.grid = grid;
this.menu_display = menu_display;
}
public SyntheticManagementSettings with(
List<SortingCriteria> sorting_criteria = null,
SyntheticManagementFilterSettings filters = null,
GridSettings grid = null,
SparkMenuDisplaySettings? menu_display = null) =>
new(
sorting_criteria ?? this.sorting_criteria,
filters ?? this.filters,
grid ?? this.grid,
menu_display ?? this.menu_display);
public static GridSettings default_grid_settings =>
GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria);
public static GridSettings dark_theme_grid_settings =>
default_grid_settings.with(
selection_highlight: BTSDarkColors.selection_highlight.argb_color(),
background: BTSDarkColors.background.argb_color(),
font_color: BTSDarkColors.foreground.argb_color());
public static string col_id(Columns col) =>
col.ToString();
static class DefaultColumns {
public static GridColumnSettings name =>
new(col_id(Columns.Name), ColHeaders.Name, width: ColWidths.Security);
public static GridColumnSettings description =>
new(col_id(Columns.Description), ColHeaders.Description, width: ColWidths.Description);
public static GridColumnSettings n_legs =>
new(col_id(Columns.n_legs), ColHeaders.N_Legs, width: ColWidths.N_Legs);
public static GridColumnSettings n_working_orders => new(
col_id(Columns.n_working_orders),
ColHeaders.N_Working_Orders,
width: ColWidths.N_Working_Orders);
public static GridColumnSettings security_key => new(
col_id(Columns.SecurityKey),
ColHeaders.SecurityKey,
is_visible: false,
width: ColWidths.SecurityKey);
public static GridColumnSettings user =>
new(col_id(Columns.User), ColHeaders.User, is_visible: false, width: ColWidths.User);
public static IEnumerable<SortingCriteria> default_sorting_criteria {
get {
yield return new SortingCriteria(name.id, true);
}
}
public static IEnumerable<GridColumnSettings> all {
get {
yield return name;
yield return description;
yield return n_legs;
yield return n_working_orders;
yield return security_key;
yield return user;
}
}
}
}
}
@@ -22,13 +22,13 @@ using System.Windows;
using static bts.shell.SyntheticManagementWindowFactory;
namespace mbts.spark {
class SyntheticManagementWindow : SparkWindow<StartupData>, ISharedWindow {
class SyntheticManagementWindow : SparkWindow<SyntheticManagementSettings>, ISharedWindow {
const string
_window_type = "SyntheticManagement",
_import_title = "Import Synthetics";
static readonly TimeSpan _import_op_sec_map_timeout = TimeSpan.FromSeconds(30);
SingleValuePump<SyntheticManagementDialogVM> _vm = new SingleValuePump<SyntheticManagementDialogVM>();
StartupData _state;
SyntheticManagementSettings _state;
OrdersModel _orders_model;
SyntheticManagementView _view;
SparkMenuDisplayVM _menu_display_vm;
@@ -36,7 +36,7 @@ namespace mbts.spark {
List<SparkCommand> _commands;
readonly IWindowSettingsManager<GridSettings> _settings_manager;
public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, IWindowSettingsManager<GridSettings> settings_manager)
public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, SyntheticManagementSettings state, IWindowSettingsManager<GridSettings> settings_manager)
: base("Synthetic Management", bus, factory, SparkCommands.ShowSyntheticManagement.icon) {
_orders_model = orders_model;
_state = state;
@@ -56,9 +56,9 @@ namespace mbts.spark {
public override string window_type => _window_type;
public override UIElement Content => _view;
public override IEnumerable<SparkCommand> Commands => _commands;
public override StartupData SaveState => _state = _vm.value.create().with(menu_display: _menu_display_vm.safe_create());
public override SyntheticManagementSettings SaveState => _state = _vm.value.create().with(menu_display: _menu_display_vm.safe_create());
public override double MinWidth =>
StartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width)
SyntheticManagementSettings.default_grid_settings.columns.Sum(gcs => gcs.width)
+ SPARK_MENU_COLLAPSED_WIDTH
+ LAUNCHER_BUTTON_BORDER_WIDTH
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
@@ -133,7 +133,7 @@ namespace mbts.spark {
(SecurityImmutable, ExecutionStrategyImmutable) select_row_strategy_tuple(RowStrategy? rs) => rs.HasValue ? (rs.Value.security, rs.Value.strategy) : default;
bool can_execute(RowModificationParams? rmp) => rmp.HasValue && !rmp.Value.has_working_orders;
_vm.value = new SyntheticManagementDialogVM(_bus, _orders_model, _settings_manager, _state.sorting_criteria, _state.filters ?? new FilterStates());
_vm.value = new SyntheticManagementDialogVM(_bus, _orders_model, _settings_manager, _state.sorting_criteria, _state.filters ?? new SyntheticManagementFilterSettings());
if (_view == null) _view = new SyntheticManagementView { DataContext = _vm.value };
else _view.DataContext = _vm.value;
@@ -3,23 +3,18 @@ using bts.settings;
using mbts.persist;
using mbts.spark;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.settings;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Reactive.Linq;
using System.Threading.Tasks;
using static mbts.ui.controls.DIYGrid;
using static mbts.ui.spark.SyntheticManagementView;
namespace bts.shell {
class SyntheticManagementWindowFactory : ShellWindowFactory<SyntheticManagementWindowFactory.StartupData> {
class SyntheticManagementWindowFactory : ShellWindowFactory<SyntheticManagementSettings> {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly UserSettingsHub _settings_hub;
@@ -33,100 +28,20 @@ namespace bts.shell {
public static string col_id(Columns col) => col.ToString();
public override Task<IShellWindow> load(StartupData state) =>
public override Task<IShellWindow> load(SyntheticManagementSettings state) =>
Task.FromResult<IShellWindow>(_create(state));
public async void show(SparkTags.Nothing nothing) =>
_bus.post(SparkTags.ShowWindow, await load(new StartupData()));
_bus.post(SparkTags.ShowWindow, await load(new SyntheticManagementSettings()));
IShellWindow _create(StartupData state) =>
IShellWindow _create(SyntheticManagementSettings state) =>
new SyntheticManagementWindow(this, _bus, _orders_model, state, _settings_hub.create_synth_settings_manager(state.grid));
[ProtoContract]
public class StartupData {
public const int Version = 1;
[ProtoMember(1)]
public readonly List<SortingCriteria> sorting_criteria;
[ProtoMember(2)]
public readonly FilterStates filters;
[ProtoMember(3)]
public readonly GridSettings grid;
[ProtoMember(4)]
public readonly SparkMenuDisplaySettings menu_display;
public StartupData() : this(new List<SortingCriteria>(), null, null) { }
public StartupData(List<SortingCriteria> sorting_criteria, FilterStates filters, GridSettings grid = default)
: this(sorting_criteria, filters, grid, SparkMenuDisplaySettings.Default) { }
public StartupData(List<SortingCriteria> sorting_criteria, FilterStates filters, GridSettings grid, SparkMenuDisplaySettings menu_display) {
this.sorting_criteria = sorting_criteria;
this.filters = filters;
this.grid = grid;
this.menu_display = menu_display;
}
public StartupData with(List<SortingCriteria> sorting_criteria = null, FilterStates filters = null, GridSettings grid = null, SparkMenuDisplaySettings? menu_display = null) =>
new StartupData(
sorting_criteria ?? this.sorting_criteria,
filters ?? this.filters,
grid ?? this.grid,
menu_display ?? this.menu_display);
public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria);
static class DefaultColumns {
public static GridColumnSettings name => new GridColumnSettings(col_id(Columns.Name), DefaultColumnHeaders.Name, width: DefaultColumnWidths.Security);
public static GridColumnSettings description => new GridColumnSettings(col_id(Columns.Description), DefaultColumnHeaders.Description, width: DefaultColumnWidths.Description);
public static GridColumnSettings n_legs => new GridColumnSettings(col_id(Columns.n_legs), DefaultColumnHeaders.N_Legs, width: DefaultColumnWidths.N_Legs);
public static GridColumnSettings n_working_orders => new GridColumnSettings(col_id(Columns.n_working_orders), DefaultColumnHeaders.N_Working_Orders, width: DefaultColumnWidths.N_Working_Orders);
public static GridColumnSettings security_key => new GridColumnSettings(col_id(Columns.SecurityKey), DefaultColumnHeaders.SecurityKey, is_visible: false, width: DefaultColumnWidths.SecurityKey);
public static GridColumnSettings user => new GridColumnSettings(col_id(Columns.User), DefaultColumnHeaders.User, is_visible: false, width: DefaultColumnWidths.User);
public static IEnumerable<SortingCriteria> default_sorting_criteria {
get {
yield return new SortingCriteria(name.id, true);
}
}
public static IEnumerable<GridColumnSettings> all {
get {
yield return name;
yield return description;
yield return n_legs;
yield return n_working_orders;
yield return security_key;
yield return user;
}
}
}
}
[ProtoContract]
public class FilterStates {
[ProtoMember(1)]
public string description;
[ProtoMember(2)]
public TimeFilterTuple create_time;
[ProtoMember(3)]
public string name;
[ProtoMember(4)]
public IntMinMaxState n_legs;
[ProtoMember(5)]
public UIntMinMaxState n_working_orders;
[ProtoMember(6)]
public string security_key;
[ProtoMember(7)]
public uint[] user;
}
// migration rules
[Export(typeof(ISyntheticManagementMigrationRule))]
class AddMissingColumnsMigrationRule : ISyntheticManagementMigrationRule {
public bool apply(GridSettings settings, out GridSettings new_settings) =>
settings.add_missing_columns(StartupData.DefaultGridSettings.columns, out new_settings);
settings.add_missing_columns(SyntheticManagementSettings.default_grid_settings.columns, out new_settings);
}
}
}
@@ -1,6 +1,7 @@
using bts;
using bts.api;
using bts.collections;
using bts.shell;
using bts.spark;
using bts.utils;
@@ -18,7 +19,6 @@ using System.Reactive.Linq;
using System.Windows.Data;
using System.Windows.Input;
using static bts.shell.SyntheticManagementWindowFactory;
using static mbts.ui.controls.DIYGrid;
using static mbts.ui.spark.SyntheticManagementView;
@@ -29,7 +29,7 @@ namespace mbts.spark {
readonly IWindowSettingsManager<GridSettings> _settings_manager;
public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager<GridSettings> settings_manager) : this(bus, orders_model, settings_manager, null, null) { }
public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager<GridSettings> settings_manager, IReadOnlyCollection<SortingCriteria> sorting, FilterStates filters)
public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager<GridSettings> settings_manager, IReadOnlyCollection<SortingCriteria> sorting, SyntheticManagementFilterSettings filters)
: base(orders_model.spreader.synthetic_tuples.Select(t => t.state.Values), sorting) {
_bus = bus;
_orders_model = orders_model;
@@ -54,7 +54,7 @@ namespace mbts.spark {
Columns.n_working_orders,
n_working_orders_filter,
DataGridFilterKnownTemplates.UIntMinMax) {
id = col_id(Columns.n_working_orders),
id = SyntheticManagementSettings.col_id(Columns.n_working_orders),
CommandBinding = new Binding(nameof(Row.show_order_book)),
TextBinding = new Binding(nameof(Row.n_working_orders)),
Header = DefaultColumnHeaders.N_Working_Orders,
@@ -65,7 +65,7 @@ namespace mbts.spark {
//
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),
id = SyntheticManagementSettings.col_id(col_key),
Header = header,
sort_member_path = prop,
Width = width
@@ -96,8 +96,8 @@ namespace mbts.spark {
public GridSettings get_grid_save_state() =>
_settings_manager.instance_settings == null ? null : grid_settings_manager.create();
public StartupData create() =>
new StartupData(rows_view.get_sorting_criteria(columns), _get_filter_states(), get_grid_save_state());
public SyntheticManagementSettings create() =>
new SyntheticManagementSettings(rows_view.get_sorting_criteria(columns), _get_filter_states(), get_grid_save_state());
protected override Row row_factory(SyntheticTuple row_model) =>
new Row(_bus, row_model, _orders_model);
@@ -105,8 +105,8 @@ namespace mbts.spark {
protected override void on_row_removed(Row row) =>
row.Dispose();
FilterStates _get_filter_states() =>
new FilterStates {
SyntheticManagementFilterSettings _get_filter_states() =>
new SyntheticManagementFilterSettings {
description = description_filter.get_state(),
create_time = create_time_filter.get_state(),
name = name_filter.get_state(),
@@ -385,15 +385,21 @@
and only necessary for the size param as of 6/8/2020 (slightly more uniform code doesn't warrant rocking the boat).-->
<u:TemplateSelectorKeyValue Key="{x:Static usp:AlgoParamTemplateKeys.Size}">
<DataTemplate>
<c:TickUpDownNullableInt32 Focusable="False" HorizontalAlignment="Stretch" Value="{Binding param.display_value, UpdateSourceTrigger=PropertyChanged}" ArrowKeyTickModifiers="Ctrl">
<c:TickUpDownNullableInt32.CommandBindings>
<c:TickUpDownNullableDouble
Focusable="False"
HorizontalAlignment="Stretch"
Value="{Binding param.display_value, UpdateSourceTrigger=PropertyChanged}"
TickDownCommand="{Binding param.tick_down_cmd, Mode=OneWay}"
TickUpCommand="{Binding param.tick_up_cmd, Mode=OneWay}"
ArrowKeyTickModifiers="Ctrl">
<c:TickUpDownNullableDouble.CommandBindings>
<CommandBinding Command="{x:Static u:NavigationHelper.MoveFocusCommand}" Executed="{x:Static u:NavigationHelper.KeyboardMoveFocusExecuted}"/>
</c:TickUpDownNullableInt32.CommandBindings>
<c:TickUpDownNullableInt32.InputBindings>
</c:TickUpDownNullableDouble.CommandBindings>
<c:TickUpDownNullableDouble.InputBindings>
<KeyBinding Key="Up" Command="{x:Static u:NavigationHelper.MoveFocusCommand}" CommandParameter="{x:Static FocusNavigationDirection.Up}"/>
<KeyBinding Key="Down" Command="{x:Static u:NavigationHelper.MoveFocusCommand}" CommandParameter="{x:Static FocusNavigationDirection.Down}"/>
</c:TickUpDownNullableInt32.InputBindings>
</c:TickUpDownNullableInt32>
</c:TickUpDownNullableDouble.InputBindings>
</c:TickUpDownNullableDouble>
</DataTemplate>
</u:TemplateSelectorKeyValue>
</usp:AlgoParamTemplateSelector.KeyedTemplates>
@@ -65,7 +65,7 @@ namespace bts.shell {
var settings_manager = new WindowSettingsManager<GridSettings>(_settings_hub,
state.grid,
get: us => us.fills_grid,
set: (us, gs) => us.with(provided_fills_gridsettings: gs));
set: (us, gs) => us.with(fills: gs));
return new FillsWindow(this, _bus, _orders_model, state, settings_manager);
}
@@ -39,6 +39,13 @@ namespace bts.shell.fills {
}
public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria);
public static GridSettings dark_theme_grid_settings =>
DefaultGridSettings.with(
selection_highlight: BTSDarkColors.selection_highlight.argb_color(),
background: BTSDarkColors.background.argb_color(),
font_color: BTSDarkColors.foreground.argb_color());
public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criteria);
public IReadOnlyList<SortingCriteria> sorting_criteria => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criteria.ToList());
public static FillsSettings Default() =>
@@ -7,6 +7,8 @@ using bts.md;
using mbts.co2;
using Spark.Core.Data;
using System;
using System.Threading.Tasks;
@@ -18,11 +20,13 @@ namespace mbts.spark {
SecurityMD source,
OrdersModel ordergw,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
MBOService mbo,
Func<OrderSecurity, bool> order_filter = null) {
security_md = source;
_order_gateway = ordergw;
this.position_model = position_model;
this.sec_meta_store = sec_meta_store;
orders = ordergw.on_security_working_orders_with_piq(source.security.Id);
this.mbo_service = mbo;
if (order_filter != null) {
@@ -37,6 +41,7 @@ namespace mbts.spark {
public IMDConsumerHandle md => security_md.md;
public OrdersModel order_gateway => _order_gateway;
public IPositionModel position_model { get; }
public ISecurityMetadataStore sec_meta_store { get; }
public IObservable<TableUpdate<OrderSecurity, uint>> orders { get; }
public MBOService mbo_service { get; }
@@ -646,6 +646,24 @@ namespace mbts.spark {
public static LadderSettings Default => mimic_tt ?
tt_default : historic_default;
public static LadderSettings dark_theme {
get {
var rv = Default;
rv.orders_column.background = BTSDarkColors.background.argb_color();
rv.orders_column.foreground = BTSDarkColors.foreground.argb_color();
rv.bid_column.background = BTSDarkColors.dark_background.argb_color();
rv.bid_column.foreground = BTSDarkColors.bid_foreground.argb_color();
rv.price_column.background = BTSDarkColors.background.argb_color();
rv.price_column.foreground = BTSDarkColors.foreground.argb_color();
rv.ask_column.background = BTSDarkColors.dark_background.argb_color();
rv.ask_column.foreground = BTSDarkColors.ask_foreground.argb_color();
return rv;
}
}
public enum BadgeStyle { Normal, Alternate }
// TODO: rename to PriceDisplayFormat (today is merge monday, since this isn't a functional change, it is not worth the potential merge headaches right now)
@@ -0,0 +1,48 @@
#nullable enable
namespace mbts.spark {
using bts.utils;
using ProtoBuf;
using System;
[ProtoContract]
class LadderSettingsProfile : ISettingsProfile<LadderSettings>, IEquatable<LadderSettingsProfile> {
public LadderSettingsProfile() { }
public LadderSettingsProfile(
uint id, string? name, LadderSettings? value, SecurityCriteria? security_criteria = null) {
this.id = id;
this.name = name;
this.value = value;
this.security_criteria = security_criteria;
}
[ProtoMember(1)]
public uint id { get; }
[ProtoMember(2)]
public string? name { get; }
[ProtoMember(3)]
public LadderSettings? value { get; }
[ProtoMember(4)]
public SecurityCriteria? security_criteria { get; }
public LadderSettingsProfile with(uint? id = null, LadderSettings? value = null) =>
new(id ?? this.id, name, value ?? this.value, security_criteria);
public bool Equals(LadderSettingsProfile? other) =>
other != null &&
id == other.id &&
name == other.name &&
value.safe_equals(other.value) &&
security_criteria.safe_equals(other.security_criteria);
public override bool Equals(object? obj) =>
Equals(obj as LadderSettingsProfile);
public override int GetHashCode() => id.GetHashCode();
}
}
@@ -12,6 +12,8 @@ namespace mbts.spark {
using mbts.ui.spark;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -36,6 +38,8 @@ namespace mbts.spark {
[DisallowNull]
readonly IPositionModel _position_model;
[DisallowNull]
readonly ISecurityMetadataStore _sec_meta_store;
[DisallowNull]
readonly UserSettingsHub _settings_hub;
[DisallowNull]
readonly LadderWindowSettings _window_settings;
@@ -60,6 +64,7 @@ namespace mbts.spark {
[DisallowNull] IBus bus,
[DisallowNull] OrdersModel orders_model,
[DisallowNull] IPositionModel position_model,
[DisallowNull] ISecurityMetadataStore sec_meta_store,
SecurityMD security_md,
LadderWindowSettings window_settings,
[NotNull] UserSettingsHub settings_hub,
@@ -75,6 +80,7 @@ namespace mbts.spark {
_orders_model = orders_model ?? throw new ArgumentNullException(nameof(orders_model));
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_ladder_conf = ladder_conf;
_security_md = security_md;
_mbo = mbo ?? throw new ArgumentNullException(nameof(mbo));
@@ -108,7 +114,8 @@ namespace mbts.spark {
public void thread_init() {
// resources
var model = new LadderModel(_security_md, _orders_model, _position_model, _mbo);
var model = new LadderModel(
_security_md, _orders_model, _position_model, _sec_meta_store, _mbo);
_profile_service = new SettingsProfileService<LadderSettings>(_settings_hub,
us => ImmutableDictionary<uint, SettingsProfile<LadderSettings>>.Empty.AddRange(us.ladder_profiles.ToDictionary(
lp => lp.id,
@@ -14,6 +14,8 @@
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -33,6 +35,7 @@
readonly UserSettingsHub _settings_hub;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IShellWindowThreadIDProvider _thread_id_provider;
IReadOnlyDictionary<uint, SecurityMD> _securities = new Dictionary<uint, SecurityMD>();
@@ -44,6 +47,7 @@
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
MBOService mbo)
: base(owner, _window_type, 2) {
_bus = bus;
@@ -51,6 +55,7 @@
_settings_hub = settings_hub;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_ladder_conf = new LadderConfig(
Configuration.get<bts.config.LadderKnobs>(),
Configuration.get<bts.config.MultiThreadedWindows>().ladder);
@@ -77,7 +82,18 @@
IShellWindow _create_ladder_window(SecurityMD sec_md, LadderWindowSettings ws) {
var thread_id = _thread_id_provider.next_id();
return new LadderWindow(
module, _mbo, this, _bus, _orders_model, _position_model, sec_md, ws, _settings_hub, thread_id, _ladder_conf);
module,
_mbo,
this,
_bus,
_orders_model,
_position_model,
_sec_meta_store,
sec_md,
ws,
_settings_hub,
thread_id,
_ladder_conf);
}
void _show_windows(IEnumerable<SecurityMD> securities) {
@@ -49,7 +49,7 @@ namespace mbts.spark {
ImmutableDictionary<uint, OrderSecurity>.Empty;
LadderSettings.BadgeStyle _current_badge_style;
double _phantom_price = double.NaN;
uint _filled;
double _filled;
uint _num_root_orders;
double _quantity;
uint? _min_piq = uint.MaxValue;
@@ -64,7 +64,7 @@ namespace mbts.spark {
_orders = orders;
_real_price = real_price;
_text_lines = backing(nameof(text_lines), () => {
var fmt = MDDisplayHelper.get_value_formatter(_owner.display_quantity_divisor);
var fmt = MDDisplayHelper.get_value_formatter(_owner.model.security_md.quantity_display);
return BadgeRender.format(side, _quantity, _filled, _current_badge_style, fmt);
});
_clear_phantom_price = new(() => {
@@ -199,7 +199,7 @@ namespace mbts.spark {
using var _ = _clear_phantom_price.defer_execution(true);
if (await _owner.model.order_gateway.update_order(
order, new_price, order.State.Quantity, null)) {
order, new_price, order.State.quantity(), null)) {
// wait 3 secs before clearing the phantom price
await Task.Delay(3000);
}
@@ -218,7 +218,7 @@ namespace mbts.spark {
hoverbackground = _mk_hover_bg_brush(dark, _darkbg, 0);
(_num_root_orders, _filled, _quantity) = _root_nodes
.Select(n => (1u, n.filled(), n.quantity()))
.Select(n => (1u, n.filled_quantity(), n.quantity()))
.Sum();
if (_num_root_orders == 1) {
@@ -262,6 +262,7 @@ namespace mbts.spark {
null,
_owner.model.order_gateway,
_owner.model.position_model,
_owner.model.sec_meta_store,
settings_man,
true,
global_filter: order_price_filter);
@@ -19,6 +19,7 @@ namespace mbts.spark {
using Spark.Api.Position;
using Spark.Core;
using Spark.Core.Data;
using Spark.ViewModel.Commands;
using System;
@@ -8,6 +8,7 @@ namespace mbts.spark {
using mbts.ui.shell;
using Spark.Core.Collections;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
@@ -18,15 +19,21 @@ namespace mbts.spark {
readonly IBus _bus;
readonly OrdersModel _model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
LadderVM? _value;
SecurityMD? _security_md;
HashSet<uint> _selected_order_tree = new();
public LadderVMContainer(IBus bus, OrdersModel model, IPositionModel position_model) {
public LadderVMContainer(
IBus bus,
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) {
_bus = bus;
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
}
public SecurityMD? security_md {
@@ -69,7 +76,12 @@ namespace mbts.spark {
}
var model = new LadderModel(
_security_md.Value, _model, _position_model, _model.mbo_service, order_filter);
_security_md.Value,
_model,
_position_model,
_sec_meta_store,
_model.mbo_service,
order_filter);
var settings_src = Observable.Return(LadderSettings.sanitize(LadderSettings.Default));
_value = LadderVM.create_readonly(_bus, model, settings_src);
@@ -88,7 +88,8 @@ namespace mbts.spark {
double _last_origin_price;
readonly MarketBreakLines _mkt_break_lines;
NativePriceSize _last_trade;
Func<NativePriceSize, string> _fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default());
Func<NativePriceSize, string> _fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
MarketSizeDisplay.get_default(), SecurityDataHelper.Defaults.quantity_display_settingsi);
Func<double, string> _fmt_mkt_quantity_impl = v => v.ToString();
int _old_tooltip_row = int.MaxValue;
NativePriceSize? _old_last_trade;
@@ -395,6 +396,11 @@ namespace mbts.spark {
int _row_count => _price_list?.Count ?? 0;
bts.api.domain.TickDisplaySettingsImmutable _qty_display =>
_vm is null ?
SecurityDataHelper.Defaults.quantity_display_settingsi :
_vm.model.security_md.quantity_display;
public void drag_out_of_bounds() =>
_tactile_adorner?.drag_out_of_bounds();
@@ -1428,9 +1434,9 @@ namespace mbts.spark {
static GlyphContext glyph_context(LadderColumnSettings cs) =>
GlyphContext.create(cs.font_family, cs.font_weight);
var mkt_qty_display_divisor = _vm?.display_quantity_divisor ?? 1;
_fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(_settings.size_display, mkt_qty_display_divisor);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(mkt_qty_display_divisor);
_fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
_settings.size_display, _qty_display);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(_qty_display);
_set_columns();
_apply_column_visual_offset();
if (prev_row_height != _settings.row_height)
@@ -1508,7 +1514,8 @@ namespace mbts.spark {
// Assign the impl delegate to a local variable, just in case it is reassigned on another thread.
// This shouldn't happen, but better to avoid the potential null ref just in case it does. Expect the unexpected.
var impl = _fmt_mkt_depth_item_impl;
return impl is null ? MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default())?.ToString() ?? "Error" : impl(value);
impl ??= MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default(), _qty_display);
return impl(value);
}
// This is designed to be a redundant null check for _fmt_mkt_quantity_impl.
@@ -24,7 +24,7 @@ namespace mbts.spark {
public static IReadOnlyList<string> format(
Side side,
double quantity,
uint filled,
double filled,
LadderSettings.BadgeStyle style,
Func<double, string> fmt_value = null
) {
@@ -1,166 +1,184 @@
using bts.api;
using bts.api.position;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.shell;
using Spark.Core.Reflection;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace bts.shell.manual_fills {
class ManualFillRow : DisposableViewModelBase, IEquatable<ManualFillRow> {
public const int _uncommitted_record_id = -1;
static readonly PropertyInfo[] _snapshot_props =
Array.ConvertAll(new[] {
nameof(security),
nameof(account),
nameof(user),
nameof(side),
nameof(size),
nameof(price)
}, typeof(ManualFillRow).GetProperty);
readonly Property<bool> _is_dirty;
readonly Property<EditableItemState> _editable_item_state;
readonly DelegateProperty<bool> _is_valid;
readonly DisplayQuantityMultiplier<double> _size = DisplayQuantityMultiplier.create_double();
readonly Func<SecurityImmutable?, double> _get_display_qty_divisor;
SecurityImmutable? _security;
AccountTuple? _account;
UserTuple? _user;
Side _side;
double _price;
bool _is_selected;
ManualFillData? _data;
IDisposable _committed_snapshot;
public ManualFillRow(ManualFillData data, Func<SecurityImmutable?, double> get_display_qty_divisor) {
_data = data;
_get_display_qty_divisor = get_display_qty_divisor ?? new Func<SecurityImmutable?, double>(sec => 1);
key = data.key;
_security = data.value.security;
_account = data.value.account;
_user = data.value.user;
_side = data.value.manual_fill.Side;
_size.actual_value = data.value.manual_fill.Quantity;
_size.conversion_data = new(
_get_display_qty_divisor(data.value.security), QuantityConversionOpType.DivideActual);
_price = data.value.manual_fill.Price;
if (placeholder_key.HasValue) {
_is_dirty = backing(nameof(is_dirty), false);
_editable_item_state = backing(nameof(editable_item_state), EditableItemState.Uncommitted);
_committed_snapshot = ReflectionHelper.create(this, _snapshot_props);
} else {
_is_dirty = backing(
nameof(is_dirty),
ReflectionHelper.dirty_monitor(this, out _committed_snapshot, _snapshot_props));
_editable_item_state = backing(nameof(editable_item_state), _is_dirty, ch => ch.newval ? EditableItemState.Modified : EditableItemState.None);
}
_is_valid = backing(nameof(is_valid), () => _validate(this));
_dispose = _size.connect_owner(this, nameof(size), nameof(display_size));
}
public event Action<bool> is_selected_changed;
// key/id
public ManualFillKey key { get; }
public long? placeholder_key => key.unpersisted;
public int record_id => key.persisted ?? _uncommitted_record_id;
public string record_id_display_text => key.persisted?.ToString();
// security/spec
public SecurityImmutable? security {
get => _security;
set {
if (_set(ref _security, value)) {
_size.conversion_data = new(
_get_display_qty_divisor(value), QuantityConversionOpType.DivideActual);
RaisePropertyChanged(nameof(spec));
}
}
}
public ContractSpecificationImmutable? spec => security.spec_or_default();
// account/user
public AccountTuple? account { get => _account; set => _set(ref _account, value); }
public UserTuple? user { get => _user; set => _set(ref _user, value); }
// side/size/price
public Side side { get => _side; set => _set(ref _side, value); }
public double size { get => _size.actual_value; set => _size.actual_value = value; }
public double display_size { get => _size.display_value; set => _size.display_value = value; }
public double price { get => _price; set => _set(ref _price, value); }
// is selected
public bool is_selected {
get => _is_selected;
set {
if (_set(ref _is_selected, value))
is_selected_changed?.Invoke(value);
}
}
// dirty/valid/editable-state
public bool is_dirty => _is_dirty.Value;
public bool is_valid => _is_valid.Value;
public EditableItemState editable_item_state => _editable_item_state.Value;
public ManualFillData data => _data ??
(_data = new ManualFillData(key, new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user))).Value;
public void revert() =>
_committed_snapshot.Dispose();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
public IObservable<bool> subscribe_is_selected() =>
Observable.Create<bool>(o => {
o.OnNext(is_selected);
is_selected_changed += o.OnNext;
return Disposable.Create(() => is_selected_changed -= o.OnNext);
});
public ManualFill to_man_fill() =>
new ManualFill {
RecordId = record_id,
AccountId = account?.id ?? 0,
AccountName = account?.name ?? string.Empty,
FillType = ManualFill.Types.FillType.AdminDay,
UserId = user?.id ?? 0,
Price = price,
Side = side,
Quantity = (uint)size,
SecurityKey = security?.Id ?? 0
};
public ManualFillTuple to_tuple() =>
new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user);
public bool Equals(ManualFillRow other) =>
data == other?.data;
public override bool Equals(object obj) => Equals(obj as ManualFillRow);
public override int GetHashCode() => record_id;
static bool _validate(ManualFillRow row) =>
row.security.HasValue &&
row.account.HasValue &&
row.user.HasValue &&
row.side != Side.Undefined &&
!double.IsNaN(row._price);
bool _set<T>(ref T backing, T value, [CallerMemberName] string prop_name = "") =>
_set(ref backing, value, EqualityComparer<T>.Default, prop_name);
bool _set<T>(ref T backing, T value, IEqualityComparer<T> comparer, [CallerMemberName] string prop_name = "") {
if (Set(ref backing, value, comparer, prop_name)) {
_is_valid.refresh();
_data = null;
return true;
}
return false;
}
}
}
using bts.api;
using bts.api.position;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.shell;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
namespace bts.shell.manual_fills {
class ManualFillRow : DisposableViewModelBase, IEquatable<ManualFillRow> {
public const int _uncommitted_record_id = -1;
static readonly PropertyInfo[] _snapshot_props =
Array.ConvertAll(new[] {
nameof(security),
nameof(account),
nameof(user),
nameof(side),
nameof(quantity),
nameof(price)
}, typeof(ManualFillRow).GetProperty);
readonly ISecurityMetadataStore _sec_meta_store;
readonly Property<bool> _is_dirty;
readonly Property<EditableItemState> _editable_item_state;
readonly DelegateProperty<bool> _is_valid;
readonly DisplayQuantityMultiplier<double> _quantity = DisplayQuantityMultiplier.create_double();
readonly DelegateProperty<TickDisplaySettingsImmutable> _quantity_display;
SecurityImmutable? _security;
AccountTuple? _account;
UserTuple? _user;
Side _side;
double _price;
bool _is_selected;
ManualFillData? _data;
IDisposable _committed_snapshot;
public ManualFillRow(ManualFillData data, ISecurityMetadataStore sec_meta_store) {
_data = data;
_sec_meta_store = sec_meta_store;
key = data.key;
_security = data.value.security;
_account = data.value.account;
_user = data.value.user;
_side = data.value.manual_fill.Side;
_quantity.actual_value = data.value.manual_fill.Quantity;
_quantity_display = backing(
nameof(quantity_display),
() => {
var sec_meta = security.HasValue ? _sec_meta_store.get(security.Value) : null;
return sec_meta?.QuantityDisplay ??
SecurityDataHelper.Defaults.quantity_display_settingsi;
});
// TODO (prob): remove conversion_data. Replace get_qty_display_divisor delegates w/
// TickDisplaySettingsImmutable for qty, obtained via ISecurityMetadataStore.
_quantity.conversion_data = new(1, QuantityConversionOpType.DivideActual);
_price = data.value.manual_fill.Price;
if (placeholder_key.HasValue) {
_is_dirty = backing(nameof(is_dirty), false);
_editable_item_state = backing(nameof(editable_item_state), EditableItemState.Uncommitted);
_committed_snapshot = ReflectionHelper.create(this, _snapshot_props);
} else {
_is_dirty = backing(
nameof(is_dirty),
ReflectionHelper.dirty_monitor(this, out _committed_snapshot, _snapshot_props));
_editable_item_state = backing(nameof(editable_item_state), _is_dirty, ch => ch.newval ? EditableItemState.Modified : EditableItemState.None);
}
_is_valid = backing(nameof(is_valid), () => _validate(this));
_dispose = _quantity.connect_owner(this, nameof(quantity), nameof(display_quantity));
}
public event Action<bool> is_selected_changed;
// key/id
public ManualFillKey key { get; }
public long? placeholder_key => key.unpersisted;
public int record_id => key.persisted ?? _uncommitted_record_id;
public string record_id_display_text => key.persisted?.ToString();
// security/spec
public SecurityImmutable? security {
get => _security;
set {
if (_set(ref _security, value)) {
_quantity.conversion_data = new(1, QuantityConversionOpType.DivideActual);
_quantity_display.refresh();
RaisePropertyChanged(nameof(spec));
}
}
}
public ContractSpecificationImmutable? spec => security.spec_or_default();
// account/user
public AccountTuple? account { get => _account; set => _set(ref _account, value); }
public UserTuple? user { get => _user; set => _set(ref _user, value); }
// side/quantity/price
public Side side { get => _side; set => _set(ref _side, value); }
public double quantity { get => _quantity.actual_value; set => _quantity.actual_value = value; }
public double? display_quantity {
get => _quantity.display_value;
set => _quantity.display_value = value ?? double.NaN;
}
public TickDisplaySettingsImmutable quantity_display => _quantity_display.Value;
public double price { get => _price; set => _set(ref _price, value); }
// is selected
public bool is_selected {
get => _is_selected;
set {
if (_set(ref _is_selected, value))
is_selected_changed?.Invoke(value);
}
}
// dirty/valid/editable-state
public bool is_dirty => _is_dirty.Value;
public bool is_valid => _is_valid.Value;
public EditableItemState editable_item_state => _editable_item_state.Value;
public ManualFillData data => _data ??
(_data = new ManualFillData(key, new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user))).Value;
public void revert() =>
_committed_snapshot.Dispose();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
public IObservable<bool> subscribe_is_selected() =>
Observable.Create<bool>(o => {
o.OnNext(is_selected);
is_selected_changed += o.OnNext;
return Disposable.Create(() => is_selected_changed -= o.OnNext);
});
public ManualFill to_man_fill() =>
new ManualFill {
RecordId = record_id,
AccountId = account?.id ?? 0,
AccountName = account?.name ?? string.Empty,
FillType = ManualFill.Types.FillType.AdminDay,
UserId = user?.id ?? 0,
Price = price,
Side = side,
Quantity = quantity,
SecurityKey = security?.Id ?? 0
};
public ManualFillTuple to_tuple() =>
new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user);
public bool Equals(ManualFillRow other) =>
data == other?.data;
public override bool Equals(object obj) => Equals(obj as ManualFillRow);
public override int GetHashCode() => record_id;
static bool _validate(ManualFillRow row) =>
row.security.HasValue &&
row.account.HasValue &&
row.user.HasValue &&
row.side != Side.Undefined &&
!double.IsNaN(row._price);
bool _set<T>(ref T backing, T value, [CallerMemberName] string prop_name = "") =>
_set(ref backing, value, EqualityComparer<T>.Default, prop_name);
bool _set<T>(ref T backing, T value, IEqualityComparer<T> comparer, [CallerMemberName] string prop_name = "") {
if (Set(ref backing, value, comparer, prop_name)) {
_is_valid.refresh();
_data = null;
return true;
}
return false;
}
}
}
@@ -71,7 +71,12 @@
<ComboBox Grid.Row="2" Grid.Column="2" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Accounts}}" SelectedItem="{Binding account}"/>
<ComboBox Grid.Row="2" Grid.Column="4" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Users}}" SelectedItem="{Binding user}"/>
<ComboBox Grid.Row="2" Grid.Column="6" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Sides}}" SelectedItem="{Binding side}" Width="48"/>
<c:TickUpDownUInt Grid.Row="2" Grid.Column="8" MinWidth="40" Value="{Binding display_size}"/>
<c:TickUpDownNullableDouble
Grid.Row="2"
Grid.Column="8"
MinWidth="40"
TickDisplaySettings="{Binding quantity_display}"
Value="{Binding display_quantity}" />
<usp:PriceEntryControl Grid.Row="2" Grid.Column="10" MinWidth="55" Value="{Binding price}" ContractSpec="{Binding spec}"/>
</Grid>
<c:DialogSkirt Grid.Row="1" Margin="0,6,0,0">
@@ -59,7 +59,7 @@
<ComboBox ItemsSource="{Binding DataContext.sides, RelativeSource={RelativeSource AncestorType=DataGrid}}" SelectedItem="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static Size, MemberType={u:Nested usp:ManualFillsImportConflictsView.ManualFillComponentNames}}">
<u:TemplateSelectorKeyValue Key="{x:Static Quantity, MemberType={u:Nested usp:ManualFillsImportConflictsView.ManualFillComponentNames}}">
<DataTemplate>
<c:TickUpDownUInt Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
@@ -13,7 +13,7 @@ namespace mbts.ui.spark {
Account,
User,
Side,
Size,
Quantity,
Price
}
@@ -23,7 +23,7 @@ namespace mbts.ui.spark {
Account = ManualFillComponent.Account.ToString(),
User = ManualFillComponent.User.ToString(),
Side = ManualFillComponent.Side.ToString(),
Size = ManualFillComponent.Size.ToString(),
Quantity = ManualFillComponent.Quantity.ToString(),
Price = ManualFillComponent.Price.ToString();
}
}
@@ -5,6 +5,8 @@ using bts.collections;
using mbts.spark;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -80,13 +82,22 @@ namespace bts.shell.manual_fills {
class ManualFillsModel {
readonly OrdersModel _model;
public ManualFillsModel(OrdersModel model)
: this(model, model.on_manual_fill_tuples,
model.factory.subscribe_accounts().Select(d => MappedDictionary.create(d, (k, v) => new AccountTuple(k, v))).Table(u => u.id),
model.factory.subscribe_users().Select(d => MappedDictionary.create(d, (k, v) => new UserTuple(k, v))).Table(a => a.id)) { }
public ManualFillsModel(OrdersModel model, ISecurityMetadataStore sec_meta_store)
: this(
model,
sec_meta_store,
model.on_manual_fill_tuples,
model.factory.subscribe_accounts().Select(d => MappedDictionary.create(d, (k, v) => new AccountTuple(k, v))).Table(u => u.id),
model.factory.subscribe_users().Select(d => MappedDictionary.create(d, (k, v) => new UserTuple(k, v))).Table(a => a.id)) { }
public ManualFillsModel(OrdersModel model, IObservable<TableUpdate<ManualFillTuple, int>> manual_fills, IObservable<TableUpdate<AccountTuple, uint>> accounts, IObservable<TableUpdate<UserTuple, uint>> users) {
public ManualFillsModel(
OrdersModel model,
ISecurityMetadataStore sec_meta_store,
IObservable<TableUpdate<ManualFillTuple, int>> manual_fills,
IObservable<TableUpdate<AccountTuple, uint>> accounts,
IObservable<TableUpdate<UserTuple, uint>> users) {
_model = model;
this.sec_meta_store = sec_meta_store;
this.manual_fills = manual_fills.SelectKeyValue(
mft => new ManualFillData(new ManualFillKey(mft.manual_fill.RecordId), mft),
ManualFillData.key_fn);
@@ -94,6 +105,7 @@ namespace bts.shell.manual_fills {
this.users = users;
}
public ISecurityMetadataStore sec_meta_store { get; }
public IObservable<TableUpdate<ManualFillData, ManualFillKey>> manual_fills { get; }
public IObservable<TableUpdate<AccountTuple, uint>> accounts { get; }
public IObservable<TableUpdate<UserTuple, uint>> users { get; }
@@ -39,7 +39,7 @@ namespace bts.shell.manual_fills {
case ManualFillComponent.Account: return (mf, val) => mf.AccountId = ConvertUtils.try_convert<AccountTuple?>(val)?.id ?? 0;
case ManualFillComponent.User: return (mf, val) => mf.UserId = ConvertUtils.try_convert<UserTuple?>(val)?.id ?? 0;
case ManualFillComponent.Side: return (mf, val) => mf.Side = ConvertUtils.try_convert<Side>(val, Side.Undefined);
case ManualFillComponent.Size: return (mf, val) => mf.Quantity = ConvertUtils.try_convert<uint>(val);
case ManualFillComponent.Quantity: return (mf, val) => mf.Quantity = ConvertUtils.try_convert<uint>(val);
case ManualFillComponent.Price: return (mf, val) => mf.Price = ConvertUtils.try_convert(val, double.NaN);
default: throw new NotImplementedException();
}
@@ -60,7 +60,7 @@ namespace bts.shell.manual_fills {
add_missing(ManualFillComponent.User, pmf.user.text, pmf);
}
if (!pmf.quantity.success) {
add_missing(ManualFillComponent.Size, pmf.quantity.text, pmf);
add_missing(ManualFillComponent.Quantity, pmf.quantity.text, pmf);
}
if (!pmf.side.success) {
add_missing(ManualFillComponent.Side, pmf.side.text, pmf);
@@ -12,6 +12,7 @@ using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.ViewModel.Commands;
using System;
@@ -47,8 +48,9 @@ namespace bts.shell.manual_fills {
long _placeholder_id_counter = long.MinValue;
IDisposable _import_fills_hooks;
public static ManualFillsVM create(IBus bus, OrdersModel model) =>
new ManualFillsVM(bus, new ManualFillsModel(model));
public static ManualFillsVM create(
IBus bus, OrdersModel model, ISecurityMetadataStore sec_meta_store) =>
new(bus, new ManualFillsModel(model, sec_meta_store));
public ManualFillsVM(IBus bus, ManualFillsModel model) {
_bus = bus;
@@ -73,7 +75,7 @@ namespace bts.shell.manual_fills {
RXCollection.connect(_persisted_rows,
_model.manual_fills.OnDispatcher(),
Observable.Return(Comparer<ManualFillData>.Create((a, b) => a.key.CompareTo(b.key))),
mfd => new ManualFillRow(mfd, model.get_display_qty_divisor),
mfd => new ManualFillRow(mfd, model.sec_meta_store),
mfr => mfr.data),
_bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m => {
security_map = new FilteredDictionary<uint, SecurityMD>(
@@ -137,7 +139,7 @@ namespace bts.shell.manual_fills {
new ManualFillTuple(new ManualFillImmutable(new ManualFill {
Side = Side.Buy
}), null, accounts.FirstOrDefault(), users.FirstOrDefault())),
_model.get_display_qty_divisor);
_model.sec_meta_store);
void _add_fill(ManualFillRow new_row) =>
_placeholder_rows.InsertSorted((new_row ?? (new_row = row_factory())).placeholder_key.HasValue ?
@@ -214,7 +216,7 @@ namespace bts.shell.manual_fills {
object get_error_value(ManualFillComponent component) {
switch (component) {
case ManualFillComponent.Price: return double.NaN;
case ManualFillComponent.Size: return 0;
case ManualFillComponent.Quantity: return 0;
default: return null;
}
}
@@ -232,7 +234,7 @@ namespace bts.shell.manual_fills {
pmf.result.SecurityKey != 0 && security_map.TryGetValue(pmf.result.SecurityKey, out var smd) ? smd.security : (SecurityImmutable?)null,
accounts.FirstOrDefault(a => a?.id == pmf.result.AccountId),
users.FirstOrDefault(a => a?.id == pmf.result.UserId)));
return new ManualFillRow(data, _model.get_display_qty_divisor);
return new(data, _model.sec_meta_store);
}
}
} catch (Exception ex) {
@@ -208,16 +208,26 @@
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--Size-->
<DataGridTemplateColumn c:DataGridEx.CellKey="{x:Static Size, MemberType={u:Nested usp:ManualFillsView.Columns}}" Header="Qty" SortMemberPath="side">
<!--Quantity-->
<DataGridTemplateColumn c:DataGridEx.CellKey="{x:Static Quantity, MemberType={u:Nested usp:ManualFillsView.Columns}}" Header="Qty" SortMemberPath="side">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding display_size}" VerticalAlignment="Center"/>
<TextBlock VerticalAlignment="Center">
<TextBlock.Text>
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="display_quantity" />
<Binding Path="quantity_display" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<c:TickUpDownUInt MinWidth="40" Value="{Binding display_size, UpdateSourceTrigger=PropertyChanged}"/>
<c:TickUpDownNullableDouble
MinWidth="40"
TickDisplaySettings="{Binding quantity_display}"
Value="{Binding display_quantity, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
@@ -28,7 +28,7 @@ namespace mbts.ui.spark {
Account,
User,
Side,
Size,
Quantity,
Price
}
@@ -9,6 +9,8 @@ using mbts.ui;
using mbts.ui.controls;
using mbts.ui.spark;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -27,11 +29,18 @@ namespace bts.shell {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly ManualFillsConfig _manual_fills_conf = ManualFillsConfig.read();
public ManualFillsWindowFactory(IShellModule owner, IBus bus, OrdersModel orders_model) : base(owner, window_name) {
public ManualFillsWindowFactory(
IShellModule owner,
IBus bus,
OrdersModel orders_model,
ISecurityMetadataStore sec_meta_store)
: base(owner, window_name) {
_bus = bus;
_orders_model = orders_model;
_sec_meta_store = sec_meta_store;
_dispose = bus.subscribe(SparkTags.ShowManualFillsTag).Subscribe(open_window);
//
async void open_window(ManualFillsSettings state) =>
@@ -43,7 +52,7 @@ namespace bts.shell {
window_type, window_name, _bus, this, Icons.DataEdit, _manual_fills_conf.thread_id, thread_init, _window_min_width));
//
(UIElement, IEnumerable<SparkCommand>, Func<ManualFillsSettings>, IDisposable) thread_init() {
var vm = ManualFillsVM.create(_bus, _orders_model);
var vm = ManualFillsVM.create(_bus, _orders_model, _sec_meta_store);
var view = new ManualFillsView { DataContext = vm };
view.data_grid.Sorting += on_sorting;
IReadOnlyList<SortingCriteria> last_sorting_criteria = Array.Empty<SortingCriteria>();
File diff suppressed because it is too large. Load diff
@@ -30,7 +30,7 @@ namespace mbts.spark {
readonly OrderBookVM _owner;
Color? _root_algo_badge_color_backing;
Brush _badge_fill, _root_algo_badge_fill;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _detach_command, _attach_command, _update_command, _modify_order_quantity_andor_price, _revert_prospective_order_quantity_andor_price;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _detach_command, _attach_command, _update_command, _modify_order_cmd, _revert_order_cmd;
bool _is_parent, _is_expanded, _is_selected, _is_attachable, _is_detachable;
int _depth_level;
TickDisplaySettingsImmutable _quantity_display_settings =
@@ -115,9 +115,13 @@ namespace mbts.spark {
});
}
}
public uint filled_quantity => order.filled();
public double filled_quantity => order.filled_quantity();
public string filled_quantity_text =>
quantity_display_settings.to_tick_display_settings().format(filled_quantity);
// TODO: get rid of 'display_filled_quantity/_text' (it was added before we had a proper
// SecurityMetadata config structure, with entries keyed by SecurityCriteria)
public double display_filled_quantity =>
((double)filled_quantity).safe_divide(_display_qty_divisor);
filled_quantity.safe_divide(_display_qty_divisor);
public string display_filled_quantity_text =>
quantity_display_settings.to_tick_display_settings().format(display_filled_quantity);
public string last_msg => order.last_msg();
@@ -128,7 +132,8 @@ namespace mbts.spark {
public bool is_non_terminal => order.is_non_terminal();
public bool is_attachable { get => _is_attachable; set => SetVisual(ref _is_attachable, value); }
public bool is_detachable { get => _is_detachable; set => SetVisual(ref _is_detachable, value); }
public string filled_status_desc => order.filled_status_description(security.spec_or_default(), _display_qty_divisor);
public string filled_status_desc =>
order.filled_status_description(security.spec_or_default(), _quantity_display_settings);
// Root Algo
public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo.value.CustomCase;
@@ -168,6 +173,7 @@ namespace mbts.spark {
set {
if (Set(ref _prospective_price, value)) {
RaisePropertyChanged(nameof(is_price_dirty));
_revert_order_cmd?.RaiseCanExecuteChanged();
}
}
}
@@ -184,37 +190,35 @@ namespace mbts.spark {
public ICommand cancel_command => _cancel_cmd ??
(_cancel_cmd = new DelegateCommand(() => _owner.cancel_order(this), () => status == OrderStatus.Working || status == OrderStatus.Disconnected));
public ICommand modify_order_quantity_andor_price {
public ICommand modify_order_cmd {
get {
if (_modify_order_quantity_andor_price == null) {
_modify_order_quantity_andor_price = new DelegateCommand(execute, can_execute);
invalidated += _modify_order_quantity_andor_price.RaiseCanExecuteChanged;
// impl
void execute() {
if (is_qty_dirty && is_price_dirty) {
_owner.modify_order_price_and_quantity(this, prospective_price, prospective_quantity);
} else if (is_qty_dirty) {
_owner.modify_order_quantity(this, prospective_quantity);
} else if (is_price_dirty) {
_owner.modify_order_price(this, this.prospective_price);
}
_unselect_me();
}
bool can_execute() => status == OrderStatus.Working && (is_price_dirty || is_qty_dirty);
if (_modify_order_cmd is not null) {
return _modify_order_cmd;
}
return _modify_order_quantity_andor_price;
_modify_order_cmd = new Command(execute, can_execute);
invalidated += _modify_order_cmd.RaiseCanExecuteChanged;
return _modify_order_cmd;
void execute() {
double? new_price = is_price_dirty ? prospective_price : null;
double? new_qty = is_qty_dirty ? prospective_quantity : null;
_owner.modify_order(this, new_price, new_qty);
_unselect_me();
}
bool can_execute() =>
status == OrderStatus.Working && (is_price_dirty || is_qty_dirty);
}
}
public ICommand revert_prospective_order_quantity_andor_price => _revert_prospective_order_quantity_andor_price ??
(_revert_prospective_order_quantity_andor_price = new DelegateCommand(
public ICommand revert_order_cmd =>
_revert_order_cmd ??= new Command(
() => {
prospective_price = price;
prospective_quantity = quantity;
},
() => this.status == OrderStatus.Working && (is_price_dirty || is_qty_dirty)
)
);
() => status == OrderStatus.Working && (is_price_dirty || is_qty_dirty));
public ICommand detach_command => _detach_command ??
(_detach_command = new DelegateCommand(() => {
@@ -265,8 +269,11 @@ namespace mbts.spark {
_prospective_qty_translator_backing.conversion_data = new(
_display_qty_divisor, QuantityConversionOpType.DivideActual);
_prospective_qty_translator_backing.actual_value = quantity;
_prospective_qty_translator.value_changed += () =>
_prospective_qty_translator.value_changed += () => {
RaisePropertyChanged(nameof(is_qty_dirty));
_modify_order_cmd?.RaiseCanExecuteChanged();
_revert_order_cmd?.RaiseCanExecuteChanged();
};
} else {
_sync_display_qty_if_dirty();
}
@@ -488,7 +495,7 @@ namespace mbts.spark {
dirty |= Columns.Security;
if (oldval.order.order.last_change() != newval.order.order.last_change())
dirty |= Columns.LastChange;
if (oldval.order.order.filled() != newval.order.order.filled())
if (oldval.order.order.filled_quantity() != newval.order.order.filled_quantity())
dirty |= Columns.Filled;
if (oldval.order.order.last_price() != newval.order.order.last_price())
dirty |= Columns.LastPrice;
File diff suppressed because it is too large. Load diff
@@ -17,6 +17,8 @@ using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -38,6 +40,7 @@ namespace mbts.spark {
List<IDisposable> _thread_init_resources;
OrderBookStartupData _state;
OrdersModel _model;
ISecurityMetadataStore _sec_meta_store;
OrderBookVM _vm;
OrderBookView _view;
OrderBookWindowFactory _factory;
@@ -47,6 +50,7 @@ namespace mbts.spark {
public OrderBookWindow(
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
OrderBookWindowFactory factory,
IBus bus,
INotificationService notification_service,
@@ -57,6 +61,7 @@ namespace mbts.spark {
: base(_default_title, bus, factory, SparkCommands.ShowOrders.icon) {
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_factory = factory;
_notification_service = notification_service;
_state = state;
@@ -95,7 +100,7 @@ namespace mbts.spark {
_menu_display_vm = new SparkMenuDisplayVM();
if (_state != null)
_menu_display_vm.load_from(_state.menu_display);
_vm = new(_bus, _notification_service, _model, _position_model, _settings_manager);
_vm = new(_bus, _notification_service, _model, _position_model, _sec_meta_store, _settings_manager);
_vm.load_from(_state);
_view = new OrderBookView(_vm);
_vm.SubscribeDisposed(
@@ -8,6 +8,8 @@ using mbts.persist;
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
@@ -19,6 +21,7 @@ namespace bts.shell {
readonly INotificationServiceDataCache _notification_service_data_cache;
readonly OrdersModel _model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly UserSettingsHub _settings_hub;
readonly OrderBookConfig _config;
@@ -29,6 +32,7 @@ namespace bts.shell {
INotificationServiceDataCache notification_service_data_cache,
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
UserSettingsHub settings_hub) : base(owner, "SparkOrderBookWindow") {
var raw_config = Configuration.get<bts.config.OrderBookOptions>();
_config = new OrderBookConfig(raw_config.can_edit_specific_algo_params);
@@ -37,6 +41,7 @@ namespace bts.shell {
_notification_service_data_cache = notification_service_data_cache;
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_settings_hub = settings_hub;
_dispose = bus.subscribe(SparkTags.ShowOrderBookTag).OnDispatcher().Subscribe(show);
}
@@ -45,8 +50,17 @@ namespace bts.shell {
var settings_manager = new WindowSettingsManager<OrderBookGridSettings>(_settings_hub, state.grid_settings_wrapper(),
us => us.order_book_grid ?? OrderBookStartupData.DefaultGrid,
(us, s) => us.with(order_book_grid: s));
var w = new OrderBookWindow(_model, _position_model, this, _bus, _notification_service, state,
SparkCommands.ShowOrders.icon, settings_manager.as_non_shared(), _config.can_edit_specific_algo_params);
var w = new OrderBookWindow(
_model,
_position_model,
_sec_meta_store,
this,
_bus,
_notification_service,
state,
SparkCommands.ShowOrders.icon,
settings_manager.as_non_shared(),
_config.can_edit_specific_algo_params);
return Task.FromResult<IShellWindow>(w);
}
@@ -0,0 +1,273 @@
namespace mbts.spark {
using bts;
using bts.api;
using bts.api.orderman;
using bts.collections;
using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using Spark.ViewModel.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using CompositeDisposable = System.Reactive.Disposables.CompositeDisposable;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
class OrderParamsVM : DisposableViewModelBase {
readonly OrdersModel _model;
readonly OrderParamsAggregator _selected_params_mon;
readonly SelectorProperty<AccountTuple, AccountTuple?> _accounts;
readonly Property<bool> _is_dirty;
readonly Func<SecurityImmutable?, double> _get_display_qty_divisor;
IRaiseCanExecuteChangedCommand _payup_bid_cmd;
IRaiseCanExecuteChangedCommand _payup_ask_cmd;
IAlgoParamVM<double> _price_param;
AlgoParamVM<double?> _quantity_param;
AlgoParamPermissions _price_permissions =
AlgoParamPermissions.ReadOnly | AlgoParamPermissions.Write;
AlgoParamPermissions _quantity_permissions =
AlgoParamPermissions.ReadOnly | AlgoParamPermissions.Write;
SecurityMD? _security_md;
public OrderParamsVM(
OrdersModel model,
OrderParamsAggregator selected_params_mon,
AlgoEditingPermissions init_permissions,
Func<SecurityImmutable?, double> get_display_qty_divisor
) {
_model = model;
_selected_params_mon = selected_params_mon;
_get_display_qty_divisor = get_display_qty_divisor;
algo_vm = AlgoDefinitionVM.create(
model,
AlgoData.create_unpersisted(
OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(
CustomOrderDefinition.CustomOneofCase.Iceberg),
CustomOrderDefinition.CustomOneofCase.Iceberg.display_name()),
editing_permissions: init_permissions);
// accounts
_accounts = new SelectorProperty<AccountTuple, AccountTuple?>(this,
nameof(selected_account),
a => new AccountTuple?(a),
() => accounts.Cast<AccountTuple?>().FirstOrDefault(),
EqualityComparer<AccountTuple?>.Default,
Array.Empty<PropertyValidation<AccountTuple?>>());
attach(
_accounts,
_model.factory.subscribe_account_tuples(),
_model.admin_model.on_account_tuples
.Where(ts => ts.Count > 0)
.Select(ts => new InlineUserProperty<AccountTuple>(ts[0])).Take(1));
bbo = new BBOVM { security_md = security_md };
_payup_bid_cmd = new Command<int>(payup_bid, payup_can_execute);
_payup_ask_cmd = new Command<int>(payup_ask, payup_can_execute);
var algo_param_rows = new ObservableAggregateCollection<AlgoParamRowVM>();
var appended_param_rows = new ObservableAppendCollection<AlgoParamRowVM>(algo_param_rows);
param_rows = appended_param_rows;
var dirty_params_mon = new ReactiveThresholdMonitor<AlgoParamRowVM>(r => r.param.subscribe_is_dirty());
_is_dirty = backing(nameof(is_dirty), dirty_params_mon);
_dispose = new CompositeDisposable(bbo, algo_vm,
AlgoParamRowsHelper.connect(algo_vm, algo_param_rows, false),
algo_vm.observe_algo_root().Subscribe(on_algo_root_changed),
ObservableAutoWrapper.connect_item_hooks(param_rows, dirty_params_mon.join),
algo_vm);
// payup methods
void payup_bid(int ticks) => payup(bbo.bid, -ticks);
void payup_ask(int ticks) => payup(bbo.ask, ticks);
void payup(double from_price, int ticks) {
if (spec.HasValue && _selected_params_mon.all_active)
price = spec.Value.tickup(from_price, ticks);
}
bool payup_can_execute(int ticks) => spec.HasValue && _selected_params_mon.all_active;
void on_algo_root_changed(IAlgoVM root) {
appended_param_rows.clear_front();
if (root is null) {
_price_param = null;
_quantity_param = null;
return;
}
_quantity_param = new(
"size", "Size", _selected_params_mon.size, EqualityComparer<double?>.Default,
to_display_value: v => v.HasValue ? v.Value / display_quantity_divisor : v,
from_display_value: v => v.HasValue ? v.Value * display_quantity_divisor : v
) {
permissions = _quantity_permissions & _param_permissions,
tick_up_cmd = new Command(() => tick_qty(1)),
tick_down_cmd = new Command(() => tick_qty(-1))
};
_quantity_param.has_value = is_qty_valid(_quantity_param.value);
_quantity_param.value_changed += on_qty_changed;
var price_param = new AlgoParamVM<double>(
"price",
"Price",
_selected_params_mon.price,
spec?.tick_equality_comparer() ?? MathUtils.epsilon_eq_comparer) {
permissions = _price_permissions & _param_permissions
};
_price_param = price_param;
_price_param.value_changed += on_price_changed;
appended_param_rows.insert_front(
new(root, _quantity_param, null, AlgoParamTemplateKeys.Size));
appended_param_rows.insert_front(
new(root, _price_param, null, AlgoParamTemplateKeys.Price));
static bool is_qty_valid(double? qty) =>
qty?.is_real_non_negative() ?? false;
void on_qty_changed(double? oldval, double? newval) =>
_quantity_param.has_value = is_qty_valid(newval);
void tick_qty(int count) {
if (_quantity_param is null
|| !_quantity_param.has_value
|| !(quantity_display?.HasTickFactors ?? false)) {
return;
}
_quantity_param.value = quantity_display.Value.tick(
_quantity_param.value ?? 0D, count);
}
void on_price_changed(double oldval, double newval) =>
price_param.has_value = !double.IsNaN(newval);
}
}
public bool is_dirty => _is_dirty.Value;
public AlgoParamPermissions price_permissions {
get => _price_permissions;
set => _assign_param_permissions(_price_param, ref _price_permissions, value);
}
public AlgoParamPermissions quantity_permissions {
get => _quantity_permissions;
set => _assign_param_permissions(_quantity_param, ref _quantity_permissions, value);
}
public ReadOnlyObservableCollection<AccountTuple> accounts => _accounts.items;
public AccountTuple? selected_account {
get => _accounts.selected_item;
set => _accounts.selected_item = value;
}
public SecurityImmutable? security => _selected_params_mon.security;
/// <see cref="security_md"/> should be synced with the root of the selected row(s),
public SecurityMD? security_md {
get => _security_md;
set {
if (_security_md == value) {
return;
}
using var _ = detect_property_changes(
nameof(spec),
nameof(display_quantity_divisor),
nameof(quantity_display),
nameof(unit_quantity));
_security_md = value;
bbo.security_md = value;
_payup_bid_cmd.RaiseCanExecuteChanged();
_payup_ask_cmd.RaiseCanExecuteChanged();
_quantity_param?.refresh_display_value();
RaisePropertyChanged(nameof(security_md), nameof(security));
}
}
public ContractSpecificationImmutable? spec => security?.ContractSpec;
public TickDisplaySettingsImmutable? quantity_display =>
security_md?.quantity_display;
public double price {
get => _price_param?.value ?? double.NaN;
set {
if (_price_param != null)
_price_param.value = value;
}
}
public double? quantity {
get => _quantity_param?.value;
set {
if (_quantity_param != null)
_quantity_param.value = value;
}
}
public double unit_quantity =>
(security?.ContractSpec)?.tick_factors()?.tick_unit_frac() ?? 1;
public AlgoDefinitionVM algo_vm { get; }
public IReadOnlyObservableCollection<AlgoParamRowVM> param_rows { get; }
public BBOVM bbo { get; }
public double display_quantity_divisor => _get_display_qty_divisor(security);
public ICommand send_order { get; }
public ICommand payup_bid_cmd => _payup_bid_cmd;
public ICommand payup_ask_cmd => _payup_ask_cmd;
AlgoParamPermissions _param_permissions =>
_selected_params_mon.all_active ?
AlgoParamPermissions.ReadWrite : AlgoParamPermissions.ReadOnly;
AlgoEditingPermissions _algo_permissions =>
_selected_params_mon.all_active ?
AlgoEditingPermissions.AllowEditValues : AlgoEditingPermissions.None;
public void on_common_price(double price) {
if (_price_param is null) {
return;
}
_price_param.value = price;
_price_param.mark_committed();
}
public void on_common_size(double? size) {
if (_quantity_param is null) {
return;
}
_quantity_param.value = size;
_quantity_param.mark_committed();
}
public void on_all_active_changed() {
algo_vm.editing_permissions_mask = _algo_permissions;
if (!_selected_params_mon.all_active)
revert();
}
public void revert() =>
param_rows.revert_all();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
void _assign_param_permissions<T>(
IAlgoParamVM<T> param,
ref AlgoParamPermissions permissions_backing,
AlgoParamPermissions permissions) {
if (permissions_backing == permissions) {
return;
}
permissions_backing = permissions;
if (param is not null) {
param.permissions = permissions & _param_permissions;
}
}
}
}
@@ -42,7 +42,7 @@ namespace bts.shell.orderbook {
[ProtoMember(11)]
public DoubleMinMaxState price;
[ProtoMember(12)]
public UIntMinMaxState qty_filled;
public DoubleMinMaxState qty_filled;
[ProtoMember(13)]
public DoubleMinMaxState avg_price;
[ProtoMember(14)]
@@ -148,7 +148,7 @@ namespace bts.shell.orderbook {
// numeric
pb.add_numeric(fs.qty, o => o.order.order.quantity());
pb.add_price(fs.price, o => o.order.order.ui_price(), o => o.order.security);
pb.add_numeric(fs.qty_filled, o => o.order.order.filled());
pb.add_numeric(fs.qty_filled, o => o.order.order.filled_quantity());
pb.add_numeric(fs.avg_price, o => o.order.order.avg_price());
pb.add_numeric(fs.last_price, o => o.order.order.last_price());
pb.add_numeric(fs.piq, o => o.order.piq ?? uint.MaxValue);
@@ -8,6 +8,8 @@ using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.utility;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -40,6 +42,7 @@ namespace bts.shell.orderbook {
IBus bus,
INotificationService notification_service,
OrdersModel model,
ISecurityMetadataStore sec_meta_store,
IEnumerable<OrderBookRowVM> rows,
ObservableCollection<DIYGrid.ColumnBase> columns) {
core_manager = new GridSettingsManager<OrderBookRowVM, OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings>(
@@ -58,8 +61,8 @@ namespace bts.shell.orderbook {
return pvm;
},
(gen, anims) => new OrderBookGridSettings(gen, anims.empty_if_null().Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_data, a.cell_animations, a.row_animations, a.sound_notifications))) { algo_tree_display_mode = _algo_tree_display_mode },
p => p.create_predicate(notification_service.data_cache),
p => p.create_notification_predicate(notification_service.data_cache),
p => p.create_predicate(notification_service.data_cache, sec_meta_store),
p => p.create_notification_predicate(notification_service.data_cache, sec_meta_store),
notification_service == null ? new Func<IPredicate<OrderSecurity>, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order,
notification_service == null ? new Func<INotificationPredicate<OrderSecurity>, IDisposable>(t => Disposable.empty) : notification_service.link_to_order,
hard_column_flags);
@@ -22,8 +22,6 @@ using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using OrderParamsVM = mbts.spark.OrderBookVM.OrderParamsVM;
namespace mbts.spark {
internal partial class OrderBookView : UserControl {
public const double
@@ -186,7 +186,7 @@ namespace bts.shell.pnl {
public double display_top_volume =>
data.Count > 0 ?
data.Values.First().Values.Sum(o => o.qty_conversion
.convert_numeric_type<int>()
.convert_numeric_type<double>()
.to_display(o.order.working_quantity())) :
0;
@@ -195,7 +195,7 @@ namespace bts.shell.pnl {
public WorkingOrderSideData Add(
OrderRecordImmutable order_record, QuantityConversionData<double> qty_conversion) {
int working_qty = order_record.working_quantity();
var working_qty = order_record.working_quantity();
if (working_qty <= 0)
throw new ArgumentException(nameof(working_qty));
uint order = order_record.Key;
@@ -19,6 +19,8 @@ namespace bts.shell {
using mbts.ui.spark;
using mbts.ui.utility;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -44,12 +46,20 @@ namespace bts.shell {
readonly PNLConfig _pnl_conf;
readonly IShellWindowThreadIDProvider _thread_id_provider;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model, IPositionModel position_model) : base(owner, _window_type) {
public PNLWindowFactory(
IShellModule owner,
IBus bus,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) : base(owner, _window_type) {
_bus = bus;
_orders_model = orders_model;
_settings_hub = settings_hub;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_pnl_conf = new PNLConfig(Configuration.get<bts.config.PNLOptions>());
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().pnl);
_dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show);
@@ -85,7 +95,7 @@ namespace bts.shell {
menu_display_vm.load_from(init_settings.menu_display);
on_parent_view_created_impl = menu_display_vm.safe_bind_to_view;
var vm = new PNLVM(
_bus, _orders_model, _position_model, init_settings);
_bus, _orders_model, _position_model, _sec_meta_store, init_settings);
var content = new PNLView {
DataContext = vm
};
@@ -18,6 +18,7 @@
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
@@ -48,6 +49,7 @@
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IObservableCollectionAddRemoveOnly<PNLRowVM> _selected_rows = new ObservableSortedCollection<PNLRowVM>(PNLRowVM.key_comparer);
/// treat <see cref="_rows_data_wrapper"/> and <see cref="_rows_key_wrapper"/>
/// as IReadOnlyLists - don't call any mutation methods.
@@ -84,10 +86,12 @@
IBus bus,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
PNLSettings settings) {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_rows_data_wrapper = rows.WrapSelector(r => r.data, null);
_rows_key_wrapper = rows.WrapSelector(r => r.key, null);
_rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers);
@@ -726,8 +730,8 @@
state.orderbook_grid.general = GridSettingsHelper.hide_cols(state.orderbook_grid.general, hide_counterparts);
var settings_man = new WindowSettingsManager<orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, _position_model, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, orders_source, settings_man, true);
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, orders_source, settings_man, true);
foreach (var c in OrderBookVM.OrderBookColumnCollection.editable_columns)
obvm.columns.Insert(0, c);
obvm.load_from(state);
@@ -6,6 +6,8 @@ namespace Spark.Trading {
using bts.api.position;
using bts.utils;
using mbts.utils;
using Spark.Api.Position;
using System;
@@ -122,8 +124,35 @@ namespace Spark.Trading {
public static double sys_price(this ReconcileReportRowData rd) =>
rd.sys_position?.total_net_avg_price() ?? double.NaN;
public static bool has_exch_position(this ReconcileReportRowData rd) =>
(rd.exch_position?.Position).is_real_non_zero();
public static bool has_sys_position(this ReconcileReportRowData rd) =>
(rd.sys_position?.total_pos()).is_real_non_zero();
public static bool is_match(this ReconcileReportRowData rd) =>
rd.sys_quantity().epsilon_equals(rd.exch_quantity()) &&
rd.sys_price().epsilon_equals(rd.exch_price());
rd.match_type() ==
(ReconcileReportMatchType.Quantity | ReconcileReportMatchType.Price);
/// <summary>
/// Determines which components of the system/exchange positions (if any) match. If both
/// positions are undefined (i.e., the quantity is finite positive), then the position is
/// considered a proper match, and both the 'price' and 'quantity' flags are returned.
/// </summary>
public static ReconcileReportMatchType match_type(this ReconcileReportRowData rd) {
if (!rd.has_exch_position() && !rd.has_sys_position()) {
return ReconcileReportMatchType.Price | ReconcileReportMatchType.Quantity;
}
var mt = ReconcileReportMatchType.None;
// allow for rounding error
if (rd.sys_quantity().epsilon_equals(rd.exch_quantity())) {
mt |= ReconcileReportMatchType.Quantity;
}
if (rd.sys_price().epsilon_equals(rd.exch_price())) {
mt |= ReconcileReportMatchType.Price;
}
return mt;
}
}
}
@@ -55,18 +55,7 @@ namespace Spark.Trading {
public double exchange_quantity => _data.exch_quantity();
public double price => _data.sys_price();
public double exchange_price => _data.exch_price();
public ReconcileReportMatchType match_type {
get {
var mt = ReconcileReportMatchType.None;
if (quantity.epsilon_equals(exchange_quantity)) {
mt |= ReconcileReportMatchType.Quantity;
}
if (price.epsilon_equals(exchange_price)) {
mt |= ReconcileReportMatchType.Price;
}
return mt;
}
}
public ReconcileReportMatchType match_type => _data.match_type();
public bts.api.domain.TickDisplaySettingsImmutable quantity_display {
get => _quantity_display;
@@ -79,7 +68,7 @@ namespace Spark.Trading {
}
public bool is_match =>
quantity.epsilon_equals(exchange_quantity) && price.epsilon_equals(exchange_price);
_data.is_match();
public bool has_system_position => _data.sys_position.HasValue;
public bool has_exchange_position => _data.exch_position.HasValue;
@@ -36,10 +36,13 @@ namespace Spark.Trading {
rv.sorting_criteria.AddRange(
new(nameof(ColKey.Security), true),
new(nameof(ColKey.Account), true));
rv.grid = GridSettings.Default.with(columns: DefaultColumns.all);
rv.grid = default_grid_settings;
return rv;
}
public static GridSettings default_grid_settings =>
GridSettings.Default.with(columns: DefaultColumns.all);
public IList<SortingCriteria> sorting_criteria =>
_sorting_criteria ??= new(1);
@@ -48,12 +48,22 @@
/// as they are responsible for launching windows in response to a SparkTag being published to the bus.
/// The tags may be published by anything (i.e., not just the spark commands in <see cref="actions"/>).
_window_factories = new() {
new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, position_model, mbo),
new OrderBookWindowFactory(this, bus, notification_service, notification_service_data_cache, orders_model, position_model, settings_hub),
new LadderWindowFactory(
this, bus, wm, settings_hub, orders_model, position_model, security_metadata, mbo),
new OrderBookWindowFactory(
this,
bus,
notification_service,
notification_service_data_cache,
orders_model,
position_model,
security_metadata,
settings_hub),
new FillsWindowFactory(this, bus, settings_hub, orders_model),
new PNLWindowFactory(this, bus, settings_hub, orders_model, position_model),
new PNLWindowFactory(
this, bus, settings_hub, orders_model, position_model, security_metadata),
new AlgoStudioWindowFactory(this, bus, orders_model, error_reporter),
new ManualFillsWindowFactory(this, bus, orders_model),
new ManualFillsWindowFactory(this, bus, orders_model, security_metadata),
new ReconcileReportWindowFactory(
this, bus, settings_hub, position_model, security_metadata, user.Value),
};
@@ -99,6 +99,7 @@
this._toolstripseperator_zoom = new System.Windows.Forms.ToolStripSeparator();
this._toolstripmenuitem_sheet_settings_window = new System.Windows.Forms.ToolStripMenuItem();
this._statusbar_toolstripstatus_security = new System.Windows.Forms.ToolStripStatusLabel();
this._statusbar_vs_dropdown = new System.Windows.Forms.ToolStripComboBox();
this._statusbar_toolstripstatus_column = new System.Windows.Forms.ToolStripStatusLabel();
this._statustrip_main = new System.Windows.Forms.StatusStrip();
this._statusbar_toolstripstatus_task = new System.Windows.Forms.ToolStripStatusLabel();
@@ -716,6 +717,15 @@
this._statusbar_toolstripstatus_security.Size = new System.Drawing.Size(49, 17);
this._statusbar_toolstripstatus_security.Text = "Contract";
this._statusbar_toolstripstatus_security.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// _statusbar_vs_dropdown
//
this._statusbar_vs_dropdown.Font = new System.Drawing.Font("Tahoma", 8F);
this._statusbar_vs_dropdown.Name = "_statusbar_vs_dropdown";
this._statusbar_vs_dropdown.Size = new System.Drawing.Size(49, 17);
this._statusbar_vs_dropdown.Enabled = false;
this._statusbar_vs_dropdown.Text = "Vol Time";
this._statusbar_vs_dropdown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// _statusbar_toolstripstatus_column
//
@@ -731,6 +741,7 @@
this._statustrip_main.GripMargin = new System.Windows.Forms.Padding(0);
this._statustrip_main.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this._statustrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this._statusbar_vs_dropdown,
this._statusbar_toolstripstatus_security,
this._statusbar_toolstripstatus_task,
this._statusbar_toolstripstatus_quoterdata,
@@ -830,6 +841,9 @@
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_edgesize;
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_midprice;
private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_security;
private System.Windows.Forms.ToolStripComboBox _statusbar_vs_dropdown;
private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_column;
private System.Windows.Forms.StatusStrip _statustrip_main;
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_sheet_column_settings;
+1 -1
View File
@@ -90,7 +90,7 @@ namespace mbts.ui {
break;
case ToastNotificationSettings.Mode.Flash:
_toast_notifications_enabled = true;
_toast_controller.flash_duration = s.notification.toast_notification.duration ?? _fallback_flash_duration;
_toast_controller.flash_duration = s.notification.toast_notification.duration;
break;
case ToastNotificationSettings.Mode.ManualClose:
_toast_notifications_enabled = true;
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.domain;
using bts.api.orderman;
using bts.spark;
using bts.utils;
@@ -65,11 +66,15 @@ namespace bts.shell {
public static IToastNotification order_filled(OrderSecurity oldval, OrderSecurity newval) =>
new OrderFilledToastNotification(oldval.order, newval.order, newval.security);
public static IToastNotification order_completed(OrderRecordImmutable order, SecurityImmutable? security) =>
new OrderCompletedToastNotification(order, security);
public static IToastNotification order_completed(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) =>
new OrderCompletedToastNotification(order, security, qty_display);
public static IToastNotification order_completed(OrderSecurity order) =>
new OrderCompletedToastNotification(order.order, order.security);
public static IToastNotification order_completed(
OrderSecurity order, TickDisplaySettingsImmutable qty_display) =>
new OrderCompletedToastNotification(order.order, order.security, qty_display);
public static IToastNotification order_status_changed(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) =>
new OrderStatusChangeToastNotification(key, old_status, new_status, security);
@@ -145,13 +150,19 @@ namespace bts.shell {
class OrderCompletedToastNotification : ToastNotificationBase, IEquatable<OrderCompletedToastNotification> {
readonly OrderRecordImmutable _order;
readonly SecurityImmutable? _security;
readonly TickDisplaySettingsImmutable _qty_display;
public OrderCompletedToastNotification(OrderRecordImmutable order, SecurityImmutable? security) {
public OrderCompletedToastNotification(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) {
_order = order;
_security = security;
_qty_display = qty_display;
}
public override string text => OrderActivitySummarizer.order_completion_debrief(_order, _security);
public override string text => OrderActivitySummarizer.order_completion_debrief(
_order, _security, _qty_display);
public override ImageSource content_icon => Icons.OrderCompleted;
public bool Equals(OrderCompletedToastNotification other) =>
@@ -185,18 +196,18 @@ namespace bts.shell {
other != null &&
_security.HasValue == other._security.HasValue &&
_newval.Key == other._newval.Key &&
_newval.filled() == other._newval.filled() &&
_newval.filled_quantity().Equals(other._newval.filled_quantity()) &&
_newval.quantity() == other._newval.quantity() &&
_oldval.filled() == other._oldval.filled();
_oldval.filled_quantity().Equals(other._oldval.filled_quantity());
public override bool Equals(object obj) => Equals(obj as OrderFilledToastNotification);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
(int)_newval.Key,
(int)_newval.filled(),
(int)_newval.quantity(),
(int)_oldval.filled());
HashCode.Combine(
_newval.Key,
_newval.filled_quantity(),
_newval.quantity(),
_oldval.filled_quantity());
public override string ToString() => text;
}
+15
View File
@@ -6,15 +6,19 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace mbts.spark {
class AlgoParamVM<T> : IAlgoParamVM<T>, INotifyPropertyChanged, ITemplateSelectorKey {
readonly IEqualityComparer<T> _comparer;
readonly string _template_key;
readonly Func<T, T> _to_display_value, _from_display_value;
AlgoParamPermissions _permissions;
bool _is_enabled, _has_value;
T _committed_value, _value;
ICommand _tick_up_cmd;
ICommand _tick_down_cmd;
public AlgoParamVM(string id, string display_name)
: this(id, display_name, default, EqualityComparer<T>.Default) { }
@@ -61,6 +65,17 @@ namespace mbts.spark {
public bool is_enabled { get => _is_enabled; set => _set(ref _is_enabled, value); }
public bool has_value { get => _has_value; set => _set(ref _has_value, value); }
public bool is_dirty { get; private set; }
public ICommand tick_up_cmd {
get => _tick_up_cmd;
set => _set(ref _tick_up_cmd, value);
}
public ICommand tick_down_cmd {
get => _tick_down_cmd;
set => _set(ref _tick_down_cmd, value);
}
object IAlgoParamVM.value { get => value; set => this.value = (T)value; }
object IAlgoParamVM.display_value { get => display_value; set => display_value = (T)value; }
@@ -8,6 +8,8 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -17,12 +19,15 @@ namespace mbts {
public static Dictionary<OrderCompletedEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderCompletedEventPredicate>> get_oneofs(IBus bus) =>
new Dictionary<OrderCompletedEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderCompletedEventPredicate>> {
{ OrderCompletedEventPredicate.PredicateTypeOneofCase.AnyOrder, PredicateVMWrapper.create<OrderCompletedEventPredicate>(p => p.security = null) },
{ OrderCompletedEventPredicate.PredicateTypeOneofCase.SecurityOrder, SecurityCriteriaVMFactory.create<OrderCompletedEventPredicate>(bus, o => o.security?.is_value ?? new SecurityCriteria(),
(p, s) => {
if (p.security == null)
p.security = new SecurityPredicate();
p.security.is_value = s;
})
{
OrderCompletedEventPredicate.PredicateTypeOneofCase.SecurityOrder,
SecurityCriteriaVMFactory.create<OrderCompletedEventPredicate>(
bus, o => o.security?.is_value ?? new SecurityCriteria(),
(p, s) => {
if (p.security == null)
p.security = new SecurityPredicate();
p.security.is_value = s;
})
}
};
}
@@ -53,8 +58,9 @@ namespace mbts {
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Completed, security, data_cache);
public INotificationPredicate<OrderSecurity> create_toast(INotificationServiceDataCache data_cache) =>
new MyToaster(security?.create(), data_cache);
public INotificationPredicate<OrderSecurity> create_toast(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) =>
new MyToaster(security?.create(), data_cache, sec_meta_store);
public bool Equals(OrderCompletedEventPredicate other) => other != null && other.security.safe_equals(other.security);
public override bool Equals(object obj) => Equals(obj as OrderCompletedEventPredicate);
@@ -66,15 +72,28 @@ namespace mbts {
class MyToaster : INotificationPredicate<OrderSecurity>, IEquatable<MyToaster> {
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
readonly ISecurityMetadataStore _sec_meta_store;
public MyToaster(IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) {
public MyToaster(
IPredicate<SecurityImmutable> security_predicate,
INotificationServiceDataCache data_cache,
ISecurityMetadataStore sec_meta_store) {
_security_predicate = security_predicate;
_data_cache = data_cache;
_sec_meta_store = sec_meta_store;
}
public IToastNotification trigger(OrderSecurity order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache) ?
ToastNotifications.order_completed(order) : ToastNotifications.empty;
public IToastNotification trigger(OrderSecurity order) {
if (!OrderEventPredicateHelper.check_order_transition_predicate(
order, _is_completed, _security_predicate, _data_cache)) {
return ToastNotifications.empty;
}
var sec = order.security;
var sec_meta = sec.HasValue ? _sec_meta_store.get(sec.Value) : null;
var qty_display = sec_meta?.QuantityDisplay ??
SecurityDataHelper.Defaults.quantity_display_settingsi;
return ToastNotifications.order_completed(order, qty_display);
}
bool IPredicate<OrderSecurity>.trigger(OrderSecurity order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache);
@@ -78,10 +78,10 @@
public (OrderSecurity oldval, OrderSecurity newval)? get_filled_order_args(OrderSecurity ort) {
if (ort.order.is_exchange_order() && OrderEventPredicateHelper.check_security_predicate(ort, _security_predicate)) {
if (_data_cache.get_previous_order_state(ort.order.Key) is var oldval && oldval.HasValue) {
if (ort.order.filled() > oldval?.order.filled()) {
if (ort.order.filled_quantity() > oldval?.order.filled_quantity()) {
return (oldval.Value, ort);
}
} else if (!_data_cache.is_first_order_update && ort.order.filled() > 0) {
} else if (!_data_cache.is_first_order_update && ort.order.filled_quantity() > 0) {
// old order will be a copy of new order, except with filledQuantity set to 0
var old_state = ort.order.State.CloneToMutable();
old_state.FilledQuantity = 0;
@@ -9,6 +9,8 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
@@ -64,8 +66,11 @@ namespace mbts {
class OrderRecordTuplePredicate : IEquatable<OrderRecordTuplePredicate> {
SecurityPredicate _security;
SidePredicate _side;
DoublePredicate _price, _last_price, _avg_price;
UIntPredicate _filled_quantity, _security_key, _order_key, _parent_key, _attached_target_order_key;
DoublePredicate _price;
DoublePredicate _last_price;
DoublePredicate _avg_price;
DoublePredicate _filled_quantity;
UIntPredicate _security_key, _order_key, _parent_key, _attached_target_order_key;
DoublePredicate _quantity;
OrderStatusPredicate _order_status;
OrderTypePredicate _order_type;
@@ -155,7 +160,7 @@ namespace mbts {
[ProtoMember(10)]
public DoublePredicate quantity { get => _quantity; set => _set(ref _quantity, value); }
[ProtoMember(11)]
public UIntPredicate filled_quantity { get => _filled_quantity; set => _set(ref _filled_quantity, value); }
public DoublePredicate filled_quantity { get => _filled_quantity; set => _set(ref _filled_quantity, value); }
[ProtoMember(12)]
public DoublePredicate last_price { get => _last_price; set => _set(ref _last_price, value); }
[ProtoMember(13)]
@@ -218,7 +223,8 @@ namespace mbts {
}
}
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) {
public IPredicate<OrderSecurity> create_predicate(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) {
switch (predicate_type_case) {
case PTOC.Security: return wrap(_security.create(), r => r.security ?? SecurityDataHelper.Defaults.SecurityImmutable);
case PTOC.Time: return wrap(_time_created.create(), r => r.order.created());
@@ -232,7 +238,7 @@ namespace mbts {
case PTOC.Side: return wrap(_side.create(), r => r.order.side());
case PTOC.Size: return wrap(_quantity.create(), r => r.order.quantity());
case PTOC.Price: return wrap(_price.create(), r => r.order.price());
case PTOC.Filled: return wrap(_filled_quantity.create(), r => r.order.filled());
case PTOC.Filled: return wrap(_filled_quantity.create(), r => r.order.filled_quantity());
case PTOC.AvgFilled: return wrap(_avg_price.create(), r => r.order.avg_price());
case PTOC.LastPrice: return wrap(_last_price.create(), r => r.order.last_price());
case PTOC.Status: return wrap(_order_status.create(), r => r.order.status());
@@ -252,15 +258,18 @@ namespace mbts {
trigger.wrap<OrderSecurity, T>(select);
}
public INotificationPredicate<OrderSecurity> create_notification_predicate(INotificationServiceDataCache notification_service_data_cache) {
public INotificationPredicate<OrderSecurity> create_notification_predicate(
INotificationServiceDataCache notification_service_data_cache,
ISecurityMetadataStore sec_meta_store) {
if (!is_toast_enabled)
return null;
switch (predicate_type_case) {
case PTOC.FilledEvent: return _filled_event.create_toast(notification_service_data_cache);
case PTOC.CompletedEvent: return _completed_event.create_toast(notification_service_data_cache);
case PTOC.CanceledEvent: return _canceled_event.create_toast(notification_service_data_cache);
default: return null;
}
return predicate_type_case switch {
PTOC.FilledEvent => _filled_event.create_toast(notification_service_data_cache),
PTOC.CompletedEvent => _completed_event.create_toast(
notification_service_data_cache, sec_meta_store),
PTOC.CanceledEvent => _canceled_event.create_toast(notification_service_data_cache),
_ => null,
};
}
public bool Equals(OrderRecordTuplePredicate other) {
+2 -2
View File
@@ -11,7 +11,7 @@ namespace mbts {
SecurityExpiration security_expiration,
double? strike,
PutOrCall? call_put,
int size,
double size,
double price,
double theo,
string account,
@@ -47,7 +47,7 @@ namespace mbts {
public SecurityExpiration? security_expiration { get; }
public SecurityStrike? security_strike { get; }
public PutOrCall? call_put { get; }
public int size { get; }
public double size { get; }
public double price { get; }
public double theo { get; }
public string account { get; }
+1 -1
View File
@@ -15,7 +15,7 @@ namespace mbts {
SecurityExpiration? security_expiration { get; }
SecurityStrike? security_strike { get; }
PutOrCall? call_put { get; }
int size { get; }
double size { get; }
double price { get; }
double theo { get; }
string account { get; }
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more